@cline/core 0.0.64 → 0.0.65

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.
@@ -1,7 +1,7 @@
1
- import{createRequire as vf}from"node:module";var{defineProperty:S7,getOwnPropertyNames:xf}=Object;var oY=Object.prototype.hasOwnProperty;function sY($){return this[$]}var M=($,W,Z)=>{var Q=xf(W);for(let J of Q)if(!oY.call($,J)&&J!=="default")S7($,J,{get:sY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!oY.call(Z,J)&&J!=="default")S7(Z,J,{get:sY.bind(W,J),enumerable:!0});return Z}};var gf=($)=>$;function mf($,W){this[$]=gf.bind(null,W)}var w=($,W)=>{for(var Z in W)S7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:mf.bind(W,Z)})};var Z2=($,W)=>()=>($&&(W=$($=0)),W);var tY=vf(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as df,captureAgentUnexpectedReasoningTokens as WV,SDK_ERROR_TELEMETRY_EVENT as lf}from"@cline/shared";function n($,W,Z){$?.capture({event:W,properties:Z})}function rW($){if(!$)return;return $.substring(0,pf)}function rf($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function nf($){return typeof $==="string"?$:$.message}function $V($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function ZV($){n($,v.CLIENT.EXTENSION_ACTIVATED)}function iW($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:$V(Z,new Set(["git"])),has_mercurial:$V(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;n($,v.WORKSPACE.INITIALIZED,Q)}function nW($,W,Z){n($,v.WORKSPACE.INIT_ERROR,{error_type:rf(W),error_message:rW(nf(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function QV($,W){n($,v.WORKSPACE.PATH_RESOLVED,{...W})}function m1($,W){n($,v.USER.AUTH_STARTED,{provider:W})}function v1($,W){n($,v.USER.AUTH_SUCCEEDED,{provider:W})}function c1($,W,Z){n($,v.USER.AUTH_FAILED,{provider:W,errorMessage:rW(Z)})}function D$($,W,Z,Q){n($,v.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function h7($,W,Z){n($,v.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function JV($,W){n($,v.USER.PROVIDER_CONFIGURED,{provider:W})}function jV($,W){$?.captureRequired(v.USER.TELEMETRY_OPT_OUT,W)}function H1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function aW($,W){n($,v.TASK.CREATED,W)}function oW($,W){n($,v.TASK.RESTARTED,W)}function $4($,W){n($,v.TASK.COMPLETED,W)}function D8($,W){n($,v.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function sW($,W){n($,v.TASK.TOKEN_USAGE,W)}function tW($,W,Z){n($,v.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function _8($,W){n($,v.TASK.TOOL_USED,W)}function eW($,W){n($,v.TASK.SKILL_USED,W)}function $9($,W){n($,v.TASK.DIFF_EDIT_FAILED,W)}function W4($,W){n($,v.TASK.PROVIDER_API_ERROR,{...W,errorMessage:rW(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function W9($,W){n($,v.TASK.MISTAKE_LIMIT_REACHED,{...W,timestamp:new Date().toISOString()})}function XV($,W){n($,v.SDK.TOOL_TIMEOUT,af(W))}function af($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function Z9($,W,Z){n($,v.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function Q9($,W,Z,Q){n($,v.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:rW(Q),timestamp:new Date().toISOString()})}function J9($,W,Z,Q,J){n($,v.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function _$($,W){n($,v.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function j9($,W){n($,v.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function Z4($,W){n($,W.event==="ended"?v.TASK.SUBAGENT_COMPLETED:v.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function X9($,W,Z,Q){n($,v.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function Y9($,W){n($,v.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function V9($,W){n($,v.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function YV($,W){n($,v.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var pf=500,v;var D0=Z2(()=>{v={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:df},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MISTAKE_LIMIT_REACHED:"task.mistake_limit_reached",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:lf,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as vT,readFileSync as cT,statSync as uT,writeFileSync as dT}from"node:fs";import{dirname as lT}from"node:path";import{resolveGlobalSettingsPath as WH}from"@cline/shared/storage";import{z as L2}from"zod";function x9(){return x4.parse({})}function rT(){g9=void 0}function iT($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function nT($){let W;try{W=cT($,"utf8")}catch{return x9()}try{let Z=x4.safeParse(JSON.parse(W));return Z.success?Z.data:x9()}catch{return x9()}}function aT(){let $=WH(),W=uT($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=g9;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=iT(W?nT($):x9());return g9={path:$,mtimeMs:Z,size:Q,value:j},g9}function N0(){return aT().value}function M1($,W={}){let Z=WH(),Q=N0();vT(lT(Z),{recursive:!0});let J=x4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)jV(W.telemetry);dT(Z,`${JSON.stringify(J,null,2)}
2
- `,"utf8"),rT()}function m9(){return N0().telemetryOptOut}function ZH($,W={}){M1({...N0(),telemetryOptOut:$},W)}function QH(){return N0().autoUpdateEnabled}function JH($,W={}){M1({...N0(),autoUpdateEnabled:$},W)}function jH(){return N0().compactionStrategy??"basic"}function XH($){M1({...N0(),compactionStrategy:$})}function R1($){return new Set($??N0().disabledTools??[])}function g4($){return new Set($??N0().disabledPlugins??[])}function YH($){return R1().has($)}function v9($){let W=N0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return M1({...W,disabledTools:[...Z]}),!Q}function _3($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=N0(),J=R1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);M1({...Q,disabledTools:[...J]})}function VH($,W){return _3([$],W),W}function BH($){return g4().has($)}function HH($,W){let Z=$.trim();if(!Z)return;let Q=N0(),J=g4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);M1({...Q,disabledPlugins:[...J]})}function c9($,W){let Z=g4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function n1($,W){let Z=R1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function u9($,W){if(!$||$.length===0)return $;let Z=R1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var $H,pT,x4,g9;var U1=Z2(()=>{D0();$H=L2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,L2.array(L2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),pT=L2.enum(["basic","agentic"]).catch("basic"),x4=L2.object({telemetryOptOut:L2.boolean().default(!1).catch(!1),autoUpdateEnabled:L2.boolean().default(!0).catch(!0),compactionStrategy:pT.optional(),disabledTools:$H.optional(),disabledPlugins:$H.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});var PH={};w(PH,{normalizeUserMessage:()=>oz,buildInitialUserContent:()=>az});async function az($,W,Z,Q){let J=sz(W),j=await ez(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function oz($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
- `)}function sz($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=tz(Z);if(Q)W.push(Q)}return W}function tz($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function ez($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var KF={};w(KF,{updateMcpSettingsFileSync:()=>D1,updateMcpSettingsFile:()=>F6,updateMcpServerOAuthStateAsync:()=>k5,updateMcpServerOAuthState:()=>v2,setMcpServerDisabled:()=>g2,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>Q0,registerMcpServersFromSettingsFile:()=>c2,normalizeMcpServerOAuthState:()=>A6,loadMcpSettingsFile:()=>x2,listMcpServerOAuthStatuses:()=>I5,hasMcpSettingsFile:()=>W$,getMcpServerOAuthState:()=>m2,McpSettingsUpdateSkippedError:()=>K6,McpSettingsMutatorPurityError:()=>g$,McpSettingsLockTimeoutError:()=>m$});import{existsSync as sK,mkdirSync as PJ,readFileSync as tK,renameSync as yJ,rmdirSync as $E,rmSync as SJ,statSync as WE,unlinkSync as eK,writeFileSync as $F}from"node:fs";import{randomUUID as ZE}from"node:crypto";import{dirname as WF,join as oK}from"node:path";import{setTimeout as QE}from"node:timers/promises";import{resolveMcpSettingsPath as JE}from"@cline/shared/storage";import{z as S}from"zod";function bJ($){if(!$)return;if($==="http")return"streamableHttp";return $}function Q0(){return JE()}function UE($,W){PJ(WF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{$F(Z,W,{encoding:"utf8",flag:"wx"}),yJ(Z,$)}catch(Q){try{eK(Z)}catch{}throw Q}}function _E($){Atomics.wait(DE,0,0,$)}function fE($){return`${$}.lock`}function jF(){return`${process.pid}.${Date.now()}.${ZE()}`}function XF($,W){PJ(WF($),{recursive:!0});let Z=`${$}.tmp.${W}`;SJ(Z,{recursive:!0,force:!0}),PJ(Z,{recursive:!0}),$F(oK(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return yJ(Z,$),{lockDir:$,ownerFile:oK($,`owner.${W}`)}}catch(Q){if(SJ(Z,{recursive:!0,force:!0}),sK($))return;throw Q}}function YF($,W){let Z;try{Z=Date.now()-WE($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<kJ)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${jF()}`;try{yJ($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}SJ(Q,{recursive:!0,force:!0})}function LE($){try{eK($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{$E($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function VF($){let W=fE($);if(nZ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:jF()}}function OE($,W){let{lockDir:Z,token:Q}=VF($),J=W.timeoutMs??kJ,j=Date.now();while(!0){let X=XF(Z,Q);if(X)return nZ.add(Z),X;if(Date.now()-j>J)throw new m$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);YF(Z,W),_E(JF)}}async function TE($,W){let{lockDir:Z,token:Q}=VF($),J=W.timeoutMs??kJ,j=Date.now();while(!0){let X=XF(Z,Q);if(X)return nZ.add(Z),X;if(Date.now()-j>J)throw new m$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);YF(Z,W),await QE(JF)}}function BF($,W,Z){try{let Q=zE(W),J=qE(Q,Z);return UE(W,`${JSON.stringify(Q,null,2)}
4
- `),J}finally{nZ.delete($.lockDir),LE($)}}function D1($,W,Z={}){let Q=OE($,Z);return BF(Q,$,W)}async function F6($,W,Z={}){let Q=await TE($,Z);return BF(Q,$,W)}function zE($){let W=RE($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function qE($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new g$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new g$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function ME($){let W=tK($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function RE($){try{return ME($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function HF($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function NE($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function x2($={}){let W=$.filePath??Q0(),Z=tK(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=AE.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function A6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function EE($){if($===void 0)return;let W=hJ.safeParse($);if(!W.success)return;return A6(W.data)}function W$($={}){let W=$.filePath??Q0();return sK(W)}function t0($={}){let W=x2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function g2($){let W=$.filePath??Q0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");D1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=HF(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;NE(j,Z,Y),Q.mcpServers=j})}function m2($,W={}){let Z=x2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return A6(Z.mcpServers[$]?.oauth)}function GF($,W){return(Z)=>{let Q=Z.mcpServers,J=HF(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=EE(J.oauth)??{},X=A6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function v2($,W,Z={}){let Q=Z.filePath??Q0();return D1(Q,GF($,W))}async function k5($,W,Z={}){let Q=Z.filePath??Q0();return F6(Q,GF($,W))}function I5($={}){return t0($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function c2($,W={}){let Z=t0(W);for(let Q of Z)await $.registerServer(Q);return Z}var h5,ZF,hJ,jE,XE,YE,VE,BE,HE,QF,GE,KE,FE,AE,K6,m$,g$,kJ=1e4,JF=25,DE,nZ;var aZ=Z2(()=>{h5=S.record(S.string(),S.string()),ZF=S.record(S.string(),S.unknown()),hJ=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),jE=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:h5.optional()}),XE=S.object({type:S.literal("sse"),url:S.string().url(),headers:h5.optional()}),YE=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:h5.optional()}),VE=S.discriminatedUnion("type",[jE,XE,YE]),BE=S.object({transport:VE,disabled:S.boolean().optional(),metadata:ZF.optional(),oauth:hJ.optional()}),HE=S.enum(["stdio","sse","http","streamableHttp"]).optional(),QF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:HE,disabled:S.boolean().optional(),metadata:ZF.optional(),oauth:hJ.optional()});GE=QF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:h5.optional()}).superRefine(($,W)=>{let Z=$.type??bJ($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),KE=QF.extend({url:S.string().url(),headers:h5.optional()}).superRefine(($,W)=>{let Z=$.type??bJ($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??bJ($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth}}),FE=S.union([BE,GE,KE]),AE=S.object({mcpServers:S.record(S.string(),FE)}).passthrough();K6=class K6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};m$=class m$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};g$=class g$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};DE=new Int32Array(new SharedArrayBuffer(4)),nZ=new Set});import{existsSync as vS,mkdirSync as cS,readFileSync as uS,writeFileSync as dS}from"node:fs";import{resolve as lS}from"node:path";import{resolveSessionDataDir as pS}from"@cline/shared/storage";import{nanoid as rS}from"nanoid";import*as iS from"node-machine-id";function c0($){let W=$?.trim();if(W)return W;let Z=oS();if(Z)return Z;return sS()}function aS(){let $=iS;return $.machineIdSync??$.default?.machineIdSync}function oS(){try{let $=aS();if(!$)return;return $().trim()||void 0}catch{return}}function sS(){let $=pS(),W=lS($,nS);try{if(vS(W)){let Q=uS(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${rS()}`;try{cS($,{recursive:!0}),dS(W,Z,"utf8")}catch{}return Z}var nS="machine-id";var M6=()=>{};class AW{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(Py(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function Py($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class UW{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class v6{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new UW({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var tj=()=>{};import{metrics as Sy,trace as by}from"@opentelemetry/api";import{logs as yy}from"@opentelemetry/api-logs";import{OTLPLogExporter as hy}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as ky}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as Iy}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as xy}from"@opentelemetry/resources";import{BatchLogRecordProcessor as gy,ConsoleLogRecordExporter as my,LoggerProvider as vy}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as cy,MeterProvider as uy,PeriodicExportingMetricReader as dU}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as dy,ConsoleSpanExporter as ly,SimpleSpanProcessor as py}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as ry}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as iy,ATTR_SERVICE_VERSION as ny}from"@opentelemetry/semantic-conventions";class lU{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class c6{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=xy({[iy]:$.serviceName??"cline",...$.serviceVersion?{[ny]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)Sy.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)yy.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return by.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new AW({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new v6({...$,adapters:[W],distinctId:c0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let W=ej(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>sy(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new uy({resource:$,readers:J})}createTracerProvider($){let W=ej(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=oy(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new ry({resource:$,spanProcessors:J})}createLoggerProvider($){let W=ej(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=ay(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new gy(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new vy({resource:$,processors:Z})}}function DW($){let W=new c6($),Z=W.createTelemetryService($);return Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:W,telemetry:Z}}function H$($){if(m9())return{telemetry:new lU($)};if($.enabled!==!0)return{telemetry:new v6({...$,distinctId:c0($.distinctId)})};return DW($)}function n$($){let{telemetry:W,provider:Z}=H$($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function ej($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function ay($,W){if($==="console")return new my;if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/logs");return new hy({url:Z,headers:W.headers})}function oy($,W){if($==="console")return new py(new ly);if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/traces");return new dy(new Iy({url:Z,headers:W.headers}))}function sy($,W){if($==="console")return new dU({exporter:new cy,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/metrics");return new dU({exporter:new ky({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function $X($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var _W=Z2(()=>{U1();M6();tj()});var Q_={};w(Q_,{resolveCoreDistinctId:()=>c0,createOpenTelemetryTelemetryService:()=>DW,createConfiguredTelemetryService:()=>H$,createConfiguredTelemetryHandle:()=>n$,OpenTelemetryProvider:()=>c6,OpenTelemetryAdapter:()=>AW});var uQ=Z2(()=>{M6();_W()});import{AgentRuntimeAbortError as dv}from"@cline/agents";import{initVcr as lv,resolveClineBuildEnv as pv}from"@cline/shared";import{normalizeProviderId as Iv}from"@cline/llms";var Mf={};w(Mf,{LocalRuntimeHost:()=>h1});import{readdirSync as Ev}from"node:fs";import{homedir as wv}from"node:os";import{isAbsolute as Cv,join as rY,resolve as iY}from"node:path";import{captureSdkError as $2,createSessionId as Pv,isLikelyAuthError as Sv,normalizeUserInput as bv}from"@cline/shared";import{setHomeDirIfUnset as yv}from"@cline/shared/storage";var IV={};w(IV,{saveProviderOAuthCredentials:()=>j2,resolveProviderApiKeyFromSettings:()=>i7,loginAndSaveProviderOAuthCredentials:()=>G4,isOAuthProvider:()=>J2,getProviderOAuthCredentialsFromSettings:()=>K4,getProviderAuthStorageId:()=>r7,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>q8,formatProviderOAuthApiKey:()=>n7});import{decodeJwtPayload as NL,getClineEnvironmentConfig as hV}from"@cline/shared";var _V={};w(_V,{startClineDeviceAuth:()=>v7,refreshClineToken:()=>K9,loginClineOAuth:()=>Q4,getValidClineCredentials:()=>J4,completeClineDeviceAuth:()=>c7});import{getClineEnvironmentConfig as k7}from"@cline/shared";var eY={};w(eY,{setSdkLogger:()=>y7,sdkDebug:()=>s,hashSecret:()=>R0,getSdkLogger:()=>uf});import{createHash as cf}from"node:crypto";var b7;function y7($){b7=$}function uf(){return b7}function R0($){if(typeof $!=="string"||$.length===0)return"unset";return cf("sha256").update($).digest("hex").slice(0,8)}function s($){try{b7?.debug($)}catch{}}D0();var VV={};w(VV,{startLocalOAuthServer:()=>G1});function of(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function G1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??sf,j=of(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var sf=`<!DOCTYPE html>
1
+ import{createRequire as cf}from"node:module";var{defineProperty:S7,getOwnPropertyNames:gf}=Object;var oY=Object.prototype.hasOwnProperty;function sY($){return this[$]}var M=($,W,Z)=>{var Q=gf(W);for(let J of Q)if(!oY.call($,J)&&J!=="default")S7($,J,{get:sY.bind(W,J),enumerable:!0});if(Z){for(let J of Q)if(!oY.call(Z,J)&&J!=="default")S7(Z,J,{get:sY.bind(W,J),enumerable:!0});return Z}};var mf=($)=>$;function vf($,W){this[$]=mf.bind(null,W)}var w=($,W)=>{for(var Z in W)S7($,Z,{get:W[Z],enumerable:!0,configurable:!0,set:vf.bind(W,Z)})};var Q2=($,W)=>()=>($&&(W=$($=0)),W);var tY=cf(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as lf,captureAgentUnexpectedReasoningTokens as WV,SDK_ERROR_TELEMETRY_EVENT as pf}from"@cline/shared";function i($,W,Z){$?.capture({event:W,properties:Z})}function rW($){if(!$)return;return $.substring(0,rf)}function nf($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function af($){return typeof $==="string"?$:$.message}function $V($,W){return $.some((Z)=>W.has(Z.trim().toLowerCase()))}function ZV($){i($,m.CLIENT.EXTENSION_ACTIVATED)}function iW($,W){let Z=[...W.vcs_types],Q={root_count:W.root_count,vcs_types:Z,is_multi_root:W.root_count>1,has_git:$V(Z,new Set(["git"])),has_mercurial:$V(Z,new Set(["mercurial","hg"]))};if(W.init_duration_ms!==void 0)Q.init_duration_ms=W.init_duration_ms;if(W.feature_flag_enabled!==void 0)Q.feature_flag_enabled=W.feature_flag_enabled;if(W.is_remote_workspace!==void 0)Q.is_remote_workspace=W.is_remote_workspace;i($,m.WORKSPACE.INITIALIZED,Q)}function nW($,W,Z){i($,m.WORKSPACE.INIT_ERROR,{error_type:nf(W),error_message:rW(af(W)),fallback_to_single_root:Z.fallback_to_single_root,workspace_count:Z.workspace_count??0})}function QV($,W){i($,m.WORKSPACE.PATH_RESOLVED,{...W})}function v1($,W){i($,m.USER.AUTH_STARTED,{provider:W})}function c1($,W){i($,m.USER.AUTH_SUCCEEDED,{provider:W})}function u1($,W,Z){i($,m.USER.AUTH_FAILED,{provider:W,errorMessage:rW(Z)})}function D$($,W,Z,Q){i($,m.USER.AUTH_LOGGED_OUT,{provider:W,reason:Z,status:Q?.status,errorCode:Q?.errorCode})}function h7($,W,Z){i($,m.USER.AUTH_REFRESH_SOFT_FAILURE,{provider:W,status:Z?.status,errorCode:Z?.errorCode,errorName:Z?.errorName,tokenExpired:Z?.tokenExpired})}function JV($,W,Z){i($,m.USER.AUTH_RUN_RETRY,{provider:W,recovered:Z?.recovered})}function jV($,W){i($,m.USER.PROVIDER_CONFIGURED,{provider:W})}function XV($,W){$?.captureRequired(m.USER.TELEMETRY_OPT_OUT,W)}function K1($,W){let Z=W.id?.trim();if(Z)$?.setDistinctId(Z);$?.updateCommonProperties({user_id:Z||W.id,account_id:W.id,account_email:W.email,provider:W.provider,organization_id:W.organizationId,organization_name:W.organizationName,member_id:W.memberId})}function aW($,W){i($,m.TASK.CREATED,W)}function oW($,W){i($,m.TASK.RESTARTED,W)}function W4($,W){i($,m.TASK.COMPLETED,W)}function _8($,W){i($,m.TASK.CONVERSATION_TURN,{...W,timestamp:new Date().toISOString()})}function sW($,W){i($,m.TASK.TOKEN_USAGE,W)}function tW($,W,Z){i($,m.TASK.MODE_SWITCH,{ulid:W,mode:Z})}function f8($,W){i($,m.TASK.TOOL_USED,W)}function eW($,W){i($,m.TASK.SKILL_USED,W)}function $9($,W){i($,m.TASK.DIFF_EDIT_FAILED,W)}function Z4($,W){i($,m.TASK.PROVIDER_API_ERROR,{...W,errorMessage:rW(W.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function W9($,W){i($,m.TASK.MISTAKE_LIMIT_REACHED,{...W,timestamp:new Date().toISOString()})}function YV($,W){i($,m.SDK.TOOL_TIMEOUT,of(W))}function of($){let W={};for(let[Z,Q]of Object.entries($))if(Q!==void 0)W[Z]=Q;return W}function Z9($,W,Z){i($,m.TASK.MENTION_USED,{mentionType:W,contentLength:Z,timestamp:new Date().toISOString()})}function Q9($,W,Z,Q){i($,m.TASK.MENTION_FAILED,{mentionType:W,errorType:Z,errorMessage:rW(Q),timestamp:new Date().toISOString()})}function J9($,W,Z,Q,J){i($,m.TASK.MENTION_SEARCH_RESULTS,{queryLength:W.length,resultCount:Z,searchType:Q,isEmpty:J,timestamp:new Date().toISOString()})}function _$($,W){i($,m.TASK.AGENT_CREATED,{...W,timestamp:new Date().toISOString()})}function j9($,W){i($,m.TASK.AGENT_TEAM_CREATED,{...W,timestamp:new Date().toISOString()})}function Q4($,W){i($,W.event==="ended"?m.TASK.SUBAGENT_COMPLETED:m.TASK.SUBAGENT_STARTED,{...W,timestamp:new Date().toISOString()})}function X9($,W,Z,Q){i($,m.HOOKS.DISCOVERY_COMPLETED,{hookName:W,globalCount:Z,workspaceCount:Q,totalCount:Z+Q,timestamp:new Date().toISOString()})}function Y9($,W){i($,m.TASK.COMPACTION_EXECUTED,{...W,timestamp:new Date().toISOString()})}function V9($,W){i($,m.TASK.COMPACTION_SKIPPED,{...W,timestamp:new Date().toISOString()})}function VV($,W){i($,m.TASK.COMPACTION_BUDGET_EMERGENCY,{...W,timestamp:new Date().toISOString()})}var rf=500,m;var U0=Q2(()=>{m={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:lf},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",AUTH_REFRESH_SOFT_FAILURE:"user.auth_refresh_soft_failure",AUTH_RUN_RETRY:"user.auth_run_retry",PROVIDER_CONFIGURED:"user.provider_configured",TELEMETRY_OPT_OUT:"user.opt_out"},TASK:{CREATED:"task.created",RESTARTED:"task.restarted",COMPLETED:"task.completed",CONVERSATION_TURN:"task.conversation_turn",TOKEN_USAGE:"task.tokens",MODE_SWITCH:"task.mode",TOOL_USED:"task.tool_used",SKILL_USED:"task.skill_used",DIFF_EDIT_FAILED:"task.diff_edit_failed",PROVIDER_API_ERROR:"task.provider_api_error",MISTAKE_LIMIT_REACHED:"task.mistake_limit_reached",MENTION_USED:"task.mention_used",MENTION_FAILED:"task.mention_failed",MENTION_SEARCH_RESULTS:"task.mention_search_results",AGENT_CREATED:"task.agent_created",AGENT_TEAM_CREATED:"task.agent_team_created",SUBAGENT_STARTED:"task.subagent_started",SUBAGENT_COMPLETED:"task.subagent_completed",COMPACTION_EXECUTED:"task.compaction_executed",COMPACTION_SKIPPED:"task.compaction_skipped",COMPACTION_BUDGET_EMERGENCY:"task.compaction_budget_emergency"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:pf,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as lT,readFileSync as pT,statSync as rT,writeFileSync as iT}from"node:fs";import{dirname as nT}from"node:path";import{resolveGlobalSettingsPath as ZH}from"@cline/shared/storage";import{z as L2}from"zod";function x9(){return g4.parse({})}function oT(){g9=void 0}function sT($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function tT($){let W;try{W=pT($,"utf8")}catch{return x9()}try{let Z=g4.safeParse(JSON.parse(W));return Z.success?Z.data:x9()}catch{return x9()}}function eT(){let $=ZH(),W=rT($,{throwIfNoEntry:!1}),Z=W?.mtimeMs??0,Q=W?.size??0,J=g9;if(J&&J.path===$&&J.mtimeMs===Z&&J.size===Q)return J;let j=sT(W?tT($):x9());return g9={path:$,mtimeMs:Z,size:Q,value:j},g9}function R0(){return eT().value}function R1($,W={}){let Z=ZH(),Q=R0();lT(nT(Z),{recursive:!0});let J=g4.parse($);if(!Q.telemetryOptOut&&J.telemetryOptOut)XV(W.telemetry);iT(Z,`${JSON.stringify(J,null,2)}
2
+ `,"utf8"),oT()}function m9(){return R0().telemetryOptOut}function QH($,W={}){R1({...R0(),telemetryOptOut:$},W)}function JH(){return R0().autoUpdateEnabled}function jH($,W={}){R1({...R0(),autoUpdateEnabled:$},W)}function XH(){return R0().compactionStrategy??"basic"}function YH($){R1({...R0(),compactionStrategy:$})}function N1($){return new Set($??R0().disabledTools??[])}function m4($){return new Set($??R0().disabledPlugins??[])}function VH($){return N1().has($)}function v9($){let W=R0(),Z=new Set(W.disabledTools??[]),Q=Z.has($);if(Q)Z.delete($);else Z.add($);return R1({...W,disabledTools:[...Z]}),!Q}function _3($,W){let Z=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Z.length===0)return;let Q=R0(),J=N1(Q.disabledTools);for(let j of Z)if(W)J.add(j);else J.delete(j);R1({...Q,disabledTools:[...J]})}function BH($,W){return _3([$],W),W}function HH($){return m4().has($)}function GH($,W){let Z=$.trim();if(!Z)return;let Q=R0(),J=m4(Q.disabledPlugins);if(W)J.add(Z);else J.delete(Z);R1({...Q,disabledPlugins:[...J]})}function c9($,W){let Z=m4(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q))}function a1($,W){let Z=N1(W);if(Z.size===0)return[...$];return $.filter((Q)=>!Z.has(Q.name))}function u9($,W){if(!$||$.length===0)return $;let Z=N1(W);if(Z.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(J,j)=>Q.setup?.({...J,registerTool:(X)=>{if(!Z.has(X.name))J.registerTool(X)}},j)}})}var WH,aT,g4,g9;var _1=Q2(()=>{U0();WH=L2.preprocess(($)=>Array.isArray($)?$.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter(Boolean):void 0,L2.array(L2.string()).optional()).transform(($)=>{if(!$)return;let W=[...new Set($)].sort((Z,Q)=>Z.localeCompare(Q));return W.length>0?W:void 0}),aT=L2.enum(["basic","agentic"]).catch("basic"),g4=L2.object({telemetryOptOut:L2.boolean().default(!1).catch(!1),autoUpdateEnabled:L2.boolean().default(!0).catch(!0),compactionStrategy:aT.optional(),disabledTools:WH.optional(),disabledPlugins:WH.optional()}).strip().transform(($)=>{let W={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)W.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)W.disabledTools=$.disabledTools;if($.disabledPlugins?.length)W.disabledPlugins=$.disabledPlugins;return W})});var SH={};w(SH,{normalizeUserMessage:()=>$q,buildInitialUserContent:()=>ez});async function ez($,W,Z,Q){let J=Wq(W),j=await Qq(Z,Q);if(J.length===0&&!j)return $;let X=[{type:"text",text:$},...J];if(j)X.push(...j);return X}function $q($){if($==null)return"";if(typeof $==="string")return $;let W=$.content;if(typeof W==="string")return W;if(!Array.isArray(W))return"";let Z=[];for(let Q of W)if(Q&&typeof Q==="object"&&Q.type==="text"){let J=Q.text;if(typeof J==="string")Z.push(J)}return Z.join(`
3
+ `)}function Wq($){if(!$||$.length===0)return[];let W=[];for(let Z of $){let Q=Zq(Z);if(Q)W.push(Q)}return W}function Zq($){let W=$.trim();if(!W)return;let Z=W.match(/^data:([^;,]+);base64,(.+)$/);if(Z){let Q=Z[1],J=Z[2];if(!Q||!J)return;return{type:"image",mediaType:Q,data:J}}return{type:"image",mediaType:"image/png",data:W}}async function Qq($,W){if(!$||$.length===0)return;let Z=W??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(J)=>{let j=J.replace(/\\/g,"/");try{let X=await Z(J);return{type:"file",path:j,content:X}}catch(X){let Y=X instanceof Error?X.message:String(X);return{type:"file",path:j,content:`Error fetching content: ${Y}`}}}));if(Q.length===0)return;return Q}var FF={};w(FF,{updateMcpSettingsFileSync:()=>f1,updateMcpSettingsFile:()=>A6,updateMcpServerOAuthStateAsync:()=>I5,updateMcpServerOAuthState:()=>v2,setMcpServerDisabled:()=>g2,resolveMcpServerRegistrations:()=>W1,resolveDefaultMcpSettingsPath:()=>Q0,registerMcpServersFromSettingsFile:()=>c2,normalizeMcpServerOAuthState:()=>U6,loadMcpSettingsFile:()=>x2,listMcpServerOAuthStatuses:()=>x5,hasMcpSettingsFile:()=>Z$,getMcpServerOAuthState:()=>m2,McpSettingsUpdateSkippedError:()=>F6,McpSettingsMutatorPurityError:()=>m$,McpSettingsLockTimeoutError:()=>v$});import{existsSync as tK,mkdirSync as PJ,readFileSync as eK,renameSync as yJ,rmdirSync as XE,rmSync as SJ,statSync as YE,unlinkSync as $F,writeFileSync as WF}from"node:fs";import{randomUUID as VE}from"node:crypto";import{dirname as ZF,join as sK}from"node:path";import{setTimeout as BE}from"node:timers/promises";import{resolveMcpSettingsPath as HE}from"@cline/shared/storage";import{z as S}from"zod";function bJ($){if(!$)return;if($==="http")return"streamableHttp";return $}function Q0(){return HE()}function TE($,W){PJ(ZF($),{recursive:!0});let Z=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{WF(Z,W,{encoding:"utf8",flag:"wx"}),yJ(Z,$)}catch(Q){try{$F(Z)}catch{}throw Q}}function qE($){Atomics.wait(zE,0,0,$)}function ME($){return`${$}.lock`}function XF(){return`${process.pid}.${Date.now()}.${VE()}`}function YF($,W){PJ(ZF($),{recursive:!0});let Z=`${$}.tmp.${W}`;SJ(Z,{recursive:!0,force:!0}),PJ(Z,{recursive:!0}),WF(sK(Z,`owner.${W}`),W,{encoding:"utf8",flag:"wx"});try{return yJ(Z,$),{lockDir:$,ownerFile:sK($,`owner.${W}`)}}catch(Q){if(SJ(Z,{recursive:!0,force:!0}),tK($))return;throw Q}}function VF($,W){let Z;try{Z=Date.now()-YE($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Z<kJ)return;W.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Z}ms); reclaiming.`,{severity:"warn"});let Q=`${$}.stale.${XF()}`;try{yJ($,Q)}catch(J){if(J.code==="ENOENT")return;throw J}SJ(Q,{recursive:!0,force:!0})}function RE($){try{$F($.ownerFile)}catch(W){if(W.code!=="ENOENT")throw W}try{XE($.lockDir)}catch(W){let Z=W.code;if(Z!=="ENOENT"&&Z!=="ENOTEMPTY"&&Z!=="EEXIST")throw W}}function BF($){let W=ME($);if(nZ.has(W))throw Error(`Reentrant MCP settings update for ${$}. Keep mutators pure: compute values up front and do not call back into the settings API.`);return{lockDir:W,token:XF()}}function NE($,W){let{lockDir:Z,token:Q}=BF($),J=W.timeoutMs??kJ,j=Date.now();while(!0){let X=YF(Z,Q);if(X)return nZ.add(Z),X;if(Date.now()-j>J)throw new v$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);VF(Z,W),qE(jF)}}async function EE($,W){let{lockDir:Z,token:Q}=BF($),J=W.timeoutMs??kJ,j=Date.now();while(!0){let X=YF(Z,Q);if(X)return nZ.add(Z),X;if(Date.now()-j>J)throw new v$(`Timed out waiting for MCP settings lock at ${Z} after ${J}ms.`);VF(Z,W),await BE(jF)}}function HF($,W,Z){try{let Q=wE(W),J=CE(Q,Z);return TE(W,`${JSON.stringify(Q,null,2)}
4
+ `),J}finally{nZ.delete($.lockDir),RE($)}}function f1($,W,Z={}){let Q=NE($,Z);return HF(Q,$,W)}async function A6($,W,Z={}){let Q=await EE($,Z);return HF(Q,$,W)}function wE($){let W=SE($);if(!W.mcpServers||typeof W.mcpServers!=="object"||Array.isArray(W.mcpServers))W.mcpServers={};return W}function CE($,W){let Z=JSON.stringify($),Q=JSON.parse(Z),J=W(Q),j=JSON.stringify(Q),X=W($);if(JSON.stringify($)!==j)throw new m$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(X)!==JSON.stringify(J))throw new m$("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return X}function PE($){let W=eK($,"utf8"),Z;try{Z=JSON.parse(W)}catch(Q){let J=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Z}function SE($){try{return PE($)}catch(W){if(W.code==="ENOENT")return{};throw W}}function GF($,W){if(!Object.hasOwn($,W))return;let Z=$[W];if(!Z||typeof Z!=="object"||Array.isArray(Z))return;return Z}function bE($,W,Z){Object.defineProperty($,W,{value:Z,enumerable:!0,configurable:!0,writable:!0})}function x2($={}){let W=$.filePath??Q0(),Z=eK(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(j){let X=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${W}": ${X}`)}let J=OE.safeParse(Q);if(!J.success){let j=J.error.issues.map((X)=>{let Y=X.path.join(".");return Y?`${Y}: ${X.message}`:X.message}).join("; ");throw Error(`Invalid MCP settings at "${W}": ${j}`)}return J.data}function U6($){if(!$)return;let W={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(W).length>0?W:void 0}function yE($){if($===void 0)return;let W=hJ.safeParse($);if(!W.success)return;return U6(W.data)}function Z$($={}){let W=$.filePath??Q0();return tK(W)}function W1($={}){let W=x2($);return Object.entries(W.mcpServers).map(([Z,Q])=>({name:Z,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function g2($){let W=$.filePath??Q0(),Z=$.name.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");f1(W,(Q)=>{let J=Q.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${W}": mcpServers must be an object.`);let j={...J},X=GF(j,Z);if(!X)throw Error(`Unknown MCP server: ${Z}`);let Y={...X};if($.disabled)Y.disabled=!0;else delete Y.disabled;bE(j,Z,Y),Q.mcpServers=j})}function m2($,W={}){let Z=x2(W);if(!Object.hasOwn(Z.mcpServers,$))return;return U6(Z.mcpServers[$]?.oauth)}function KF($,W){return(Z)=>{let Q=Z.mcpServers,J=GF(Q,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let j=yE(J.oauth)??{},X=U6(W(j));if(X)J.oauth=X;else delete J.oauth;return X??{}}}function v2($,W,Z={}){let Q=Z.filePath??Q0();return f1(Q,KF($,W))}async function I5($,W,Z={}){let Q=Z.filePath??Q0();return A6(Q,KF($,W))}function x5($={}){return W1($).map((Z)=>{let Q=Z.transport.type!=="stdio",J=Z.oauth?.tokens?.access_token;return{serverName:Z.name,oauthSupported:Q,oauthConfigured:Q&&typeof J==="string"&&J.trim().length>0,lastError:Z.oauth?.lastError,lastAuthenticatedAt:Z.oauth?.lastAuthenticatedAt}}).sort((Z,Q)=>Z.serverName.localeCompare(Q.serverName))}async function c2($,W={}){let Z=W1(W);for(let Q of Z)await $.registerServer(Q);return Z}var k5,QF,hJ,GE,KE,FE,AE,UE,DE,JF,_E,fE,LE,OE,F6,v$,m$,kJ=1e4,jF=25,zE,nZ;var aZ=Q2(()=>{k5=S.record(S.string(),S.string()),QF=S.record(S.string(),S.unknown()),hJ=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),GE=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:k5.optional()}),KE=S.object({type:S.literal("sse"),url:S.string().url(),headers:k5.optional()}),FE=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:k5.optional()}),AE=S.discriminatedUnion("type",[GE,KE,FE]),UE=S.object({transport:AE,disabled:S.boolean().optional(),metadata:QF.optional(),oauth:hJ.optional()}),DE=S.enum(["stdio","sse","http","streamableHttp"]).optional(),JF=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:DE,disabled:S.boolean().optional(),metadata:QF.optional(),oauth:hJ.optional()});_E=JF.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:k5.optional()}).superRefine(($,W)=>{let Z=$.type??bJ($.transportType);if(Z&&Z!=="stdio")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),fE=JF.extend({url:S.string().url(),headers:k5.optional()}).superRefine(($,W)=>{let Z=$.type??bJ($.transportType)??"sse";if(Z!=="sse"&&Z!=="streamableHttp")W.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??bJ($.transportType)??"sse")==="streamableHttp")return{transport:{type:"streamableHttp",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth};return{transport:{type:"sse",url:$.url,headers:$.headers},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth}}),LE=S.union([UE,_E,fE]),OE=S.object({mcpServers:S.record(S.string(),LE)}).passthrough();F6=class F6 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};v$=class v$ extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};m$=class m$ extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};zE=new Int32Array(new SharedArrayBuffer(4)),nZ=new Set});import{existsSync as rS,mkdirSync as iS,readFileSync as nS,writeFileSync as aS}from"node:fs";import{resolve as oS}from"node:path";import{resolveSessionDataDir as sS}from"@cline/shared/storage";import{nanoid as tS}from"nanoid";import*as eS from"node-machine-id";function d0($){let W=$?.trim();if(W)return W;let Z=Zb();if(Z)return Z;return Qb()}function Wb(){let $=eS;return $.machineIdSync??$.default?.machineIdSync}function Zb(){try{let $=Wb();if(!$)return;return $().trim()||void 0}catch{return}}function Qb(){let $=sS(),W=oS($,$b);try{if(rS(W)){let Q=nS(W,"utf8").trim();if(Q.length>0)return Q}}catch{}let Z=`cl-${tS()}`;try{iS($,{recursive:!0}),aS(W,Z,"utf8")}catch{}return Z}var $b="machine-id";var R6=()=>{};class UW{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,W){if(!this.isEnabled())return;this.emitLog($,W,!1)}emitRequired($,W){this.emitLog($,W,!0)}recordCounter($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,j);j.add(W,this.flattenProperties(this.buildAttributes(Z)))}recordHistogram($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,j);j.record(W,this.flattenProperties(this.buildAttributes(Z)))}recordGauge($,W,Z,Q,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let j=this.buildAttributes(Z),X=JSON.stringify(j),Y=this.gaugeValues.get($);if(W===null){if(Y){if(Y.delete(X),Y.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=Y;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let B=this.meter.createObservableGauge($,Q?{description:Q}:void 0);B.addCallback((H)=>{for(let G of this.snapshotGaugeSeries($))H.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,B)}V.set(X,{value:W,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,W,Z){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(W,Z));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,W=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...W?{_required:!0}:{}}}snapshotGaugeSeries($){let W=this.gaugeValues.get($);if(!W)return[];return Array.from(W.values(),(Z)=>({value:Z.value,attributes:Z.attributes?{...Z.attributes}:void 0}))}flattenProperties($,W="",Z=new WeakSet,Q=0){if(!$)return{};let J={},j=100,X=10;for(let[Y,V]of Object.entries($)){if(Y==="__proto__"||Y==="constructor"||Y==="prototype")continue;let B=W?`${W}.${Y}`:Y;if(V===null||V===void 0){J[B]=String(V);continue}if(Array.isArray(V)){let H=V.length>j?V.slice(0,j):V;try{J[B]=JSON.stringify(H)}catch{J[B]="[UnserializableArray]"}if(V.length>j)J[`${B}_truncated`]=!0,J[`${B}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[B]=V.toISOString();continue}if(V instanceof Error){J[B]=V.message;continue}if(Z.has(V)){J[B]="[Circular]";continue}if(Q>=X){J[B]="[MaxDepthExceeded]";continue}Z.add(V),Object.assign(J,this.flattenProperties(V,B,Z,Q+1));continue}if(Iy(V)){J[B]=V;continue}try{J[B]=JSON.stringify(V)}catch{J[B]=String(V)}}return J}}function Iy($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class DW{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,W){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:W})}emitRequired($,W){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:W})}recordCounter($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordHistogram($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:W,attributes:Z,description:Q,required:J===!0})}recordGauge($,W,Z,Q,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:W,attributes:Z,description:Q,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class c6{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new DW({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let W=this.buildAttributes($.properties);for(let Z of this.adapters)Z.emit($.event,W)}captureRequired($,W){let Z=this.buildAttributes(W);for(let Q of this.adapters)Q.emitRequired($,Z)}recordCounter($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordCounter($,W,j,Q,J)}recordHistogram($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordHistogram($,W,j,Q,J)}recordGauge($,W,Z,Q,J=!1){let j=this.buildAttributes(Z);for(let X of this.adapters)X.recordGauge($,W,j,Q,J)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var tj=()=>{};import{metrics as xy,trace as gy}from"@opentelemetry/api";import{logs as my}from"@opentelemetry/api-logs";import{OTLPLogExporter as vy}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as cy}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as uy}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as dy}from"@opentelemetry/resources";import{BatchLogRecordProcessor as ly,ConsoleLogRecordExporter as py,LoggerProvider as ry}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as iy,MeterProvider as ny,PeriodicExportingMetricReader as lU}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as ay,ConsoleSpanExporter as oy,SimpleSpanProcessor as sy}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as ty}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as ey,ATTR_SERVICE_VERSION as $h}from"@opentelemetry/semantic-conventions";class pU{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,W){this.resolveProperties(W)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class u6{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let W=dy({[ey]:$.serviceName??"cline",...$.serviceVersion?{[$h]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(W),this.loggerProvider=this.createLoggerProvider(W),this.tracerProvider=this.createTracerProvider(W),this.meterProvider)xy.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)my.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",W){return gy.getTracer($,W??this.options.serviceVersion)}createAdapter($){return new UW({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let W=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new c6({...$,adapters:[W],distinctId:d0($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let W=ej(this.options.metricsExporter);if(W.length===0)return null;let Z=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(Z*0.8)),J=W.map((j)=>Qh(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Z,timeout:Q})).filter((j)=>j!==null);if(J.length===0)return null;return new ny({resource:$,readers:J})}createTracerProvider($){let W=ej(this.options.tracesExporter);if(W.length===0)return null;let Z=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let j of W){let X=Zh(j,{endpoint:Z,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(X)J.push(X)}if(J.length===0)return null;return new ty({resource:$,spanProcessors:J})}createLoggerProvider($){let W=ej(this.options.logsExporter);if(W.length===0)return null;let Z=W.map((Q)=>{let J=Wh(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new ly(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(Z.length===0)return null;return new ry({resource:$,processors:Z})}}function _W($){let W=new u6($),Z=W.createTelemetryService($);return Z.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:W,telemetry:Z}}function G$($){if(m9())return{telemetry:new pU($)};if($.enabled!==!0)return{telemetry:new c6({...$,distinctId:d0($.distinctId)})};return _W($)}function a$($){let{telemetry:W,provider:Z}=G$($);return{telemetry:W,provider:Z,flush:async()=>{let j=Z;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([W.dispose(),Z?.dispose()])}}}function ej($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Z)=>Z.trim()).filter((Z)=>Z==="console"||Z==="otlp")}function Wh($,W){if($==="console")return new py;if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/logs");return new vy({url:Z,headers:W.headers})}function Zh($,W){if($==="console")return new sy(new oy);if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/traces");return new ay(new uy({url:Z,headers:W.headers}))}function Qh($,W){if($==="console")return new lU({exporter:new iy,exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout});if(!W.endpoint)return null;let Z=$X(W.endpoint,"/v1/metrics");return new lU({exporter:new cy({url:Z,headers:W.headers}),exportIntervalMillis:W.interval,exportTimeoutMillis:W.timeout})}function $X($,W){let Z=new URL($),Q=Z.pathname.endsWith("/")?Z.pathname.slice(0,-1):Z.pathname;return Z.pathname=Q.endsWith(W)?Q:`${Q}${W}`,Z.toString()}var fW=Q2(()=>{_1();R6();tj()});var J_={};w(J_,{resolveCoreDistinctId:()=>d0,createOpenTelemetryTelemetryService:()=>_W,createConfiguredTelemetryService:()=>G$,createConfiguredTelemetryHandle:()=>a$,OpenTelemetryProvider:()=>u6,OpenTelemetryAdapter:()=>UW});var uQ=Q2(()=>{R6();fW()});import{AgentRuntimeAbortError as av}from"@cline/agents";import{initVcr as ov,resolveClineBuildEnv as sv}from"@cline/shared";import{normalizeProviderId as uv}from"@cline/llms";var Rf={};w(Rf,{LocalRuntimeHost:()=>k1});import{readdirSync as yv}from"node:fs";import{homedir as hv}from"node:os";import{isAbsolute as kv,join as rY,resolve as iY}from"node:path";import{captureSdkError as W2,createSessionId as Iv,isLikelyAuthError as xv,normalizeUserInput as gv}from"@cline/shared";import{setHomeDirIfUnset as mv}from"@cline/shared/storage";var xV={};w(xV,{saveProviderOAuthCredentials:()=>j2,resolveProviderApiKeyFromSettings:()=>i7,loginAndSaveProviderOAuthCredentials:()=>K4,isOAuthProvider:()=>L$,getProviderOAuthCredentialsFromSettings:()=>F4,getProviderAuthStorageId:()=>r7,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>M8,formatProviderOAuthApiKey:()=>n7});import{decodeJwtPayload as EL,getClineEnvironmentConfig as kV}from"@cline/shared";var fV={};w(fV,{startClineDeviceAuth:()=>v7,refreshClineToken:()=>K9,loginClineOAuth:()=>J4,getValidClineCredentials:()=>j4,completeClineDeviceAuth:()=>c7});import{getClineEnvironmentConfig as k7}from"@cline/shared";var eY={};w(eY,{setSdkLogger:()=>y7,sdkDebug:()=>s,hashSecret:()=>M0,getSdkLogger:()=>df});import{createHash as uf}from"node:crypto";var b7;function y7($){b7=$}function df(){return b7}function M0($){if(typeof $!=="string"||$.length===0)return"unset";return uf("sha256").update($).digest("hex").slice(0,8)}function s($){try{b7?.debug($)}catch{}}U0();var BV={};w(BV,{startLocalOAuthServer:()=>F1});function sf(){let $;return{promise:new Promise((Z)=>{$=Z}),resolve:$}}async function F1($){let W=await import("node:http"),Z=$.host??"127.0.0.1",Q=$.timeoutMs??300000,J=$.successHtml??tf,j=sf(),X=!1,Y=null,V=null,B=null,H=(F)=>{if(X)return;X=!0,j.resolve(F)},G=()=>{if(Y)clearTimeout(Y),Y=null;let F=B;if(B=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Z,port:F})).catch(()=>{})},K=async()=>{return Y=setTimeout(()=>{G(),H(null)},Q),j.promise};for(let F of $.ports){let A=W.createServer((U,f)=>{try{let _=new URL(U.url||"",`http://${Z}:${F}`);if(_.pathname!==$.callbackPath){f.statusCode=404,f.end("Not found");return}let R={url:_,code:_.searchParams.get("code")??void 0,state:_.searchParams.get("state")??void 0,provider:_.searchParams.get("provider")??void 0,error:_.searchParams.get("error")??void 0};if(R.error){f.statusCode=400,f.end(`Authentication failed: ${R.error}`),G(),H(R);return}if(!R.code){f.statusCode=400,f.end("Missing authorization code");return}if($.expectedState&&R.state!==$.expectedState){f.statusCode=400,f.end("State mismatch");return}f.statusCode=200,f.setHeader("Content-Type","text/html; charset=utf-8"),f.end(J),G(),H(R)}catch{f.statusCode=500,f.end("Internal error")}}),D=await new Promise((U)=>{let f=(_)=>{A.off("error",f),U({bound:!1,error:_})};A.once("error",f),A.listen(F,Z,()=>{A.off("error",f),V=A,U({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw G(),D.error}if(D.bound){B=F;let U=`http://${Z}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Z,port:F,callbackUrl:U})).catch(()=>{});return{callbackUrl:U,waitForCallback:K,cancelWait:()=>{G(),H(null)},close:()=>{G(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var tf=`<!DOCTYPE html>
5
5
  <html lang="en">
6
6
  <head>
7
7
  <meta charset="utf-8">
@@ -42,27 +42,27 @@ import{createRequire as vf}from"node:module";var{defineProperty:S7,getOwnPropert
42
42
  </div>
43
43
  <script>setTimeout(() => window.close(), 3000);</script>
44
44
  </body>
45
- </html>`;function BV($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function tf($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function ef($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),BV(W)}async function B9(){let $=ef(),W=BV(await tf($));return{verifier:$,challenge:W}}function H9($){return $.endsWith("/")?$.slice(0,-1):$}function Q2($,W){return new URL(W,`${H9($)}/`).toString()}function f8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function L8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function O8($,W){return Date.now()>=$.expires-W}async function T8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return f8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return f8(W,$.parseOptions);return{}}var G9={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},FV={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},I7="https://api.workos.com",$L="/auth",HV=Array.from({length:11},($,W)=>48801+W),WL=300000,ZL=30000,z8=30000,QL=300,JL=5;class T1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function jL($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function x7($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:jL($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function g7($){if(!$)return{};return typeof $==="function"?await $():$}function GV($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function KV($){await new Promise((W)=>setTimeout(W,$))}function m7($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function AV($,W){let Z=await fetch(Q2(I7,FV.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??z8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new T1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:GV(Q.expires_in,QL),pollIntervalSeconds:GV(Q.interval,JL)}}async function UV($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(Q2($.workosApiBaseUrl,FV.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await KV(Z*1000);break}case"slow_down":{Z+=1,await KV(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new T1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new T1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function DV($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(Q2(W.apiBaseUrl,G9.register),{method:"POST",headers:{"Content-Type":"application/json",...await g7(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??z8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=L8(X);throw new T1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return x7(m7(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function XL($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(Q2(Z.apiBaseUrl,G9.token),{method:"POST",headers:{"Content-Type":"application/json",...await g7(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??z8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=L8(Y);throw new T1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return x7(m7(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function Q4($){m1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:HV,Q=$.callbackPath??$L,J=W?null:await G1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??HV[0]}${Q}`;try{let X;if(W){let Y=k7().workOsClientId,V=await AV(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await UV({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??z8,workosApiBaseUrl:I7,onProgress:$.callbacks.onProgress});X=await DV(B,$,$.provider)}else{let Y=new URL(Q2($.apiBaseUrl,G9.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await T8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=f8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await XL(V,j,$,B)}return v1($.telemetry,$.provider??"cline"),H1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw c1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function v7($){return await AV(k7().workOsClientId,$)}async function c7($){let W=$.provider??"cline";m1($.telemetry,W);try{let Z=await UV({clientId:k7().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??z8,workosApiBaseUrl:I7}),Q=await DV(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return v1($.telemetry,W),H1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw c1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function K9($,W){let Z=Q2(W.apiBaseUrl,G9.refresh);s(`cline.refresh.request url=${Z} refreshTokenHash=${R0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await g7(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??z8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=L8(Y);throw s(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new T1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=x7(m7(J,"Invalid token refresh response"),j,$);return s(`cline.refresh.success newAccessTokenHash=${R0(X.access)} newRefreshTokenHash=${R0(X.refresh)} expires=${X.expires}`),X}async function J4($,W,Z){if(!$)return s("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??WL,J=Z?.retryableTokenGraceMs??ZL,j=Z?.forceRefresh===!0;if(!j&&!O8($,Q))return s(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;s(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${R0($.access)}`);try{return await K9($,W)}catch(X){let Y={status:X instanceof T1?X.status:void 0,errorCode:X instanceof T1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof T1&&X.isLikelyInvalidGrant())return s(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),D$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return s(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),h7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw s(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),h7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}D0();var LV={};w(LV,{refreshOpenAICodexToken:()=>A9,loginOpenAICodex:()=>j4,getValidOpenAICodexCredentials:()=>X4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as u7}from"@cline/shared";import{nanoid as YL}from"nanoid";var Y0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class F9 extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function VL($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function BL($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=L8(Q);throw new F9(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof F9)throw W;return{type:"failed"}}}async function HL($="pi"){let{verifier:W,challenge:Z}=await B9(),Q=YL(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function GL(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function KL($,W){let Z=W?u7(W):u7($),Q=Z?Z:u7($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function fV($,W){let Z=KL($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function j4($){m1($.telemetry,"openai-codex");let W=GL(),{verifier:Z,state:Q,url:J}=await HL($.originator),j=await G1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await T8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=f8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await VL(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=fV(V);return v1($.telemetry,"openai-codex"),H1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw c1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function A9($,W){let Z=await BL($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=fV(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function X4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!O8($,Z))return $;try{return await A9($.refresh,$)}catch(j){if(j instanceof F9&&j.isLikelyInvalidGrant())return D$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}D0();var yV={};w(yV,{refreshOcaToken:()=>f9,loginOcaOAuth:()=>B4,getValidOcaCredentials:()=>H4,OCI_HEADER_OPC_REQUEST_ID:()=>FL,DEFAULT_INTERNAL_OCA_BASE_URL:()=>U9,DEFAULT_INTERNAL_IDCS_URL:()=>zV,DEFAULT_INTERNAL_IDCS_SCOPES:()=>qV,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>TV,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>D9,DEFAULT_EXTERNAL_IDCS_URL:()=>RV,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>NV,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>MV});import{decodeJwtPayload as Y4}from"@cline/shared";import{nanoid as OV}from"nanoid";class d7{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var TV="a8331954c0cf48ba99b5dd223a14c6ea",zV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",qV="openid offline_access",U9="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",MV="c1aba3deed5740659981a752714eba33",RV="https://login-ext.identity.oraclecloud.com",NV="openid offline_access",D9="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",FL="opc-request-id",AL="/auth/oca",UL=Array.from({length:11},($,W)=>48801+W),DL=300000,_L=30000,EV=30000,fL=600000;class _9 extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var f$={internal:{clientId:TV,idcsUrl:zV,scopes:qV,baseUrl:U9},external:{clientId:MV,idcsUrl:RV,scopes:NV,baseUrl:D9}},V4=new Map,LL=86400000,OL=300000,TL=32,l7=new d7(LL,TL);function wV($){if(typeof $==="function")return $();return $??"internal"}function CV($){return{internal:{clientId:$?.internal?.clientId??f$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??f$.internal.idcsUrl,scopes:$?.internal?.scopes??f$.internal.scopes,baseUrl:$?.internal?.baseUrl??f$.internal.baseUrl},external:{clientId:$?.external?.clientId??f$.external.clientId,idcsUrl:$?.external?.idcsUrl??f$.external.idcsUrl,scopes:$?.external?.scopes??f$.external.scopes,baseUrl:$?.external?.baseUrl??f$.external.baseUrl}}}function zL($=Date.now()){let W=$-fL;for(let[Z,Q]of V4.entries())if(Q.createdAt<W)V4.delete(Z)}function qL($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=Y4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=Y4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function PV($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=Y4($.id_token),X=Y4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:qL($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function SV($,W){let Z=H9($),Q=l7.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return l7.set(Z,V,Date.now(),OL),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return l7.set(Z,Y),Y}function bV($){return{code:$.error,message:$.error_description}}async function ML($){let W=V4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");V4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await SV(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=bV(X);throw new _9(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=Y4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return PV(X,$.mode)}function RL($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${H9(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function B4($){m1($.telemetry,"oca");let W=CV($.config),Z=wV($.mode),Q=$.callbackPorts?.length?$.callbackPorts:UL,J=$.callbackPath??AL,j=$.requestTimeoutMs??EV,X=await G1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=OV(16),B=OV(16),{verifier:H,challenge:G}=await B9();zL(),V4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=RL({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await T8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,D=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==V)throw Error("State mismatch");let U=await ML({code:A,state:D,mode:Z,config:W,requestTimeoutMs:j});return v1($.telemetry,"oca"),H1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw c1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function f9($,W={}){let Z=CV(W.config),Q=W.requestTimeoutMs??EV,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:wV(W.mode),X=j==="external"?Z.external:Z.internal,Y=await SV(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=bV(H);throw new _9(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return PV(H,j,$)}async function H4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??DL,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??_L;if(W?.forceRefresh!==!0&&!O8($,Q))return $;try{return await f9($,Z)}catch(X){if(X instanceof _9&&X.isLikelyInvalidGrant())return D$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var L9="workos:";function EL($){let W=$.trim();return W.toLowerCase().startsWith(L9)?W:`${L9}${W}`}function wL($){let W=$.trim();return W.toLowerCase().startsWith(L9)?W.slice(L9.length):W}function CL($){let Z=NL($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function PL($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=CL(W);if(Q)return Q;return Date.now()-1}function SL($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:PL($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function bL($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function p7($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return bL({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function kV($){return p7({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:EL,normalizeStoredAccessToken:wL,login:({settings:W,callbacks:Z,telemetry:Q})=>Q4({apiBaseUrl:W?.baseUrl?.trim()||hV().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>J4(Z,{apiBaseUrl:W.baseUrl?.trim()||hV().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var yL=[kV({providerId:"cline"}),kV({providerId:"cline-pass",storageProviderId:"cline"}),p7({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>B4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>H4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),p7({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>j4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>X4($,{forceRefresh:W,telemetry:Z})})],hL=new Map(yL.map(($)=>[$.providerId,$]));function H0($){return hL.get($.trim().toLowerCase())}function J2($){return H0($)!==void 0}function r7($){return H0($)?.storageProviderId}function i7($,W){let Z=H0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??q8(W,J)}async function G4($,W,Z){let Q=H0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function K4($,W){let Z=H0($);if(!Z)return null;return SL(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function j2($){let W=H0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function q8($,W){let Z=H0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function n7($,W){let Z=H0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}D0();var TB={};w(TB,{createContextCompactionPrepareTurn:()=>T4,createCompactionStateAwarePrepareTurn:()=>z4});import{estimateRequestInputTokens as fO}from"@cline/shared";var uV={};w(uV,{projectSessionCompactionState:()=>X2,parseSessionCompactionState:()=>K1,createSessionCompactionState:()=>M8,SessionCompactionStateSchema:()=>F4});import{createHash as kL}from"node:crypto";import{formatDisplayUserInput as xV}from"@cline/shared";import{z as z1}from"zod";function IL($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var xL=z1.custom(IL),F4=z1.object({version:z1.literal(1),updated_at:z1.string().datetime(),conversation_id:z1.string().min(1).optional(),source_message_count:z1.number().int().nonnegative(),source_prefix_hash:z1.string().min(1).optional(),source_last_message_key:z1.string().min(1).optional(),messages:z1.array(xL),system_prompt:z1.string().optional()});function a7($){return JSON.parse(JSON.stringify($))}function gV($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:xV($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:xV(W.text)}:W)}}function mV($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function gL($){let W=gV($);return mV(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function vV($){if(!$)return"";let W=gV($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(mV(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function cV($,W=$.length){let Z=kL("sha256");Z.update(`cline-session-compaction-source-v1
45
+ </html>`;function HV($){let W="";for(let Z=0;Z<$.length;Z+=1)W+=String.fromCharCode($[Z]??0);return btoa(W).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function ef($){let Z=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",Z);return new Uint8Array(Q)}function $L($=32){let W=new Uint8Array($);return crypto.getRandomValues(W),HV(W)}async function B9(){let $=$L(),W=HV(await ef($));return{verifier:$,challenge:W}}function H9($){return $.endsWith("/")?$.slice(0,-1):$}function J2($,W){return new URL(W,`${H9($)}/`).toString()}function L8($,W={}){let Z=$.trim();if(!Z)return{};try{let Q=new URL(Z);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:W.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(W.allowHashCodeState&&Z.includes("#")){let[Q,J]=Z.split("#",2);return{code:Q||void 0,state:J||void 0}}if(Z.includes("code=")){let Q=new URLSearchParams(Z);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:W.includeProvider?Q.get("provider")??void 0:void 0}}return{code:Z}}function O8($){try{let W=JSON.parse($),Z=W.error,Q=typeof Z==="string"?Z:Z&&typeof Z==="object"&&typeof Z.type==="string"?Z.type:void 0,J=typeof W.error_description==="string"?W.error_description:typeof W.message==="string"?W.message:Z&&typeof Z==="object"&&typeof Z.message==="string"?Z.message:void 0;return{code:Q,message:J}}catch{return{}}}function T8($,W){return Date.now()>=$.expires-W}async function z8($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let W,Z,Q=$.onManualCodeInput().then((j)=>{W=j,$.cancelWait()}).catch((j)=>{Z=j instanceof Error?j:Error(String(j)),$.cancelWait()}),J=await $.waitForCallback();if(Z)throw Z;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(W)return L8(W,$.parseOptions);if(await Q,Z)throw Z;if(W)return L8(W,$.parseOptions);return{}}var G9={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},AV={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},I7="https://api.workos.com",WL="/auth",GV=Array.from({length:11},($,W)=>48801+W),ZL=300000,QL=30000,q8=30000,JL=300,jL=5;class z1 extends Error{status;errorCode;constructor($,W){super($);this.name="ClineOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function XL($){let W=Date.parse($);if(Number.isNaN(W))throw Error(`Invalid expiresAt value: ${$}`);return W}function x7($,W,Z={}){let Q=$.userInfo.clineUserId??Z.accountId,J=$.refreshToken??Z.refresh;if(!J)throw Error("Token response did not include a refresh token");let j={...Z.metadata??{},provider:W,tokenType:$.tokenType,userInfo:$.userInfo};return delete j.startedAt,{access:$.accessToken,refresh:J,expires:XL($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||Z.email,metadata:j}}async function g7($){if(!$)return{};return typeof $==="function"?await $():$}function KV($,W){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return W;return Math.floor($)}async function FV($){await new Promise((W)=>setTimeout(W,$))}function m7($,W){if(!$.success||!$.data?.accessToken)throw Error(W);return $.data}async function UV($,W){let Z=await fetch(J2(I7,AV.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(W?.requestTimeoutMs??q8)}),Q=await Z.json().catch(()=>({}));if(!Z.ok)throw new z1(`Device authorization failed: ${Z.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:Z.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:KV(Q.expires_in,JL),pollIntervalSeconds:KV(Q.interval,jL)}}async function DV($){let W=Date.now()+$.expiresInSeconds*1000,Z=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=W){let Q=await fetch(J2($.workosApiBaseUrl,AV.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),J=await Q.json().catch(()=>({}));if(Q.ok){if(!J.access_token||!J.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:J.access_token,refreshToken:J.refresh_token,tokenType:J.token_type??"Bearer"}}switch(J.error){case"authorization_pending":{await FV(Z*1000);break}case"slow_down":{Z+=1,await FV(Z*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new z1(J.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:J.error});default:throw new z1(`WorkOS token polling failed: ${Q.status}${J.error_description?` - ${J.error_description}`:""}`,{status:Q.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function _V($,W,Z){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(J2(W.apiBaseUrl,G9.register),{method:"POST",headers:{"Content-Type":"application/json",...await g7(W.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(W.requestTimeoutMs??q8)});if(!J.ok){let X=await J.text().catch(()=>""),Y=O8(X);throw new z1(`Token registration failed: ${J.status}${Y.message?` - ${Y.message}`:""}`,{status:J.status,errorCode:Y.code})}let j=await J.json();return x7(m7(j,"Invalid token exchange response"),Z??W.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function YL($,W,Z,Q){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:W,provider:Q??Z.provider},j=await fetch(J2(Z.apiBaseUrl,G9.token),{method:"POST",headers:{"Content-Type":"application/json",...await g7(Z.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Z.requestTimeoutMs??q8)});if(!j.ok){let Y=await j.text().catch(()=>""),V=O8(Y);throw new z1(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let X=await j.json();return x7(m7(X,"Invalid token exchange response"),Q??Z.provider,{metadata:{sessionStartedAtMs:Date.now()}})}async function J4($){v1($.telemetry,$.provider??"cline");let W=$.useWorkOSDeviceAuth??!0,Z=$.callbackPorts?.length?$.callbackPorts:GV,Q=$.callbackPath??WL,J=W?null:await F1({ports:Z,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=J?.callbackUrl||`http://127.0.0.1:${Z[0]??GV[0]}${Q}`;try{let X;if(W){let Y=k7().workOsClientId,V=await UV(Y,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let B=await DV({clientId:Y,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??q8,workosApiBaseUrl:I7,onProgress:$.callbacks.onProgress});X=await _V(B,$,$.provider)}else{let Y=new URL(J2($.apiBaseUrl,G9.authorize));Y.searchParams.set("client_type","extension"),Y.searchParams.set("callback_url",j),Y.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:Y.toString(),instructions:"Continue the authentication process in your browser."});let V,B=$.provider,H=await z8({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(V=H.code,B=H.provider??B,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=L8(G,{includeProvider:!0});V=K.code,B=K.provider??B}if(!V)throw Error("Missing authorization code");X=await YL(V,j,$,B)}return c1($.telemetry,$.provider??"cline"),K1($.telemetry,{id:X.accountId,email:X.email,provider:$.provider??"cline"}),X}catch(X){throw u1($.telemetry,$.provider??"cline",X instanceof Error?X.message:String(X)),X}finally{J?.close()}}async function v7($){return await UV(k7().workOsClientId,$)}async function c7($){let W=$.provider??"cline";v1($.telemetry,W);try{let Z=await DV({clientId:k7().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??q8,workosApiBaseUrl:I7}),Q=await _V(Z,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return c1($.telemetry,W),K1($.telemetry,{id:Q.accountId,email:Q.email,provider:W}),Q}catch(Z){throw u1($.telemetry,W,Z instanceof Error?Z.message:String(Z)),Z}}async function K9($,W){let Z=J2(W.apiBaseUrl,G9.refresh);s(`cline.refresh.request url=${Z} refreshTokenHash=${M0($.refresh)}`);let Q=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/json",...await g7(W.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(W.requestTimeoutMs??q8)});if(!Q.ok){let Y=await Q.text().catch(()=>""),V=O8(Y);throw s(`cline.refresh.error status=${Q.status} errorCode=${V.code??"none"} message=${V.message??"none"}`),new z1(`Token refresh failed: ${Q.status}${V.message?` - ${V.message}`:""}`,{status:Q.status,errorCode:V.code})}let J=await Q.json(),j=$.metadata?.provider??W.provider,X=x7(m7(J,"Invalid token refresh response"),j,$);return s(`cline.refresh.success newAccessTokenHash=${M0(X.access)} newRefreshTokenHash=${M0(X.refresh)} expires=${X.expires}`),X}async function j4($,W,Z){if(!$)return s("cline.getCredentials outcome=no_current_credentials"),null;let Q=Z?.refreshBufferMs??ZL,J=Z?.retryableTokenGraceMs??QL,j=Z?.forceRefresh===!0;if(!j&&!T8($,Q))return s(`cline.getCredentials outcome=still_valid forceRefresh=${j}`),$;s(`cline.getCredentials outcome=needs_refresh forceRefresh=${j} accessTokenHash=${M0($.access)}`);try{return await K9($,W)}catch(X){let Y={status:X instanceof z1?X.status:void 0,errorCode:X instanceof z1?X.errorCode:void 0,errorName:X instanceof Error?X.name:void 0};if(X instanceof z1&&X.isLikelyInvalidGrant())return s(`cline.getCredentials outcome=invalid_grant status=${X.status} errorCode=${X.errorCode??"none"}`),D$(W.telemetry,W.provider??"cline","invalid_grant",{status:X.status,errorCode:X.errorCode}),null;if($.expires-Date.now()>J)return s(`cline.getCredentials outcome=transient_failure_kept_current error=${X instanceof Error?X.message:String(X)}`),h7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!1}),$;throw s(`cline.getCredentials outcome=transient_failure_rethrown error=${X instanceof Error?X.message:String(X)}`),h7(W.telemetry,W.provider??"cline",{...Y,tokenExpired:!0}),X}}U0();var OV={};w(OV,{refreshOpenAICodexToken:()=>A9,loginOpenAICodex:()=>X4,getValidOpenAICodexCredentials:()=>Y4,OPENAI_CODEX_OAUTH_CONFIG:()=>Y0});import{decodeJwtPayload as u7}from"@cline/shared";import{nanoid as VL}from"nanoid";var Y0={authorizationEndpoint:"https://auth.openai.com/oauth/authorize",tokenEndpoint:"https://auth.openai.com/oauth/token",clientId:"app_EMoamEEZ73f0CkXaXp7hrann",redirectUri:"http://localhost:1455/auth/callback",scopes:"openid profile email offline_access",callbackPort:1455,jwtClaimPath:"https://api.openai.com/auth",refreshBufferMs:300000,retryableTokenGraceMs:30000,httpTimeoutMs:30000};class F9 extends Error{status;errorCode;constructor($,W){super($);this.name="OpenAICodexOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function BL($,W,Z=Y0.redirectUri){let Q=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:Y0.clientId,code:$,code_verifier:W,redirect_uri:Z}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let J=await Q.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}async function HL($){try{let W=await fetch(Y0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:Y0.clientId}),signal:AbortSignal.timeout(Y0.httpTimeoutMs)});if(!W.ok){let Q=await W.text().catch(()=>""),J=O8(Q);throw new F9(`Token refresh failed: ${W.status}${J.message?` - ${J.message}`:""}`,{status:W.status,errorCode:J.code})}let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}catch(W){if(W instanceof F9)throw W;return{type:"failed"}}}async function GL($="pi"){let{verifier:W,challenge:Z}=await B9(),Q=VL(32),J=new URL(Y0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",Y0.clientId),J.searchParams.set("redirect_uri",Y0.redirectUri),J.searchParams.set("scope",Y0.scopes),J.searchParams.set("code_challenge",Z),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",Q),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:W,state:Q,url:J.toString()}}function KL(){try{let $=new URL(Y0.redirectUri),W=$.port.length>0?Number.parseInt($.port,10):Y0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(W)?W:Y0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:Y0.callbackPort,callbackPath:"/auth/callback",redirectUri:Y0.redirectUri}}}function FL($,W){let Z=W?u7(W):u7($),Q=Z?Z:u7($),j=Q?.[Y0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let X=Q?.organizations;if(Array.isArray(X)&&X.length>0){let V=X[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let Y=Q?.chatgpt_account_id;if(typeof Y==="string"&&Y.length>0)return Y;return null}function LV($,W){let Z=FL($.access,$.idToken)??W?.accountId;if(!Z)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||W?.refresh||"",expires:$.expires,accountId:Z,email:$.email??W?.email,metadata:{...W?.metadata??{},provider:"openai-codex"}}}async function X4($){v1($.telemetry,"openai-codex");let W=KL(),{verifier:Z,state:Q,url:J}=await GL($.originator),j=await F1({host:W.host,ports:[W.port],callbackPath:W.callbackPath,expectedState:Q});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let X;try{let Y=await z8({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(Y.state&&Y.state!==Q)throw Error("State mismatch");if(X=Y.code,!X){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=L8(H,{allowHashCodeState:!0});if(G.state&&G.state!==Q)throw Error("State mismatch");X=G.code}if(!X)throw Error("Missing authorization code");let V=await BL(X,Z,W.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let B=LV(V);return c1($.telemetry,"openai-codex"),K1($.telemetry,{id:B.accountId,email:B.email,provider:"openai-codex"}),B}catch(Y){throw u1($.telemetry,"openai-codex",Y instanceof Error?Y.message:String(Y)),Y}finally{j.close()}}async function A9($,W){let Z=await HL($);if(Z.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=LV(Z,W);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function Y4($,W){if(!$)return null;let Z=W?.refreshBufferMs??Y0.refreshBufferMs,Q=W?.retryableTokenGraceMs??Y0.retryableTokenGraceMs;if(W?.forceRefresh!==!0&&!T8($,Z))return $;try{return await A9($.refresh,$)}catch(j){if(j instanceof F9&&j.isLikelyInvalidGrant())return D$(W?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}U0();var hV={};w(hV,{refreshOcaToken:()=>f9,loginOcaOAuth:()=>H4,getValidOcaCredentials:()=>G4,OCI_HEADER_OPC_REQUEST_ID:()=>AL,DEFAULT_INTERNAL_OCA_BASE_URL:()=>U9,DEFAULT_INTERNAL_IDCS_URL:()=>qV,DEFAULT_INTERNAL_IDCS_SCOPES:()=>MV,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>zV,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>D9,DEFAULT_EXTERNAL_IDCS_URL:()=>NV,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>EV,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>RV});import{decodeJwtPayload as V4}from"@cline/shared";import{nanoid as TV}from"nanoid";class d7{ttlMs;maxEntries;entries=new Map;constructor($,W){this.ttlMs=$;this.maxEntries=W}get($,W=Date.now()){this.pruneExpired(W);let Z=this.entries.get($);if(!Z)return;return this.entries.delete($),this.entries.set($,Z),Z.value}set($,W,Z=Date.now(),Q=this.ttlMs){this.pruneExpired(Z),this.entries.delete($);while(this.entries.size>=this.maxEntries){let J=this.entries.keys().next().value;if(J===void 0)break;this.entries.delete(J)}this.entries.set($,{value:W,expiresAt:Z+Q})}pruneExpired($){for(let[W,Z]of this.entries)if(Z.expiresAt<=$)this.entries.delete(W)}}var zV="a8331954c0cf48ba99b5dd223a14c6ea",qV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",MV="openid offline_access",U9="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",RV="c1aba3deed5740659981a752714eba33",NV="https://login-ext.identity.oraclecloud.com",EV="openid offline_access",D9="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",AL="opc-request-id",UL="/auth/oca",DL=Array.from({length:11},($,W)=>48801+W),_L=300000,fL=30000,wV=30000,LL=600000;class _9 extends Error{status;errorCode;constructor($,W){super($);this.name="OcaOAuthTokenError",this.status=W?.status,this.errorCode=W?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var f$={internal:{clientId:zV,idcsUrl:qV,scopes:MV,baseUrl:U9},external:{clientId:RV,idcsUrl:NV,scopes:EV,baseUrl:D9}},B4=new Map,OL=86400000,TL=300000,zL=32,l7=new d7(OL,zL);function CV($){if(typeof $==="function")return $();return $??"internal"}function PV($){return{internal:{clientId:$?.internal?.clientId??f$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??f$.internal.idcsUrl,scopes:$?.internal?.scopes??f$.internal.scopes,baseUrl:$?.internal?.baseUrl??f$.internal.baseUrl},external:{clientId:$?.external?.clientId??f$.external.clientId,idcsUrl:$?.external?.idcsUrl??f$.external.idcsUrl,scopes:$?.external?.scopes??f$.external.scopes,baseUrl:$?.external?.baseUrl??f$.external.baseUrl}}}function qL($=Date.now()){let W=$-LL;for(let[Z,Q]of B4.entries())if(Q.createdAt<W)B4.delete(Z)}function ML($,W,Z){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=V4(W)?.exp;if(typeof J==="number"&&J>0)return J*1000;let X=V4(Z)?.exp;if(typeof X==="number"&&X>0)return X*1000;return Date.now()+3600000}function SV($,W,Z){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let J=$.refresh_token??Z?.refresh;if(!J)throw Error("Token response did not include a refresh token");let j=V4($.id_token),X=V4(Q),Y=j?.sub??X?.sub,V=j?.email??X?.email;return{access:Q,refresh:J,expires:ML($,Q,$.id_token),accountId:Y??Z?.accountId,email:V??Z?.email,metadata:{...Z?.metadata??{},provider:"oca",mode:W,subject:Y,idToken:$.id_token}}}async function bV($,W){let Z=H9($),Q=l7.get(Z);if(Q)return Q;let J=`${Z}/.well-known/openid-configuration`,j=await fetch(J,{method:"GET",signal:AbortSignal.timeout(W)});if(!j.ok){let V=`${Z}/oauth2/v1/token`;return l7.set(Z,V,Date.now(),TL),V}let Y=(await j.json()).token_endpoint||`${Z}/oauth2/v1/token`;return l7.set(Z,Y),Y}function yV($){return{code:$.error,message:$.error_description}}async function RL($){let W=B4.get($.state);if(!W)throw Error("No PKCE verifier found for this state");B4.delete($.state);let Z=$.mode==="external"?$.config.external:$.config.internal,Q=await bV(Z.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:W.redirectUri,client_id:Z.clientId,code_verifier:W.verifier}),j=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),X=await j.json();if(!j.ok){let V=yV(X);throw new _9(`Token exchange failed: ${j.status}${V.message?` - ${V.message}`:""}`,{status:j.status,errorCode:V.code})}let Y=V4(X.id_token);if(!X.id_token||!Y)throw Error("No ID token received from OCA");if(Y.nonce!==W.nonce)throw Error("OIDC nonce verification failed");return SV(X,$.mode)}function NL($){let W=$.mode==="external"?$.config.external:$.config.internal,Z=new URL(`${H9(W.idcsUrl)}/oauth2/v1/authorize`);return Z.searchParams.set("client_id",W.clientId),Z.searchParams.set("response_type","code"),Z.searchParams.set("scope",W.scopes),Z.searchParams.set("code_challenge",$.challenge),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("redirect_uri",$.callbackUrl),Z.searchParams.set("state",$.state),Z.searchParams.set("nonce",$.nonce),Z.toString()}async function H4($){v1($.telemetry,"oca");let W=PV($.config),Z=CV($.mode),Q=$.callbackPorts?.length?$.callbackPorts:DL,J=$.callbackPath??UL,j=$.requestTimeoutMs??wV,X=await F1({ports:Q,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Y=X.callbackUrl;if(!Y)throw Error("Unable to bind local OAuth callback server");let V=TV(16),B=TV(16),{verifier:H,challenge:G}=await B9();qL(),B4.set(V,{verifier:H,nonce:B,mode:Z,redirectUri:Y,createdAt:Date.now()});let K=NL({callbackUrl:Y,mode:Z,state:V,nonce:B,challenge:G,config:W});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await z8({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,D=F.state;if(F.error)throw Error(`OAuth error: ${F.error}`);if(!A){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==V)throw Error("State mismatch");let U=await RL({code:A,state:D,mode:Z,config:W,requestTimeoutMs:j});return c1($.telemetry,"oca"),K1($.telemetry,{id:U.accountId,email:U.email,provider:"oca"}),U}catch(F){throw u1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{X.close()}}async function f9($,W={}){let Z=PV(W.config),Q=W.requestTimeoutMs??wV,J=$.metadata?.mode,j=J==="internal"||J==="external"?J:CV(W.mode),X=j==="external"?Z.external:Z.internal,Y=await bV(X.idcsUrl,Q),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:X.clientId}),B=await fetch(Y,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(Q)}),H=await B.json();if(!B.ok){let G=yV(H);throw new _9(`Token refresh failed: ${B.status}${G.message?` - ${G.message}`:""}`,{status:B.status,errorCode:G.code})}return SV(H,j,$)}async function G4($,W,Z){if(!$)return null;let Q=W?.refreshBufferMs??Z?.refreshBufferMs??_L,J=W?.retryableTokenGraceMs??Z?.retryableTokenGraceMs??fL;if(W?.forceRefresh!==!0&&!T8($,Q))return $;try{return await f9($,Z)}catch(X){if(X instanceof _9&&X.isLikelyInvalidGrant())return D$(Z?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}var L9="workos:";function wL($){let W=$.trim();return W.toLowerCase().startsWith(L9)?W:`${L9}${W}`}function CL($){let W=$.trim();return W.toLowerCase().startsWith(L9)?W.slice(L9.length):W}function PL($){let Z=EL($)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;return null}function SL($,W){let Z=$.auth?.expiresAt;if(typeof Z==="number"&&Number.isFinite(Z)&&Z>0)return Z;let Q=PL(W);if(Q)return Q;return Date.now()-1}function bL($,W){let Z=$.auth?.accessToken?.trim(),Q=$.auth?.refreshToken?.trim();if(!Z||!Q)return null;let J=W?.normalizeAccessToken?.(Z)??Z;if(!J)return null;return{access:J,refresh:Q,expires:SL($,J),accountId:$.auth?.accountId,metadata:$.auth?.metadata}}function yL($){let W=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Z={...$.settings?.auth??{},accessToken:W,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Q=Object.fromEntries(Object.entries($.credentials.metadata??{}).filter(([,X])=>X!==void 0)),J={...$.settings?.auth?.metadata??{},...Q};if(Object.keys(J).length>0)Z.metadata=J;let j={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Z};if($.save!==!1)$.manager.saveProviderSettings(j,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return j}function p7($){let W=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:W,getApiKey(Z){let Q=Z?.auth?.accessToken?.trim();if(Q)return $.formatAccessToken?.(Q)??Q;return Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Z){return yL({...Z,storageProviderId:W,formatAccessToken:$.formatAccessToken})},isConfigured(Z){return!!Z?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function IV($){return p7({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:wL,normalizeStoredAccessToken:CL,login:({settings:W,callbacks:Z,telemetry:Q})=>J4({apiBaseUrl:W?.baseUrl?.trim()||kV().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q}),refresh:({settings:W,credentials:Z,forceRefresh:Q,telemetry:J})=>j4(Z,{apiBaseUrl:W.baseUrl?.trim()||kV().apiBaseUrl,telemetry:J},{forceRefresh:Q})})}var hL=[IV({providerId:"cline"}),IV({providerId:"cline-pass",storageProviderId:"cline"}),p7({providerId:"oca",login:({settings:$,callbacks:W,telemetry:Z})=>H4({mode:$?.oca?.mode,callbacks:W,telemetry:Z}),refresh:({settings:$,credentials:W,forceRefresh:Z,telemetry:Q})=>G4(W,{forceRefresh:Z,telemetry:Q},{mode:$.oca?.mode,telemetry:Q})}),p7({providerId:"openai-codex",login:({callbacks:$,telemetry:W})=>X4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:W}),refresh:({credentials:$,forceRefresh:W,telemetry:Z})=>Y4($,{forceRefresh:W,telemetry:Z})})],kL=new Map(hL.map(($)=>[$.providerId,$]));function B0($){return kL.get($.trim().toLowerCase())}function L$($){return B0($)!==void 0}function r7($){return B0($)?.storageProviderId}function i7($,W){let Z=B0(W),Q=Z?.storageProviderId??W,J=$.getProviderSettings(Q);return Z?.getApiKey(J)??M8(W,J)}async function K4($,W,Z){let Q=B0(W);if(!Q)throw Error(`Provider "${W}" does not support OAuth login`);let J=$.getProviderSettings(Q.storageProviderId),j=await Q.login({settings:J,callbacks:Z.callbacks,telemetry:Z.telemetry});return Q.saveCredentials({manager:$,settings:J,credentials:j})}function F4($,W){let Z=B0($);if(!Z)return null;return bL(W,{normalizeAccessToken:Z.normalizeStoredAccessToken})}function j2($){let W=B0($.providerId);if(!W)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return W.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function M8($,W){let Z=B0($);if(Z)return Z.getApiKey(W);return W?.auth?.accessToken?.trim()||W?.apiKey?.trim()||W?.auth?.apiKey?.trim()||void 0}function n7($,W){let Z=B0($);if(!Z)return W.access;return Z.getApiKey({provider:Z.storageProviderId,auth:{accessToken:W.access}})??W.access}U0();var zB={};w(zB,{createContextCompactionPrepareTurn:()=>z4,createCompactionStateAwarePrepareTurn:()=>q4});import{estimateRequestInputTokens as LO}from"@cline/shared";var dV={};w(dV,{projectSessionCompactionState:()=>X2,parseSessionCompactionState:()=>A1,createSessionCompactionState:()=>R8,SessionCompactionStateSchema:()=>A4});import{createHash as IL}from"node:crypto";import{formatDisplayUserInput as gV}from"@cline/shared";import{z as q1}from"zod";function xL($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let W=$;if(W.role!=="user"&&W.role!=="assistant")return!1;return typeof W.content==="string"||Array.isArray(W.content)}var gL=q1.custom(xL),A4=q1.object({version:q1.literal(1),updated_at:q1.string().datetime(),conversation_id:q1.string().min(1).optional(),source_message_count:q1.number().int().nonnegative(),source_prefix_hash:q1.string().min(1).optional(),source_last_message_key:q1.string().min(1).optional(),messages:q1.array(gL),system_prompt:q1.string().optional()});function a7($){return JSON.parse(JSON.stringify($))}function mV($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:gV($.content)};return{...$,content:$.content.map((W)=>W.type==="text"?{...W,text:gV(W.text)}:W)}}function vV($){if($.includes(":"))throw TypeError("Message role cannot contain ':' in compaction boundary keys")}function mL($){let W=mV($);return vV(W.role),[["role",W.role],["content",W.content],["id",W.id??null],["agent",W.agent??null],["sessionId",W.sessionId??null],["metadata",W.metadata??null],["modelInfo",W.modelInfo??null],["metrics",W.metrics??null],["ts",W.ts??null]]}function cV($){if(!$)return"";let W=mV($);if(typeof W.id==="string"&&W.id.trim())return`id:${W.id.trim()}`;if(vV(W.role),typeof W.ts==="number"&&Number.isFinite(W.ts))return`ts:${W.role}:${W.ts}`;return`content:${W.role}:${JSON.stringify(W.content)}`}function uV($,W=$.length){let Z=IL("sha256");Z.update(`cline-session-compaction-source-v1
46
46
  `),Z.update(`${W}
47
- `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(gL(Q))),Z.update(`
48
- `);return`sha256:${Z.digest("hex")}`}function M8($){let W=$.sourceMessages.at(-1),Z=vV(W);return F4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:cV($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:a7($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function X2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&cV(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&vV(J)===$.source_last_message_key;if(!(Q||j))return;return[...a7($.messages),...a7(W.slice($.source_message_count))]}function K1($){let W=F4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as JO}from"@cline/llms";function mL($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function dV($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function q1($){try{return JSON.stringify($).length}catch{return String($).length}}function O9($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function iV($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function T9($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!iV(Z))return W}return-1}function vL($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!iV(Z))return W}return-1}function s7($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function cL($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of s7($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function o7($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function uL($,W){let Z=cL($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of s7($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function dL($){return $.type==="image"||$.type==="redacted_thinking"}function lL($){return $.type==="image"}function pL($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&dL($)}function lV($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:q1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function rL($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(pL(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:q1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&lL(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:q1(G),finalSize:q1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function iL($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:q1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function R8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
47
+ `);for(let Q of $.slice(0,W))Z.update(JSON.stringify(mL(Q))),Z.update(`
48
+ `);return`sha256:${Z.digest("hex")}`}function R8($){let W=$.sourceMessages.at(-1),Z=cV(W);return A4.parse({version:1,updated_at:$.updatedAt??new Date().toISOString(),...$.conversationId?.trim()?{conversation_id:$.conversationId.trim()}:{},source_message_count:$.sourceMessages.length,source_prefix_hash:uV($.sourceMessages),...Z?{source_last_message_key:Z}:{},messages:a7($.compactedMessages),...$.systemPrompt!==void 0?{system_prompt:$.systemPrompt}:{}})}function X2($,W){if(!($.source_message_count<=W.length))return;let Q=!!$.source_prefix_hash&&uV(W,$.source_message_count)===$.source_prefix_hash,J=W[$.source_message_count-1],j=!$.source_prefix_hash&&$.source_message_count>0&&!!$.source_last_message_key&&cV(J)===$.source_last_message_key;if(!(Q||j))return;return[...a7($.messages),...a7(W.slice($.source_message_count))]}function A1($){let W=A4.safeParse($);return W.success?W.data:void 0}import{createHandlerAsync as jO}from"@cline/llms";function vL($){switch($){case"agentic_summary":case"basic_compaction_projection":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!0,dropThinkingBlocks:!0};case"normal_provider_request":return{protectLatestTypedUser:!0,protectLiveTailFromDrop:!0,dropUnsafeOutsideLiveTail:!1,dropThinkingBlocks:!1}}}function lV($){return $.map((W)=>({...W,content:Array.isArray(W.content)?W.content.map((Z)=>({...Z})):W.content,...W.metadata?{metadata:{...W.metadata}}:{}}))}function M1($){try{return JSON.stringify($).length}catch{return String($).length}}function O9($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function nV($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function T9($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z.role==="user"&&!nV(Z))return W}return-1}function cL($){for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z.role==="user"&&!nV(Z))return W}return-1}function s7($){let W=new Set;if(!Array.isArray($.content))return W;for(let Z of $.content)if(Z.type==="tool_use")W.add(Z.id);else if(Z.type==="tool_result")W.add(Z.tool_use_id);return W}function uL($){let W=new Map;for(let Z=0;Z<$.length;Z+=1)for(let Q of s7($[Z])){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function o7($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(!Array.isArray(Q.content))continue;if(Q.content.some((J)=>J.type==="tool_use"&&!W.has(J.id)))return Z}return $.length}function dL($,W){let Z=uL($),Q=new Set,J=[W];while(J.length>0){let j=J.shift();if(j===void 0||Q.has(j))continue;Q.add(j);for(let X of s7($[j]))for(let Y of Z.get(X)??[])if(!Q.has(Y))J.push(Y)}return Q}function lL($){return $.type==="image"||$.type==="redacted_thinking"}function pL($){return $.type==="image"}function rL($,W,Z){if(W.dropThinkingBlocks&&$.type==="thinking")return!0;return W.dropUnsafeOutsideLiveTail&&!Z&&lL($)}function pV($,W,Z,Q="over_budget"){let J=[],j=[];for(let X=0;X<$.length;X+=1){let Y=$[X];if(Array.isArray(Y.content)&&Y.content.length===0){Z.push({kind:"dropped_message",path:{messageIndex:W[X]},reason:Q,originalSize:M1(Y),finalSize:0});continue}J.push(Y),j.push(W[X])}return{messages:J,originalIndexes:j}}function iL($,W,Z,Q,J,j){return $.map((X,Y)=>{if(!Array.isArray(X.content))return X;let V=!1,B=Y===Q||Y>=J,H=X.content.flatMap((G,K)=>{if(rL(G,j,B))return V=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:M1(G),finalSize:0}),[];if(G.type==="tool_result"&&Array.isArray(G.content)){let F=G.content.filter((A)=>{if(j.dropUnsafeOutsideLiveTail&&!B&&pL(A))return!1;return!0});if(F.length!==G.content.length){V=!0;let A={...G,content:F};return Z.push({kind:"dropped_block",path:{messageIndex:W[Y],blockIndex:K},reason:"unsafe_to_truncate",originalSize:M1(G),finalSize:M1(A)}),[A]}}return[G]});return V?{...X,content:H}:X})}function nL($,W,Z){return $.map((Q,J)=>{if(!Array.isArray(Q.content))return Q;let j=!1,X=Q.content.filter((Y,V)=>{if(Y.type!=="thinking")return!0;return j=!0,Z.push({kind:"dropped_block",path:{messageIndex:W[J],blockIndex:V},reason:"unsafe_to_truncate",originalSize:M1(Y),finalSize:0}),!1});return j?{...Q,content:X}:Q})}function N8($,W){if(W<=0)return"";if($.length<=W)return $;if(W<=16)return $.slice(0,Math.max(1,W));let Z=`
49
49
  ...[truncated ${$.length-W} chars]`,Q=Math.max(1,W-Z.length),J=`
50
- ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function pV($,W){if(typeof $==="string")return R8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=R8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=R8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function nL($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function aL($,W){if(typeof $.content==="string")return{...$,content:R8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:pV(Q.content,0)};return Q}if(Q.type==="text"){let J=R8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=R8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=pV(Q.content,Z);return Z-=nL(J),{...Q,content:J}}return Q})}}function oL($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function sL($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function tL($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function rV($,W){return W>=0&&$.has(W)}function A4($){let W=[],Z=[],Q=mL($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:dV($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:O9($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=dV($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=lV(iL(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?T9(J):-1,Y=Q.protectLiveTailFromDrop?o7(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=lV(rL(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=O9(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=T9(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=o7(J))continue;if(!oL(J[B]))continue;let G=q1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=aL(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:q1(J[B])}),V=O9(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=vL(J),G=T9(J),K=Q.protectLiveTailFromDrop?o7(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:q1(J[B]),finalSize:q1(J[B])}),B+=1;continue}let F=uL(J,B);if(rV(F,H)){B+=1;continue}if(rV(F,G)){B+=1;continue}if(tL(F,K)){B+=1;continue}for(let D of F)W.push({kind:"dropped_message",path:{messageIndex:j[D]},reason:F.size>1||s7(J[D]).size>0?"tool_pair_boundary":"over_budget",originalSize:q1(J[D]),finalSize:0});let A=sL(J,j,F);J=A.messages,j=A.originalIndexes,V=O9(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as wc,estimateTokens as z9}from"@cline/shared";var sV=128000,eL=0.9,Y2=0.9,tV=0.7,eV=20000,nV=1024,aV=2000,$B=2000,WB=8;function oV($){return typeof $==="number"&&Number.isFinite($)&&$>0}function f4($){let W=oV($.contextWindow)?$.contextWindow:void 0,Z=oV($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*eL}function _4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
51
- ...[truncated ${$.length-W} chars]`}function $O($){let W=t7($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
50
+ ...[truncated ${$.length-Q} chars]`;return`${$.slice(0,Q)}${J}`}function rV($,W){if(typeof $==="string")return N8($,W);let Z=W;return $.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};return Q}if(Q.type==="text"){let J=N8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=N8(Q.content,Z);return Z-=J.length,{...Q,content:J}}return Q})}function aL($){if(typeof $==="string")return $.length;return $.reduce((W,Z)=>{if(Z.type==="text")return W+Z.text.length;if(Z.type==="file")return W+Z.content.length;return W},0)}function oL($,W){if(typeof $.content==="string")return{...$,content:N8($.content,W)};let Z=W;return{...$,content:$.content.map((Q)=>{if(Z<=0){if(Q.type==="text")return{...Q,text:""};if(Q.type==="file")return{...Q,content:""};if(Q.type==="tool_result")return{...Q,content:rV(Q.content,0)};return Q}if(Q.type==="text"){let J=N8(Q.text,Z);return Z-=J.length,{...Q,text:J}}if(Q.type==="file"){let J=N8(Q.content,Z);return Z-=J.length,{...Q,content:J}}if(Q.type==="tool_result"){let J=rV(Q.content,Z);return Z-=aL(J),{...Q,content:J}}return Q})}}function sL($){if(typeof $.content==="string")return $.content.length>0;return $.content.some((W)=>W.type==="text"||W.type==="file"||W.type==="tool_result")}function tL($,W,Z){return{messages:$.filter((Q,J)=>!Z.has(J)),originalIndexes:W.filter((Q,J)=>!Z.has(J))}}function eL($,W){if(W<0)return!1;for(let Z of $)if(Z>=W)return!0;return!1}function iV($,W){return W>=0&&$.has(W)}function U4($){let W=[],Z=[],Q=vL($.policyIntent);if($.targetTokens<=0)return{status:"failed",messages:lV($.messages),actions:W,liveTailHandling:"preserved_out_of_band",estimatedTokens:O9($.messages,$.estimateMessageTokens),warnings:[{code:"budget_impossible",message:"Target budget must be greater than zero."}]};let J=lV($.messages),j=J.map((B,H)=>H);if(Q.dropThinkingBlocks){let B=pV(nL(J,j,W),j,W,"unsafe_to_truncate");J=B.messages,j=B.originalIndexes}let X=Q.protectLatestTypedUser?T9(J):-1,Y=Q.protectLiveTailFromDrop?o7(J):J.length;if(Q.dropUnsafeOutsideLiveTail){let B=pV(iL(J,j,W,X,Y,Q),j,W);J=B.messages,j=B.originalIndexes}let V=O9(J,$.estimateMessageTokens);if(V<=$.targetTokens)return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z};for(let B=J.length-1;B>=0&&V>$.targetTokens;B-=1){let H=T9(J);if(B===H)continue;if(Q.protectLiveTailFromDrop&&B>=o7(J))continue;if(!sL(J[B]))continue;let G=M1(J[B]),K=Math.max(1,G/Math.max(1,$.estimateMessageTokens(J[B]))),F=Math.max(16,Math.floor($.targetTokens*K/Math.max(1,J.length)));J[B]=oL(J[B],F),W.push({kind:"truncated_text",path:{messageIndex:j[B]},reason:"over_budget",originalSize:G,finalSize:M1(J[B])}),V=O9(J,$.estimateMessageTokens)}for(let B=0;B<J.length&&V>$.targetTokens;){let H=cL(J),G=T9(J),K=Q.protectLiveTailFromDrop?o7(J):J.length;if(B===H||B===G){W.push({kind:"preserved",path:{messageIndex:j[B]},reason:"protected_live_tail",originalSize:M1(J[B]),finalSize:M1(J[B])}),B+=1;continue}let F=dL(J,B);if(iV(F,H)){B+=1;continue}if(iV(F,G)){B+=1;continue}if(eL(F,K)){B+=1;continue}for(let D of F)W.push({kind:"dropped_message",path:{messageIndex:j[D]},reason:F.size>1||s7(J[D]).size>0?"tool_pair_boundary":"over_budget",originalSize:M1(J[D]),finalSize:0});let A=tL(J,j,F);J=A.messages,j=A.originalIndexes,V=O9(J,$.estimateMessageTokens)}if(V>$.targetTokens)return Z.push({code:"budget_unachievable_with_protections",message:"Projection could not reach budget without violating protected content."}),{status:"failed",messages:J,actions:W,liveTailHandling:"included_degraded",estimatedTokens:V,warnings:Z};return{status:"ok",messages:J,actions:W,liveTailHandling:W.length>0?"included_degraded":"included_verbatim",estimatedTokens:V,warnings:Z}}import{CHARS_PER_TOKEN as hc,estimateTokens as z9}from"@cline/shared";var tV=128000,$O=0.9,Y2=0.9,eV=0.7,$B=20000,aV=1024,oV=2000,WB=2000,ZB=8;function sV($){return typeof $==="number"&&Number.isFinite($)&&$>0}function L4($){let W=sV($.contextWindow)?$.contextWindow:void 0,Z=sV($.maxInputTokens)?$.maxInputTokens:void 0;if(Z!==void 0)return W===void 0?Z:Math.min(Z,W);return W===void 0?void 0:W*$O}function f4($,W){if($.length<=W)return $;return`${$.slice(0,W)}
51
+ ...[truncated ${$.length-W} chars]`}function WO($){let W=t7($);if(typeof W==="string")return W;return W.map((Z)=>{switch(Z.type){case"text":return Z.text;case"file":return`<file path="${Z.path}">
52
52
  ${Z.content}
53
53
  </file>`;case"image":return`[image:${Z.mediaType}]`;default:return""}}).join(`
54
- `)}function t7($){if(typeof $==="string")return _4($,aV);return $.map((W)=>{switch(W.type){case"text":return{...W,text:_4(W.text,aV)};case"file":return{...W,content:_4(W.content,$B)};case"image":return W;default:return W}})}function WO($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function ZB($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${_4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${WO(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${$O(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${_4(Z.content,$B)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
55
- `)}function QB($){return $.map(ZB).join(`
54
+ `)}function t7($){if(typeof $==="string")return f4($,oV);return $.map((W)=>{switch(W.type){case"text":return{...W,text:f4(W.text,oV)};case"file":return{...W,content:f4(W.content,WB)};case"image":return W;default:return W}})}function ZO($){return Object.entries($).map(([W,Z])=>`${W}=${JSON.stringify(Z)}`).join(", ")}function QB($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let W=[];for(let Z of $.content)switch(Z.type){case"text":W.push(`[${$.role==="user"?"User":"Bot"}]: ${Z.text}`);break;case"thinking":W.push(`[Bot thinking]: ${f4(Z.thinking,2000)}`);break;case"redacted_thinking":W.push("[Bot thinking]: [redacted]");break;case"tool_use":W.push(`[Bot tool calls]: ${Z.name}(${ZO(Z.input)})`);break;case"tool_result":W.push(`[Tool result]: ${WO(Z.content)}`);break;case"file":W.push(`[${$.role==="user"?"User":"Bot"} file ${Z.path}]: ${f4(Z.content,WB)}`);break;case"image":W.push(`[${$.role==="user"?"User":"Bot"} image]: ${Z.mediaType}`);break}return W.join(`
55
+ `)}function JB($){return $.map(QB).join(`
56
56
 
57
- `).trim()}function JB(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=ZB(W)}let j=z9(J.length);return $.set(Z,j),j}}function L4($){return $.metadata?.kind==="compaction_summary"}function e7($){if(!L4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function ZO($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function O4($){return $.role==="user"&&!ZO($)&&!L4($)}function jB($){for(let W=0;W<$.length;W+=1)if(O4($[W]))return W;return-1}function q9($){for(let W=$.length-1;W>=0;W-=1)if(O4($[W]))return W;return 0}function XB($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function YB($){for(let W=$.length-1;W>=0;W-=1)if(L4($[W]))return W;return-1}function VB($,W,Z){let Q=q9($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!O4($[X]))X-=1;return X}function D4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>D4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(...D4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(...D4(Q.path))}if(Array.isArray(W.file_paths))Z.push(...D4(W.file_paths));return Z}return[]}function U4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function $3($){let W=[],Z=[];for(let Q of $){let J=e7(Q);if(J){W=U4(W,J.details.readFiles),Z=U4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=U4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=D4(j.input);if(j.name==="read_files"){W=U4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=U4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function QO($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
57
+ `).trim()}function jB(){let $=new WeakMap;return(W)=>{let Z=W,Q=$.get(Z);if(typeof Q==="number")return Q;let J;try{J=JSON.stringify(W)}catch{J=QB(W)}let j=z9(J.length);return $.set(Z,j),j}}function O4($){return $.metadata?.kind==="compaction_summary"}function e7($){if(!O4($))return;let W=$.metadata;if(!W)return;let Z=W.details;return{kind:"compaction_summary",summary:String(W.summary??""),details:{readFiles:Array.isArray(Z?.readFiles)?Z.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(Z?.modifiedFiles)?Z.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(W.tokensBefore??0),generatedAt:Number(W.generatedAt??0)}}function QO($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((W)=>W.type==="tool_result")}function T4($){return $.role==="user"&&!QO($)&&!O4($)}function XB($){for(let W=0;W<$.length;W+=1)if(T4($[W]))return W;return-1}function q9($){for(let W=$.length-1;W>=0;W-=1)if(T4($[W]))return W;return 0}function YB($){for(let W=$.length-1;W>=0;W-=1)if($[W].role==="assistant")return W;return-1}function VB($){for(let W=$.length-1;W>=0;W-=1)if(O4($[W]))return W;return-1}function BB($,W,Z){let Q=q9($);if(Q<=0)return 0;let J=0,j=$.length;for(let Y=$.length-1;Y>=0;Y-=1)if(J+=Z($[Y]),j=Y,J>=W)break;if(j<=0)return 0;let X=Math.min(j,Q);while(X>0&&!T4($[X]))X-=1;return X}function _4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((W)=>_4(W));if($&&typeof $==="object"){let W=$,Z=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])Z.push(..._4(W[Q]));if(Array.isArray(W.files)){for(let Q of W.files)if(Q&&typeof Q==="object")Z.push(..._4(Q.path))}if(Array.isArray(W.file_paths))Z.push(..._4(W.file_paths));return Z}return[]}function D4($,W){let Z=new Set($);for(let Q of W){let J=Q.trim();if(!J)continue;Z.add(J)}return[...Z].sort((Q,J)=>Q.localeCompare(J))}function $3($){let W=[],Z=[];for(let Q of $){let J=e7(Q);if(J){W=D4(W,J.details.readFiles),Z=D4(Z,J.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let j of Q.content){if(j.type==="file"){W=D4(W,[j.path]);continue}if(j.type!=="tool_use")continue;let X=_4(j.input);if(j.name==="read_files"){W=D4(W,X);continue}if(j.name==="editor"||j.name==="apply_patch")Z=D4(Z,X)}}return{readFiles:W,modifiedFiles:Z}}function JO($){let W=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
58
58
  `):"- none",Z=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
59
59
  `):"- none";return`## Files
60
60
  Read:
61
61
  ${W}
62
62
  Modified:
63
- ${Z}`}function BB($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
63
+ ${Z}`}function HB($,W){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
64
64
 
65
- ${QO(W)}`.trim()}function W3($){let W=[`Summarize this session for continuation. Be concise and factual.
65
+ ${JO(W)}`.trim()}function W3($){let W=[`Summarize this session for continuation. Be concise and factual.
66
66
 
67
67
  ## Goal
68
68
  One sentence: what is being built or fixed.
@@ -84,20 +84,20 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
84
84
  ${$.previousSummary.trim()}`);return W.push(`Conversation:
85
85
  ${$.conversationText||"(empty)"}`),W.join(`
86
86
 
87
- `)}function HB($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??nV,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??nV})}function GB($){return{role:"user",content:`Context summary:
87
+ `)}function GB($){let W=$.summarizer,Z=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:j,...X}=J;return{...X,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??aV,thinking:!1}};if(!W)return Z($.activeProviderConfig);let Q=W.providerConfig?.providerId===W.providerId?W.providerConfig:void 0;return Z({...Q??{},providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey??Q?.apiKey,baseUrl:W.baseUrl??Q?.baseUrl,headers:W.headers??Q?.headers,modelInfo:W.modelInfo??Q?.modelInfo,knownModels:W.knownModels??Q?.knownModels,maxOutputTokens:W.maxOutputTokens??aV})}function KB($){return{role:"user",content:`Context summary:
88
88
 
89
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var Z3=1024;function jO($){let W=f4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return f4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function XO($){return A4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function YO($){let W=await JO($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function VO($){try{return JSON.stringify($).length}catch{return String($).length}}async function KB($){let W=$.context.messages;if(W.length<2)return;let Z=VB(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=YB(Q),j=J>=0?e7(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=$3(Q),V=HB({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=jO(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,Z3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:Z3});let K=B??(H?G:Z3),F=z9(W3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let D=XO({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(D.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:D.warnings.map((p)=>p.code),summaryInputEstimatedTokens:D.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=$3(D.messages),f=QB(D.messages),_=W3({previousSummary:j,conversationText:f,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:f.length,summaryRequestChars:_.length,summaryRequestEstimatedTokens:z9(_.length),newMessagesJsonChars:VO(X),summaryInputEstimatedTokens:D.estimatedTokens,summaryInputActions:D.actions.length,summaryInputWarnings:D.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let R=await YO({providerConfig:V,request:_,logger:$.logger});if(!R.trim())return;let T=BB(R,U),O=W.reduce((p,x)=>p+$.estimateMessageTokens(x),0),L=[GB({summary:T,fileOps:U,tokensBefore:O}),...W.slice(Z)],C=L.reduce((p,x)=>p+$.estimateMessageTokens(x),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:O,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let N=D.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:N,warningCount:D.warnings.length,liveTailHandling:D.liveTailHandling}}}import{CHARS_PER_TOKEN as BO}from"@cline/shared";function HO($){if(L4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:t7(Z.content)}:Z)}}function FB($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function AB($,W){if($.length<=W)return $;let Z=`
90
- ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function UB($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*BO);if(typeof $.content==="string"){let X=AB($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=AB(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function GO($,W){let Z=jB($),Q=q9($),J=XB($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=HO($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:_B(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function DB($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=_B(Z),J.estimatedTokens-j}function _B($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function KO($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function FO($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function AO($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function M9($,W,Z,Q){let J=new Set($),j=KO($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=FO(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,AO($,Y)}return Q}function UO($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(WB,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=DB($,X,UB(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=DB($,j,UB(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function DO($,W){return JSON.stringify($)!==JSON.stringify(W)}function _O($){let W=q9($);if(W<0||W===0&&!O4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function fB($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=_O($.context.messages);if(Z.length===0)return;let J=FB(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=GO(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=M9(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=M9(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=M9(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=M9(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=UO(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=A4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!DO($.context.messages,K))return;let F=V+J,A=FB(K,$.estimateMessageTokens),D=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:D,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:D,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var LO=0.5;function OB($){try{return JSON.stringify($).length}catch{return String($).length}}function OO($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=OB(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var TO={basic:({context:$,estimateMessageTokens:W,logger:Z})=>fB({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>KB({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??eV,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function zO($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function qO($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*LO):Math.floor($.triggerTokens*tV),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function LB($,W){return Math.max(1,Math.floor($-W))}function MO($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function T4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=JB(),j=Z?.strategy??"basic",X=TO[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,d)=>r+J(d),0),G=fO({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,d)=>r+J(d),0),F=Math.max(0,G-H),A=f4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??sV,D=A*Y2,U=LB(D,F),f=G>=D;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:D,messageTriggerTokens:U,thresholdRatio:Y2,shouldCompact:f,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:OB(B.apiMessages),...OO(B.apiMessages)}),Y==="auto"&&!f)return;let _,R;if(Y==="auto")_=qO({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:D,messagePairCount:MO(B.messages)}),R=LB(_,F);else R=zO({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),_=F+R;let T={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:D,targetTokens:_,overheadTokens:F,thresholdRatio:Y2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:R}}},O=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:O,reason:O,phase:"started",iteration:B.iteration,triggerTokens:D,targetTokens:_,maxInputTokens:A,messageTargetTokens:R});let L=B.messages.length,C=Date.now(),N=Z?.compact?await Z.compact(T):await X({context:T,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,x=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(N?.messages){let r=N.messages.reduce((x1,W2)=>x1+J(W2),0),d=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:d,tokensSaved:G-d,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(d/A*100).toFixed(1)}%`,thresholdTrigger:`${(Y2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:O,reason:O,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:d,messagesBefore:L,messagesAfter:N.messages.length,maxInputTokens:A}),Y9($.telemetry,{ulid:x,strategy:V,mode:Y,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length,tokensBefore:G,tokensAfter:d,tokensSaved:G-d,triggerTokens:D,maxInputTokens:A,thresholdRatio:Y2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),N.budget&&(N.budget.actionCount>0||N.budget.warningCount>0))YV($.telemetry,{ulid:x,strategy:V,mode:Y,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount,liveTailHandling:N.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:O,reason:O,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),V9($.telemetry,{ulid:x,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:D,maxInputTokens:A,thresholdRatio:Y2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return N}}function z4($){return async(W)=>{let Z=$.getState?.(),Q=Z?X2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=M8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=M8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var YG={};w(YG,{zodToJsonSchema:()=>Iq,validateWithZod:()=>kq,truncateCommandOutput:()=>G2,resolveToolRoutingConfig:()=>k8,resolveToolPresetName:()=>i1,resolveCoreSelectedToolIds:()=>s9,getCoreHeadlessToolNames:()=>l4,getCoreDefaultEnabledToolIds:()=>o9,getCoreBuiltinToolCatalog:()=>R2,getCoreAcpToolNames:()=>t9,createWebFetchTool:()=>V3,createWebFetchExecutor:()=>k4,createToolPoliciesWithPreset:()=>k9,createSubmitAndExitTool:()=>K3,createSkillsTool:()=>F2,createShellTool:()=>b4,createShellExecutor:()=>K2,createSearchTool:()=>Y3,createSearchExecutor:()=>h4,createReadFilesTool:()=>X3,createFileReadExecutor:()=>y4,createEditorTool:()=>H3,createEditorExecutor:()=>D2,createDefaultToolsWithPreset:()=>I9,createDefaultTools:()=>q$,createDefaultShellExecutor:()=>I4,createDefaultExecutors:()=>y8,createBuiltinTools:()=>N2,createAskQuestionTool:()=>G3,createApplyPatchTool:()=>B3,createApplyPatchExecutor:()=>U2,computePatchChanges:()=>P8,WebFetchRequestSchema:()=>Q3,ToolPresets:()=>a0,TEAM_TOOL_NAMES:()=>g8,SubmitInputSchema:()=>S4,StructuredCommandInputSchema:()=>B2,SkillsInputSchema:()=>C4,SearchCodebaseInputSchema:()=>M4,RunCommandsInputSchema:()=>R4,ReadFilesInputSchema:()=>q4,ReadFileRequestSchema:()=>w9,PatchActionType:()=>A2,MAX_COMMAND_OUTPUT_CHARS:()=>d1,FetchWebContentInputSchema:()=>N4,EditFileInputSchema:()=>E4,DefaultToolNames:()=>z0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>h8,CommandExitError:()=>l1,AskQuestionInputSchema:()=>P4,ApplyPatchInputSchema:()=>w4,ALL_DEFAULT_TOOL_NAMES:()=>L$});import{validateWithZod as kq,zodToJsonSchema as Iq}from"@cline/shared";var z0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},L$=[z0.READ_FILES,z0.SEARCH_CODEBASE,z0.RUN_COMMANDS,z0.FETCH_WEB_CONTENT,z0.APPLY_PATCH,z0.EDITOR,z0.SKILLS,z0.ASK,z0.SUBMIT_AND_EXIT];D0();import{createTool as T$,validateWithZod as z$,zodToJsonSchema as p1}from"@cline/shared";var R9="__clineInternalTelemetry";function zB($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as kB}from"node:child_process";import{StringDecoder as PO}from"node:string_decoder";import{getDefaultShell as SO,getShellArgs as bO}from"@cline/shared";import{validateWithZod as NO}from"@cline/shared";import{z}from"zod";var O$=6000,V2=z.string().describe("The absolute path of a text file to read content from"),N9=z.object({start_line:z.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:z.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),w9=z.object({path:V2,start_line:N9.shape.start_line,end_line:N9.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),q4=z.object({files:z.array(w9).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),qB={start_line:N9.shape.start_line,end_line:N9.shape.end_line},N8=z.union([w9,z.object({file_path:V2,...qB}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:V2,...qB}).transform(({filePath:$,...W})=>({path:$,...W}))]),MB=z.union([q4,N8,z.array(N8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([V2,N8]))}),z.object({files:N8}),z.object({files:V2}),z.object({file_paths:z.array(V2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([V2,N8]))}),z.object({paths:N8}),z.object({paths:z.string()})]),M4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),RB=z.union([M4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),E9=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${O$*2} characters) to avoid timeouts.`),B2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),NB=z.union([E9,B2]),R4=z.object({commands:z.array(E9).describe("Array of complete shell command strings to execute.")}),RO=z.object({commands:z.array(NB)}),EB=z.union([R4,RO,z.object({commands:NB}),z.array(B2),B2,z.object({command:E9}),z.object({cmd:E9}),z.array(z.string()),z.string()]),Q3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),N4=z.object({requests:z.array(Q3).describe("Array of the URLs for the web fetch requests")}),E4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${O$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${O$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:z.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),w4=z.object({input:z.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),wB=z.union([w4,z.string()]),C4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),P4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),S4=z.object({summary:z.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:z.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
89
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}var Z3=1024;function XO($){let W=L4({maxInputTokens:$.maxInputTokens??$.modelInfo?.maxInputTokens,contextWindow:$.modelInfo?.contextWindow});if(W!==void 0)return W;let Z=$.knownModels?.[$.modelId];return L4({maxInputTokens:Z?.maxInputTokens,contextWindow:Z?.contextWindow})}function YO($){return U4({messages:$.messages,targetTokens:Math.max(1,$.targetTokens),policyIntent:"agentic_summary",estimateMessageTokens:$.estimateMessageTokens})}async function VO($){let W=await jO($.providerConfig),Z="";for await(let Q of W.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){Z+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Z.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Z.trim()}function BO($){try{return JSON.stringify($).length}catch{return String($).length}}async function FB($){let W=$.context.messages;if(W.length<2)return;let Z=BB(W,$.preserveRecentTokens,$.estimateMessageTokens);if(Z<=0||Z>=W.length)return;let Q=W.slice(0,Z),J=VB(Q),j=J>=0?e7(Q[J])?.summary:void 0,X=J>=0?Q.slice(J+1):Q;if(X.length===0)return;let Y=$3(Q),V=GB({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),B=XO(V),H=$.summarizer===void 0,G=Math.max($.context.budget.request.maxInputTokens,$.context.budget.request.triggerTokens,Z3);if(B===void 0&&!H)$.logger?.log("Agentic compaction summarizer has no known input limit; using conservative summary budget",{severity:"warn",summarizerProviderId:V.providerId,summarizerModelId:V.modelId,fallbackInputLimit:Z3});let K=B??(H?G:Z3),F=z9(W3({previousSummary:j,conversationText:"",fileOps:Y}).length),A=K-F;if(A<=0){$.logger?.debug("Skipped agentic compaction: summarizer budget exhausted",{summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,summaryRequestOverheadTokens:F});return}let D=YO({messages:X,targetTokens:A,estimateMessageTokens:$.estimateMessageTokens});if(D.status==="failed"){$.logger?.log("Skipped agentic compaction: summary input budget failed",{severity:"warn",budgetWarnings:D.warnings.map((p)=>p.code),summaryInputEstimatedTokens:D.estimatedTokens,targetTokens:A,summarizerProviderId:V.providerId,summarizerModelId:V.modelId});return}let U=$3(D.messages),f=JB(D.messages),_=W3({previousSummary:j,conversationText:f,fileOps:U});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:X.length,preservedMessages:W.length-Z,previousSummaryChars:j?.length??0,conversationTextChars:f.length,summaryRequestChars:_.length,summaryRequestEstimatedTokens:z9(_.length),newMessagesJsonChars:BO(X),summaryInputEstimatedTokens:D.estimatedTokens,summaryInputActions:D.actions.length,summaryInputWarnings:D.warnings.map((p)=>p.code),summaryRequestOverheadTokens:F,summarizerProviderId:V.providerId,summarizerModelId:V.modelId,summarizerInputLimit:K,maxInputTokens:$.context.budget.request.maxInputTokens,triggerTokens:$.context.budget.request.triggerTokens});let R=await VO({providerConfig:V,request:_,logger:$.logger});if(!R.trim())return;let T=HB(R,U),O=W.reduce((p,k)=>p+$.estimateMessageTokens(k),0),L=[KB({summary:T,fileOps:U,tokensBefore:O}),...W.slice(Z)],C=L.reduce((p,k)=>p+$.estimateMessageTokens(k),0);$.logger?.debug("Performed agentic compaction",{messagesBefore:W.length,messagesAfter:L.length,messagesSummarized:Z,messagesPreserved:W.length-Z,tokensBefore:O,tokensAfter:C,maxInputTokens:$.context.budget.request.maxInputTokens});let N=D.actions.filter((p)=>p.reason==="over_budget"||p.reason==="tool_pair_boundary").length;return{messages:L,budget:{policyIntent:"agentic_summary",actionCount:N,warningCount:D.warnings.length,liveTailHandling:D.liveTailHandling}}}import{CHARS_PER_TOKEN as HO}from"@cline/shared";function GO($){if(O4($))return;if(typeof $.content==="string"){let Z=$.content.trim();return Z?{...$,content:Z}:void 0}let W=$.content.filter((Z)=>Z.type!=="text"||Z.text.trim());if(W.length===0)return;return{...$,content:W.map((Z)=>Z.type==="text"?{...Z,text:Z.text.trim()}:Z.type==="tool_result"?{...Z,content:t7(Z.content)}:Z)}}function AB($,W){return $.reduce((Z,Q)=>Z+W(Q),0)}function UB($,W){if($.length<=W)return $;let Z=`
90
+ ...`,Q=Math.max(1,W-Z.length);return`${$.slice(0,Q)}${Z}`}function DB($,W){let Z=Number.isFinite(W)?Math.max(1,W):1,Q=Math.max(16,Z*HO);if(typeof $.content==="string"){let X=UB($.content,Q).trim();return{...$,content:X||"..."}}let J=Q,j=$.content.map((X)=>{if(X.type!=="text"||J<=0)return X;let Y=UB(X.text,J).trim();return J-=Y.length,{...X,text:Y||"..."}});return{...$,content:j}}function KO($,W){let Z=XB($),Q=q9($),J=YB($),j=[],X=0;for(let Y=0;Y<$.length;Y+=1){let V=GO($[Y]);if(!V)continue;let B=W(V);X+=B,j.push({index:Y,message:V,estimatedTokens:B,toolPairIds:fB(V),isFirstUser:Y===Z,isLastUser:Y===Q,isLastAssistant:Y===J})}return{candidates:j,totalTokens:X}}function _B($,W,Z,Q){let J=$[W],j=J.estimatedTokens;return J.message=Z,J.estimatedTokens=Q(Z),J.toolPairIds=fB(Z),J.estimatedTokens-j}function fB($){if(!Array.isArray($.content))return[];let W=[];for(let Z of $.content)if(Z.type==="tool_use")W.push(Z.id);else if(Z.type==="tool_result")W.push(Z.tool_use_id);return W}function FO($){let W=new Map;for(let Z of $)for(let Q of Z.toolPairIds){let J=W.get(Q);if(J)J.add(Z);else W.set(Q,new Set([Z]))}return W}function AO($,W,Z){let Q=new Set,J=[Z],j=0;while(j<J.length){let X=J[j];if(j+=1,X===void 0||!$.has(X)||Q.has(X))continue;Q.add(X);for(let Y of X.toolPairIds)for(let V of W.get(Y)??[])if(!Q.has(V))J.push(V)}return Q}function UO($,W){let Z=0;for(let Q of $){if(W.has(Q))continue;$[Z]=Q,Z+=1}$.length=Z}function M9($,W,Z,Q){let J=new Set($),j=FO($);for(let X=0;X<$.length&&Q>Z;){if(!W($[X])){X+=1;continue}let Y=AO(J,j,$[X]);if(Y.size===0){X+=1;continue}let V=0;for(let B of Y)V+=B.estimatedTokens,J.delete(B);Q-=V,UO($,Y)}return Q}function DO($,W,Z,Q,J){if(Z<=W)return Z;for(let X=$.length-1;X>=0&&Z>W;X-=1){let Y=$[X];if(Y.isFirstUser)continue;let V=Math.max(ZB,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)continue;Z+=_B($,X,DB(Y.message,V),J)}if(Z<=W)return Z;let j=$.findIndex((X)=>X.isFirstUser);if(j>=0){if($[j].estimatedTokens<=Q)return Z;while(Z>W){let Y=$[j],V=Math.max(1,Y.estimatedTokens-(Z-W));if(V>=Y.estimatedTokens)break;let B=Y.estimatedTokens;if(Z+=_B($,j,DB(Y.message,V),J),Y.estimatedTokens>=B)break}}return Z}function _O($,W){return JSON.stringify($)!==JSON.stringify(W)}function fO($){let W=q9($);if(W<0||W===0&&!T4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,W),protectedTail:$.slice(W)}}function LB($){let W=Math.max(1,Math.min($.context.budget.messages.targetTokens,$.context.budget.messages.triggerTokens)),{compactable:Z,protectedTail:Q}=fO($.context.messages);if(Z.length===0)return;let J=AB(Q,$.estimateMessageTokens),j=Math.max(1,W-J),X=KO(Z,$.estimateMessageTokens),{candidates:Y}=X;if(Y.length===0)return;let V=X.totalTokens,B=V;B=M9(Y,(U)=>U.message.role==="assistant"&&!U.isLastAssistant,j,B),B=M9(Y,(U)=>U.message.role==="user"&&!U.isFirstUser&&!U.isLastUser,j,B),B=M9(Y,(U)=>U.message.role==="assistant"&&U.isLastAssistant,j,B),B=M9(Y,(U)=>U.message.role==="user"&&U.isLastUser&&!U.isFirstUser,j,B),B=DO(Y,j,B,$.context.budget.messages.triggerTokens,$.estimateMessageTokens);let H=[...Y.map((U)=>U.message),...Q],G=U4({messages:H,targetTokens:W,policyIntent:"basic_compaction_projection",estimateMessageTokens:$.estimateMessageTokens});if(G.status==="failed")$.logger?.debug("Basic compaction returned best-effort projection",{budgetWarnings:G.warnings.map((U)=>U.code),projectedTokens:G.estimatedTokens,targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens});let K=G.messages;if(!_O($.context.messages,K))return;let F=V+J,A=AB(K,$.estimateMessageTokens),D=G.actions.filter((U)=>U.reason==="over_budget"||U.reason==="tool_pair_boundary").length;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:K.length,messagesRemoved:$.context.messages.length-K.length,tokensBefore:F,tokensAfter:A,budgetStatus:G.status,budgetActions:D,budgetWarnings:G.warnings.map((U)=>U.code),targetTokens:W,maxInputTokens:$.context.budget.request.maxInputTokens}),{messages:K,budget:{policyIntent:"basic_compaction_projection",actionCount:D,warningCount:G.warnings.length,liveTailHandling:G.liveTailHandling}}}var OO=0.5;function TB($){try{return JSON.stringify($).length}catch{return String($).length}}function TO($){let W=0,Z=0,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result")continue;let X=TB(j.content);W+=1,Z+=X,Q=Math.max(Q,X)}}return{toolResultCount:W,toolResultSerializedChars:Z,maxToolResultSerializedChars:Q}}var zO={basic:({context:$,estimateMessageTokens:W,logger:Z})=>LB({context:$,estimateMessageTokens:W,logger:Z}),agentic:({context:$,providerConfig:W,compaction:Z,estimateMessageTokens:Q,logger:J})=>FB({context:$,providerConfig:W,summarizer:Z?.summarizer,preserveRecentTokens:Math.min(Z?.preserveRecentTokens??$B,$.budget.messages.targetTokens),estimateMessageTokens:Q,logger:J})};function qO($){let W=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Z=Math.min(0.95,Math.max(0.05,W));return Math.max(1,Math.floor(Math.min($.messageTriggerTokens,$.messageInputTokens*Z)))}function MO($){let W=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*OO):Math.floor($.triggerTokens*eV),Z=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(W,$.maxInputTokens,Z))}function OB($,W){return Math.max(1,Math.floor($-W))}function RO($){let W=0,Z=!1;for(let Q of $)if(Q.role==="user")Z=!0;else if(Q.role==="assistant"&&Z)W+=1,Z=!1;return W}function z4($,W={}){let Z=$.compaction;if(Z?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=jB(),j=Z?.strategy??"basic",X=zO[j],Y=W.mode??"auto",V=Z?.compact?"custom":j;return async(B)=>{let H=B.apiMessages.reduce((r,c)=>r+J(c),0),G=LO({systemPrompt:B.systemPrompt,messages:B.apiMessages,tools:B.tools}),K=B.messages.reduce((r,c)=>r+J(c),0),F=Math.max(0,G-H),A=L4({maxInputTokens:B.model.info?.maxInputTokens,contextWindow:B.model.info?.contextWindow})??tV,D=A*Y2,U=OB(D,F),f=G>=D;if($.logger?.debug("Context compaction diagnostics",{mode:Y,strategy:j,iteration:B.iteration,providerId:$.providerId,modelId:$.modelId,requestInputTokens:G,apiMessageTokens:H,messageInputTokens:K,requestOverheadTokens:F,maxInputTokens:A,requestTriggerTokens:D,messageTriggerTokens:U,thresholdRatio:Y2,shouldCompact:f,messageCount:B.messages.length,apiMessageCount:B.apiMessages.length,apiMessagesJsonChars:TB(B.apiMessages),...TO(B.apiMessages)}),Y==="auto"&&!f)return;let _,R;if(Y==="auto")_=MO({maxInputTokens:A,modelMaxTokens:B.model.info?.maxTokens,triggerTokens:D,messagePairCount:RO(B.messages)}),R=OB(_,F);else R=qO({messageInputTokens:K,messageTriggerTokens:U,manualTargetRatio:W.manualTargetRatio}),_=F+R;let T={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId,iteration:B.iteration,messages:B.messages,model:B.model,mode:Y,budget:{request:{inputTokens:G,maxInputTokens:A,triggerTokens:D,targetTokens:_,overheadTokens:F,thresholdRatio:Y2,utilizationRatio:A>0?G/A:0},messages:{inputTokens:K,triggerTokens:U,targetTokens:R}}},O=Y==="manual"?"manual_compaction":"auto_compaction";B.emitStatusNotice?.(Y==="manual"?"compacting":"auto-compacting",{kind:O,reason:O,phase:"started",iteration:B.iteration,triggerTokens:D,targetTokens:_,maxInputTokens:A,messageTargetTokens:R});let L=B.messages.length,C=Date.now(),N=Z?.compact?await Z.compact(T):await X({context:T,providerConfig:{...Q,abortSignal:B.abortSignal},compaction:Z,estimateMessageTokens:J,logger:$.logger}),p=Date.now()-C,k=$.sessionId??B.conversationId,P={agentId:B.agentId,conversationId:B.conversationId,parentAgentId:B.parentAgentId??void 0};if(N?.messages){let r=N.messages.reduce((g1,Z2)=>g1+J(Z2),0),c=F+r;if($.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:A,messageInputTokens:K,apiInputTokens:H,requestInputTokens:G,requestOverheadTokens:F,afterMessageTokens:r,afterRequestTokens:c,tokensSaved:G-c,utilizationBefore:`${(G/A*100).toFixed(1)}%`,utilizationAfter:`${(c/A*100).toFixed(1)}%`,thresholdTrigger:`${(Y2*100).toFixed(1)}%`,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length}),B.emitStatusNotice?.(Y==="manual"?"compacted":"auto-compacted",{kind:O,reason:O,phase:"completed",iteration:B.iteration,tokensBefore:G,tokensAfter:c,messagesBefore:L,messagesAfter:N.messages.length,maxInputTokens:A}),Y9($.telemetry,{ulid:k,strategy:V,mode:Y,messagesBefore:L,messagesAfter:N.messages.length,messagesRemoved:L-N.messages.length,tokensBefore:G,tokensAfter:c,tokensSaved:G-c,triggerTokens:D,maxInputTokens:A,thresholdRatio:Y2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P}),N.budget&&(N.budget.actionCount>0||N.budget.warningCount>0))VV($.telemetry,{ulid:k,strategy:V,mode:Y,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount,liveTailHandling:N.budget.liveTailHandling,provider:$.providerId,modelId:$.modelId,...P}),B.emitStatusNotice?.("compaction-budget-adjusted",{kind:"compaction_budget_emergency",reason:"compaction_budget_emergency",iteration:B.iteration,policyIntent:N.budget.policyIntent,actionCount:N.budget.actionCount,warningCount:N.budget.warningCount})}else B.emitStatusNotice?.(Y==="manual"?"compaction-skipped":"auto-compaction-skipped",{kind:O,reason:O,phase:"skipped",iteration:B.iteration,maxInputTokens:A}),V9($.telemetry,{ulid:k,strategy:V,mode:Y,reason:"no_result",tokensBefore:G,triggerTokens:D,maxInputTokens:A,thresholdRatio:Y2,durationMs:p,provider:$.providerId,modelId:$.modelId,...P});return N}}function q4($){return async(W)=>{let Z=$.getState?.(),Q=Z?X2(Z,W.messages):void 0;if(Z&&Q){let j=$.compact?await $.compact({...W,messages:Q,apiMessages:Q}):void 0;if(j?.messages){let X=j.systemPrompt??Z.system_prompt,Y=R8({sourceMessages:W.messages,compactedMessages:j.messages,conversationId:W.conversationId,systemPrompt:X});return await $.saveState?.(Y),{...j,...X!==void 0?{systemPrompt:X}:{}}}return{messages:Q,...j?.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:Z.system_prompt!==void 0?{systemPrompt:Z.system_prompt}:{}}}let J=$.compact?await $.compact(W):void 0;if(J?.messages){let j=R8({sourceMessages:W.messages,compactedMessages:J.messages,conversationId:W.conversationId,systemPrompt:J.systemPrompt});await $.saveState?.(j)}return J}}var VG={};w(VG,{zodToJsonSchema:()=>uq,validateWithZod:()=>cq,truncateCommandOutput:()=>G2,resolveToolRoutingConfig:()=>I8,resolveToolPresetName:()=>n1,resolveCoreSelectedToolIds:()=>s9,getCoreHeadlessToolNames:()=>p4,getCoreDefaultEnabledToolIds:()=>o9,getCoreBuiltinToolCatalog:()=>R2,getCoreAcpToolNames:()=>t9,createWebFetchTool:()=>V3,createWebFetchExecutor:()=>I4,createToolPoliciesWithPreset:()=>k9,createSubmitAndExitTool:()=>K3,createSkillsTool:()=>F2,createShellTool:()=>y4,createShellExecutor:()=>K2,createSearchTool:()=>Y3,createSearchExecutor:()=>k4,createReadFilesTool:()=>X3,createFileReadExecutor:()=>h4,createEditorTool:()=>H3,createEditorExecutor:()=>D2,createDefaultToolsWithPreset:()=>I9,createDefaultTools:()=>M$,createDefaultShellExecutor:()=>x4,createDefaultExecutors:()=>h8,createBuiltinTools:()=>N2,createAskQuestionTool:()=>G3,createApplyPatchTool:()=>B3,createApplyPatchExecutor:()=>U2,computePatchChanges:()=>S8,WebFetchRequestSchema:()=>Q3,ToolPresets:()=>t0,TEAM_TOOL_NAMES:()=>m8,SubmitInputSchema:()=>b4,StructuredCommandInputSchema:()=>B2,SkillsInputSchema:()=>P4,SearchCodebaseInputSchema:()=>R4,RunCommandsInputSchema:()=>N4,ReadFilesInputSchema:()=>M4,ReadFileRequestSchema:()=>w9,PatchActionType:()=>A2,MAX_COMMAND_OUTPUT_CHARS:()=>l1,FetchWebContentInputSchema:()=>E4,EditFileInputSchema:()=>w4,DefaultToolNames:()=>T0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>k8,CommandExitError:()=>p1,AskQuestionInputSchema:()=>S4,ApplyPatchInputSchema:()=>C4,ALL_DEFAULT_TOOL_NAMES:()=>O$});import{validateWithZod as cq,zodToJsonSchema as uq}from"@cline/shared";var T0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},O$=[T0.READ_FILES,T0.SEARCH_CODEBASE,T0.RUN_COMMANDS,T0.FETCH_WEB_CONTENT,T0.APPLY_PATCH,T0.EDITOR,T0.SKILLS,T0.ASK,T0.SUBMIT_AND_EXIT];U0();import{createTool as z$,getDefaultShell as kO,getShellKind as IO,validateWithZod as q$,zodToJsonSchema as r1}from"@cline/shared";var R9="__clineInternalTelemetry";function qB($){let W=$?.__clineInternalTelemetry;return W&&typeof W==="object"&&"capture"in W&&typeof W.capture==="function"?W:void 0}import{spawn as IB}from"node:child_process";import{StringDecoder as SO}from"node:string_decoder";import{getDefaultShell as bO,getShellArgs as yO}from"@cline/shared";import{validateWithZod as EO}from"@cline/shared";import{z}from"zod";var T$=6000,V2=z.string().describe("The absolute path of a text file to read content from"),N9=z.object({start_line:z.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:z.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),w9=z.object({path:V2,start_line:N9.shape.start_line,end_line:N9.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds. Always include path; start_line/end_line must be on the same object as the path they apply to, never in a separate array element"),M4=z.object({files:z.array(w9).describe("Array of file read requests; each element is one file and must include path. Omit start_line/end_line or set them to null to read from the start; provide integers on the same object as the path to return only that inclusive one-based line range — never emit a range as its own array element. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),MB={start_line:N9.shape.start_line,end_line:N9.shape.end_line},E8=z.union([w9,z.object({file_path:V2,...MB}).transform(({file_path:$,...W})=>({path:$,...W})),z.object({filePath:V2,...MB}).transform(({filePath:$,...W})=>({path:$,...W}))]),RB=z.union([M4,E8,z.array(E8),z.array(z.string()),z.string(),z.object({files:z.array(z.union([V2,E8]))}),z.object({files:E8}),z.object({files:V2}),z.object({file_paths:z.array(V2)}),z.object({file_paths:z.string()}),z.object({paths:z.array(z.union([V2,E8]))}),z.object({paths:E8}),z.object({paths:z.string()})]),R4=z.object({queries:z.array(z.string()).describe("Array of regex search queries to execute")}),NB=z.union([R4,z.array(z.string()),z.string(),z.object({queries:z.string()})]),E9=z.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${T$*2} characters) to avoid timeouts.`),B2=z.object({command:z.string().min(1).describe("The executable to run directly without shell parsing."),args:z.array(z.string()).optional().describe("Optional argv list passed directly to the executable.")}),EB=z.union([E9,B2]),N4=z.object({commands:z.array(E9).describe("Array of complete shell command strings to execute.")}),NO=z.object({commands:z.array(EB)}),wB=z.union([N4,NO,z.object({commands:EB}),z.array(B2),B2,z.object({command:E9}),z.object({cmd:E9}),z.array(z.string()),z.string()]),Q3=z.object({url:z.string().describe("The URL to fetch"),prompt:z.string().min(2).describe("Analysis prompt for the fetched content")}),E4=z.object({requests:z.array(Q3).describe("Array of the URLs for the web fetch requests")}),w4=z.object({path:z.string().min(1).describe("The absolute path for the action to be performed on"),old_text:z.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${T$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:z.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${T$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:z.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),C4=z.object({input:z.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),CB=z.union([C4,z.string()]),P4=z.object({skill:z.string().min(1).describe("Name of the skill to execute."),args:z.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),S4=z.object({question:z.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:z.array(z.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),b4=z.object({summary:z.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:z.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
91
91
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
92
- IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function H2($){if($ instanceof Error)return $.message;return String($)}function PB($){if(typeof $.old_text==="string"&&$.old_text.length>O$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${O$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>O$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${O$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class E8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function u1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new E8(Z,W)),W)})])}function C9($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function SB($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var EO=new Set(["start_line","end_line"]);function wO($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>EO.has(Z))}function CB($){let W=[];for(let Z of $){if(wO(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function bB($){if(Array.isArray($))return CB($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:CB(Z)}}return $}function yB($){let W=NO(EB,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function CO($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var J3=200;function hB($){let W=CO($);if(W.length<=J3)return W;let Z=W.length-J3;return`${W.slice(0,J3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var d1=48000;function G2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
92
+ IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function H2($){if($ instanceof Error)return $.message;return String($)}function SB($){if(typeof $.old_text==="string"&&$.old_text.length>T$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${T$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>T$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${T$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class w8 extends Error{timeoutMs;constructor($,W){super($);this.name="TimeoutError",this.timeoutMs=W}}function d1($,W,Z){return Promise.race([$,new Promise((Q,J)=>{setTimeout(()=>J(new w8(Z,W)),W)})])}function C9($){let{path:W,start_line:Z,end_line:Q}=$;if(Z==null&&Q==null)return W;return`${W}:${Z??1}-${Q??"EOF"}`}function bB($){let{start_line:W,end_line:Z}=$;if(W==null||Z==null||W<=Z)return null;return`start_line must be less than or equal to end_line (received start_line: ${W}, end_line: ${Z})`}var wO=new Set(["start_line","end_line"]);function CO($){if($===null||typeof $!=="object"||Array.isArray($))return!1;let W=Object.keys($);return W.length>0&&W.every((Z)=>wO.has(Z))}function PB($){let W=[];for(let Z of $){if(CO(Z)){let Q=W[W.length-1];if(typeof Q==="string"){W[W.length-1]={path:Q,...Z};continue}if(Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&"path"in Q&&Object.keys(Z).every((J)=>!(J in Q))){W[W.length-1]={...Q,...Z};continue}}W.push(Z)}return W}function yB($){if(Array.isArray($))return PB($);if($!==null&&typeof $==="object")for(let W of["files","paths"]){let Z=$[W];if(Array.isArray(Z))return{...$,[W]:PB(Z)}}return $}function hB($){let W=EO(wB,$);if(typeof W==="string")return[W];if(Array.isArray(W))return W;if("commands"in W)return Array.isArray(W.commands)?W.commands:[W.commands];if("command"in W)return"args"in W?[W]:[W.command];if("cmd"in W)return[W.cmd];return[W]}function PO($){if(typeof $==="string")return $;let W=$.args??[];if(W.length===0)return $.command;let Z=W.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${Z.join(" ")}`}var J3=200;function kB($){let W=PO($);if(W.length<=J3)return W;let Z=W.length-J3;return`${W.slice(0,J3)} ... [command truncated: ${Z} more chars; full command is in the tool call input]`}var l1=48000;function G2($,W={}){let Z=W.maxChars??48000,Q=W.totalChars??$.length;if($.length<=Z&&Q<=Z)return $;let J=Math.ceil(Z/2),j=Math.max(1,Z-J);return`${$.slice(0,J)}
93
93
  [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
94
- `+$.slice(-j)}var w8=2000,j3=2000,P9=48000,C8=48000;class l1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function IB($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new PO("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function yO($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=kB($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=IB(Q),G=IB(Q),K=!1,F=!1,A=(T)=>{if(F)return;F=!0,T()},D=()=>{if(!B)return;if(Y){kB("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(T)=>{K=!0,D(),A(()=>X(T))},f=setTimeout(()=>U(new E8(`Command timed out after ${Z}ms`,Z)),Z),_=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",_);let R=()=>{clearTimeout(f),W.signal?.removeEventListener("abort",_)};V.stdout?.on("data",(T)=>{H.append(T)}),V.stderr?.on("data",(T)=>{G.append(T)}),V.on("close",(T)=>{if(R(),K)return;let O=H.snapshot(),L=G.snapshot();if(T!==0){let C=T??1,N=J?O.text+(L.text?`
94
+ `+$.slice(-j)}var C8=2000,j3=2000,P9=48000,P8=48000;class p1 extends Error{exitCode;output;constructor($,W){super(`Command exited with code ${$}`);this.exitCode=$;this.output=W;this.name="CommandExitError"}}function xB($){let W=Math.ceil($/2),Z=Math.max(1,$-W),Q=new SO("utf8"),J="",j="",X=0,Y=(V)=>{if(!V)return;X+=V.length;let B=W-J.length;if(B>0){J+=V.slice(0,B),j=(j+V.slice(B)).slice(-Z);return}j=(j+V).slice(-Z)};return{append(V){Y(Q.write(V))},snapshot(){return Y(Q.end()),{text:J+j,totalChars:X,dropped:X>J.length+j.length}}}}function hO($,W,Z,Q,J){return new Promise((j,X)=>{let Y=process.platform==="win32",V=IB($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!Y,windowsHide:!0}),B=V.pid,H=xB(Q),G=xB(Q),K=!1,F=!1,A=(T)=>{if(F)return;F=!0,T()},D=()=>{if(!B)return;if(Y){IB("taskkill",["/pid",String(B),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-B,"SIGKILL")}catch{V.kill("SIGKILL")}},U=(T)=>{K=!0,D(),A(()=>X(T))},f=setTimeout(()=>U(new w8(`Command timed out after ${Z}ms`,Z)),Z),_=()=>U(Error("Command was aborted"));if(W.signal)W.signal.addEventListener("abort",_);let R=()=>{clearTimeout(f),W.signal?.removeEventListener("abort",_)};V.stdout?.on("data",(T)=>{H.append(T)}),V.stderr?.on("data",(T)=>{G.append(T)}),V.on("close",(T)=>{if(R(),K)return;let O=H.snapshot(),L=G.snapshot();if(T!==0){let C=T??1,N=J?O.text+(L.text?`
95
95
  [stderr]
96
- ${L.text}`:""):O.text,p=O.dropped||J&&L.dropped,x=J?O.totalChars+L.totalChars:O.totalChars;if(p||N.length>Q)N=G2(N,{maxChars:Q,totalChars:x});let P=N.length>0?`[Command exited with code ${C}]
97
- ${N}`:`[Command exited with code ${C}]`;A(()=>X(new l1(C,P)))}else{let C=J?O.text+(L.text?`
96
+ ${L.text}`:""):O.text,p=O.dropped||J&&L.dropped,k=J?O.totalChars+L.totalChars:O.totalChars;if(p||N.length>Q)N=G2(N,{maxChars:Q,totalChars:k});let P=N.length>0?`[Command exited with code ${C}]
97
+ ${N}`:`[Command exited with code ${C}]`;A(()=>X(new p1(C,P)))}else{let C=J?O.text+(L.text?`
98
98
  [stderr]
99
- ${L.text}`:""):O.text;if(O.dropped||J&&L.dropped||C.length>Q){let p=J?O.totalChars+L.totalChars:O.totalChars;C=G2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(T)=>{R(),A(()=>X(Error(`Failed to execute command: ${T.message}`)))})})}function K2($={}){let{shell:W=SO(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??d1;return(X,Y,V)=>{let B=typeof X!=="string";return yO({executable:B?X.command:W,args:B?X.args??[]:bO(W,X),cwd:Y,env:Q},V,Z,j,J)}}function xB($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function hO($,W){XV(zB($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:xB($,"mode"),source:xB($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function kO($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function IO($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=kO(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
100
- `))}return W}function xO($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...IO(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function gO($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=hB(Y);try{let H=await u1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof E8)hO(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof l1)return{query:B,result:H.output,error:H.message,success:!1};let G=H2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function X3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return T$({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided on the same file entry as its path. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${w8} lines / ~${Math.round(P9/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:p1(q4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=z$(MB,bB(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=SB(Y);if(V)return{query:C9(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await u1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:C9(Y),result:B,success:!0}}catch(B){let H=H2(B);return{query:C9(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function Y3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return T$({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(C8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:p1(M4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=z$(RB,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await u1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=H2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var gB="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function b4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32";return T$({name:"run_commands",description:j?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+gB+`Output beyond ~${Math.round(d1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through PowerShell; quote paths and arguments for PowerShell and use ';' to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`:"Run non-interactive shell commands from the root of the workspace. "+gB+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(d1/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:p1(R4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let V=xO(yB(X));return gO(V,{executor:$,cwd:J,context:Y,timeoutMs:Z,timeoutSource:Q})}})}function V3($,W={}){let Z=W.webFetchTimeoutMs??30000;return T$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:p1(N4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=z$(N4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await u1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=H2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var mO=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
99
+ ${L.text}`:""):O.text;if(O.dropped||J&&L.dropped||C.length>Q){let p=J?O.totalChars+L.totalChars:O.totalChars;C=G2(C,{maxChars:Q,totalChars:p})}A(()=>j(C))}}),V.on("error",(T)=>{R(),A(()=>X(Error(`Failed to execute command: ${T.message}`)))})})}function K2($={}){let{shell:W=bO(process.platform),timeoutMs:Z=30000,env:Q={},combineOutput:J=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??l1;return(X,Y,V)=>{let B=typeof X!=="string";return hO({executable:B?X.command:W,args:B?X.args??[]:yO(W,X),cwd:Y,env:Q},V,Z,j,J)}}function gB($,W){let Z=$.metadata?.[W];return typeof Z==="string"?Z:void 0}function xO($,W){YV(qB($.metadata),{tool_name:"run_commands",effective_timeout_ms:W.effectiveTimeoutMs,timeout_source:W.timeoutSource,command_count:W.commandCount,duration_ms:W.durationMs,ulid:$.sessionId,mode:gB($,"mode"),source:gB($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function gO($){let W=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return W?.[1]??W?.[2]??W?.[3]}function mO($){let W=[];for(let Z=0;Z<$.length;Z+=1){let Q=$[Z],J=gO(Q);if(!J){W.push(Q);continue}let j=$.findIndex((Y,V)=>V>Z&&Y.trim()===J);if(j===-1){W.push(Q);continue}let X=[Q];while(Z<j){Z+=1;let Y=$[Z];X.push(Y)}W.push(X.join(`
100
+ `))}return W}function vO($){let W=[],Z=[],Q=()=>{if(Z.length>0)W.push(...mO(Z)),Z=[]};for(let J of $){if(typeof J==="string"){Z.push(J);continue}Q(),W.push(J)}return Q(),W}async function cO($,W){let{executor:Z,cwd:Q,context:J,timeoutMs:j,timeoutSource:X}=W;return Promise.all($.map(async(Y)=>{let V=Date.now(),B=kB(Y);try{let H=await d1(Z(Y,Q,J),j,`Command timed out after ${j}ms`);return{query:B,result:H,success:!0}}catch(H){if(H instanceof w8)xO(J,{effectiveTimeoutMs:H.timeoutMs,timeoutSource:X,commandCount:$.length,durationMs:Date.now()-V});if(H instanceof p1)return{query:B,result:H.output,error:H.message,success:!1};let G=H2(H);return{query:B,result:"",error:`Command failed: ${G}`,success:!1}}}))}function X3($,W={}){let Z=W.fileReadTimeoutMs??1e4;return z$({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided on the same file entry as its path. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${C8} lines / ~${Math.round(P9/1024)}k characters; longer files report their total line count, page through them with start_line/end_line on that file's entry. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:r1(M4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(Q,J)=>{let j=q$(RB,yB(Q)),X;if(typeof j==="string")X=[{path:j}];else if(Array.isArray(j))X=j.map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("files"in j)X=(Array.isArray(j.files)?j.files:[j.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in j)X=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((V)=>({path:V}));else if("paths"in j)X=(Array.isArray(j.paths)?j.paths:[j.paths]).map((V)=>typeof V==="string"?{path:V}:V);else X=[j];return Promise.all(X.map(async(Y)=>{let V=bB(Y);if(V)return{query:C9(Y),result:"",error:`Invalid file range: ${V}`,success:!1};try{let B=await d1($(Y,J),Z,`File read timed out after ${Z}ms`);return{query:C9(Y),result:B,success:!0}}catch(B){let H=H2(B);return{query:C9(Y),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function Y3($,W={}){let Z=W.searchTimeoutMs??30000,Q=W.cwd??process.cwd();return z$({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(P8/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:r1(R4),timeoutMs:Z*2,retryable:!0,maxRetries:1,execute:async(J,j)=>{let X=q$(NB,J),Y=Array.isArray(X)?X:typeof X==="object"?Array.isArray(X.queries)?X.queries:[X.queries]:[X];return Promise.all(Y.map(async(V)=>{try{let B=await d1($(V,Q,j),Z,`Search timed out after ${Z}ms`);return{query:V,result:B,success:!0}}catch(B){let H=H2(B);return{query:V,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}var mB="Use for listing files, checking git status, running builds, executing tests, etc. Commands must be non-interactive. Commands that require follow-up input like pagers should be skipped or used with supported flags/env (e.g. git --no-pager, --non-interactive) to bypass the interaction steps. ";function uO($,W){if($==="powershell"||$==="cmd"){let Q=$==="powershell"?"PowerShell":"cmd.exe",J=$==="powershell"?"';'":"'&&'";return"Run non-interactive shell commands from the root of the workspace in Windows environment. "+mB+`Output beyond ~${Math.round(l1/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Commands run through ${Q}; quote paths and arguments for ${Q} and use ${J} to sequence commands. Include multiple commands in the same call when they are independent and safe to run concurrently. When independent reads, searches, or edits are also needed, call those tools in the same response.`}let Z=$==="wsl"?"Commands run through bash in WSL (wsl.exe); the Windows working directory is mounted under /mnt/<drive>. ":W?"Commands run through a POSIX (bash-compatible) shell on Windows. ":"";return"Run non-interactive shell commands from the root of the workspace. "+mB+Z+`Commands should be properly shell-escaped and targeted to avoid error or timeout. Include multiple commands in the same call when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. When independent reads, searches, or edits are also needed, call those tools in the same response. Output beyond ~${Math.round(l1/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`}function y4($,W={}){let Z=W.bashTimeoutMs??30000,Q=W.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=W.cwd??process.cwd(),j=process.platform==="win32",X=W.shell,Y=typeof X==="function"?X:()=>X??kO(process.platform),V=()=>uO(IO(Y()),j),B=z$({name:"run_commands",description:V(),inputSchema:r1(N4),timeoutMs:Z*2,retryable:!1,maxRetries:0,execute:async(H,G)=>{let K=vO(hB(H));return cO(K,{executor:$,cwd:J,context:G,timeoutMs:Z,timeoutSource:Q})}});if(typeof X==="function")Object.defineProperty(B,"description",{get:V,enumerable:!0});return B}function V3($,W={}){let Z=W.webFetchTimeoutMs??30000;return z$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:r1(E4),timeoutMs:Z*2,retryable:!0,maxRetries:2,execute:async(Q,J)=>{let j=q$(E4,Q);return Promise.all(j.requests.map(async(X)=>{try{let Y=await d1($(X.url,X.prompt,J),Z,`Web fetch timed out after ${Z}ms`);return{query:X.url,result:Y,success:!0}}catch(Y){let V=H2(Y);return{query:X.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var dO=`Use \`apply_patch\` to edit files with the canonical freeform patch grammar. Pass the patch text directly as the \`input\` string. Prefer the exact format below:
101
101
 
102
102
  *** Begin Patch
103
103
  *** Update File: path/to/file.ts
@@ -133,109 +133,109 @@ Example:
133
133
  </div>
134
134
  );
135
135
  }
136
- *** End Patch`;function B3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return T$({name:"apply_patch",description:mO,inputSchema:p1(w4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=z$(wB,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await u1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${H2(V)}`,success:!1}}}})}function H3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return T$({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:p1(E4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=z$(E4,J),Y=X.insert_line==null?"edit":"insert",V=PB(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await u1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=H2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function F2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=T$({name:"skills",description:Q,inputSchema:p1(C4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=z$(C4,j);return u1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function G3($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:p1(P4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=z$(P4,W);return $(Q.question,Q.options,Z)}}}function K3($,W={}){let Z=W.submitTimeoutMs??15000;return T$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:p1(S4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=z$(S4,Q);return u1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function q$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(X3(W.readFile,G));if(Q&&W.search)K.push(Y3(W.search,G));if(J&&W.bash)K.push(b4(W.bash,G));if(j&&W.webFetch)K.push(V3(W.webFetch,G));if(Y&&W.editor)K.push(H3(W.editor,G));else if(X&&W.applyPatch)K.push(B3(W.applyPatch,G));if(V&&W.skills)K.push(F2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(G3(W.askQuestion));if(F)K.push(K3(F,G));return K}import*as i0 from"node:fs/promises";import*as n0 from"node:path";var a={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},vB=["%%bash","apply_patch","EOF","```"],A2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(A2||={});class G0 extends Error{constructor($){super($);this.name="DiffError"}}function r0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class F3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(a.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(a.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(a.UPDATE)){this.parseUpdate($.substring(a.UPDATE.length).trim());return}if($?.startsWith(a.DELETE)){this.parseDelete($.substring(a.DELETE.length).trim());return}if($?.startsWith(a.ADD)){this.parseAdd($.substring(a.ADD.length).trim());return}throw new G0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new G0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(a.MOVE)?(this.lines[this.index++]??"").substring(a.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new G0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
137
- `),J=0,j=[a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(!j.some((X)=>this.lines[this.index]?.startsWith(X.trim()))){let X=this.lines[this.index],Y=X?.startsWith("@@ ")?X.substring(3):void 0;if(Y!==void 0||(X==="@@"?X:void 0)!==void 0)this.index++;else if(J!==0)throw new G0(`Invalid Line:
138
- ${this.lines[this.index]}`);if(Y?.trim()){let U=r0(Y.trim());for(let f=J;f<Q.length;f++){let _=Q[f];if(_&&(r0(_)===U||r0(_.trim())===U)){if(J=f+1,r0(_.trim())===U&&r0(_)!==U)this.fuzz++;break}}}let[B,H,G,K]=uO(this.lines,this.index),[F,A,D]=cO(Q,B,J,K);if(F===-1){let U=B.join(`
139
- `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new G0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new G0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[a.END,a.UPDATE,a.DELETE,a.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new G0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
140
- `),chunks:[]}}}function mB($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=vO(Q,Z);return(Z.length-J)/Z.length}function vO($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function cO($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=r0(W.join(`
141
- `));for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
142
- `));if(H===Y)return[B,0,1];let G=mB(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
143
- `)),G=r0(W.map((K)=>K.trimEnd()).join(`
144
- `));if(H===G)return[B,1,1]}for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).map((K)=>K.trim()).join(`
145
- `)),G=r0(W.map((K)=>K.trim()).join(`
146
- `));if(H===G)return[B,100,1]}let V=0.66;for(let B=X;B<$.length;B++){let H=r0($.slice(B,B+W.length).join(`
147
- `)),G=mB(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function uO($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new G0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===a.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function A3($,W,Z){let Q=n0.isAbsolute(W),J=Q?n0.normalize(W):n0.resolve($,W);if(!Z||Q)return J;let j=n0.relative($,J);if(j.startsWith("..")||n0.isAbsolute(j))throw new G0(`Path must stay within cwd: ${W}`);return J}function dO($){return $.split(`
148
- `).map((W)=>W.replace(/\r$/,""))}function cB($){if($.trim()==="")return!1;return vB.some((W)=>$.startsWith(W))}function lO($){let W=0,Z=$.length;while(W<Z&&cB($[W]??""))W++;while(Z>W&&cB($[Z-1]??""))Z--;return $.slice(W,Z)}function pO($){let W=dO($),Z=W.findIndex((X)=>X.startsWith(a.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(a.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new G0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=lO(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[a.BEGIN,...J,a.END]}}function rO($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function iO($,W,Z){if(W.length===0)return $;let Q=$.split(`
149
- `),J=[],j=0;for(let X of W){if(X.origIndex>Q.length)throw new G0(`${Z}: chunk.origIndex ${X.origIndex} > lines.length ${Q.length}`);if(j>X.origIndex)throw new G0(`${Z}: currentIndex ${j} > chunk.origIndex ${X.origIndex}`);J.push(...Q.slice(j,X.origIndex)),J.push(...X.insLines),j=X.origIndex+X.delLines.length}return J.push(...Q.slice(j)),J.join(`
150
- `)}async function nO($,W,Z,Q){let J=rO($,[a.UPDATE,a.DELETE]),j={};for(let X of J){let Y=A3(W,X,Q),V;try{V=await i0.readFile(Y,Z)}catch{throw new G0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
151
- `)}return j}function aO($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new G0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:iO(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function oO($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
136
+ *** End Patch`;function B3($,W={}){let Z=W.applyPatchTimeoutMs??30000,Q=W.cwd??process.cwd();return z$({name:"apply_patch",description:dO,inputSchema:r1(C4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=q$(CB,J),Y=typeof X==="string"?X:X.input;try{return{query:"apply_patch",result:await d1($({input:Y},Q,j),Z,`apply_patch timed out after ${Z}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${H2(V)}`,success:!1}}}})}function H3($,W={}){let Z=W.editorTimeoutMs??30000,Q=W.cwd??process.cwd();return z$({name:"editor",description:"An editor for controlled filesystem edits on the text file at the provided path. Provide `insert_line` to insert `new_text` at a specific line number. Otherwise, the tool replaces `old_text` with `new_text`, or creates the file with `new_text` if file does not exist. Use this tool for making small, precise edits to existing files or creating new files over shell commands. If several edits to different files or non-overlapping regions are already known, emit multiple editor tool calls in the same response instead of serializing them across turns.",inputSchema:r1(w4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(J,j)=>{let X=q$(w4,J),Y=X.insert_line==null?"edit":"insert",V=SB(X);if(V)return{query:`${Y}:${X.path}`,result:"",error:V,success:!1};try{let B=await d1($(X,Q,j),Z,`Editor operation timed out after ${Z}ms`);return{query:`${Y}:${X.path}`,result:B,success:!0}}catch(B){let H=H2(B);return{query:`${Y}:${X.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function F2($,W={}){let Z=W.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',J=z$({name:"skills",description:Q,inputSchema:r1(P4),timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(j,X)=>{let Y=q$(P4,j);return d1($(Y.skill,Y.args||void 0,X),Z,`Skills operation timed out after ${Z}ms`)}});return Object.defineProperty(J,"description",{get(){let j=$.configuredSkills?.filter((X)=>!X.disabled).map((X)=>X.name);if(j&&j.length>0)return`${Q} Available skills: ${j.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),J}function G3($){return{name:"ask_question",description:"Ask user a question for clarifying or gathering information needed to complete the task. For example, ask the user clarifying questions about a key implementation decision. You should only ask one question. Provide an array of 2-5 options for the user to choose from. Never include an option to toggle to Act mode.",inputSchema:r1(S4),retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=q$(S4,W);return $(Q.question,Q.options,Z)}}}function K3($,W={}){let Z=W.submitTimeoutMs??15000;return z$({name:"submit_and_exit",description:"Submit the final answer and exit the conversation. For example, submit a summary of the investigation and confirm the issue is resolved. You should only submit once all necessary steps are completed. Make sure to verify your output matches the expected format, data types, and file locations specified. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:r1(b4),lifecycle:{completesRun:!0},timeoutMs:Z,retryable:!1,maxRetries:0,execute:async(Q,J)=>{let j=q$(b4,Q);return d1($(j.summary,j.verified,J),Z,`submit_and_exit timed out after ${Z}ms`)}})}function M$($){let{executors:W,enableReadFiles:Z=!0,enableSearch:Q=!0,enableBash:J=!0,enableWebFetch:j=!0,enableApplyPatch:X=!1,enableEditor:Y=!0,enableSkills:V=!0,enableAskQuestion:B=!0,enableSubmitAndExit:H=!1,...G}=$,K=[];if(Z&&W.readFile)K.push(X3(W.readFile,G));if(Q&&W.search)K.push(Y3(W.search,G));if(J&&W.bash)K.push(y4(W.bash,G));if(j&&W.webFetch)K.push(V3(W.webFetch,G));if(Y&&W.editor)K.push(H3(W.editor,G));else if(X&&W.applyPatch)K.push(B3(W.applyPatch,G));if(V&&W.skills)K.push(F2(W.skills,G));let F=H?W.submit:void 0;if(B&&W.askQuestion&&!F)K.push(G3(W.askQuestion));if(F)K.push(K3(F,G));return K}import*as o0 from"node:fs/promises";import*as s0 from"node:path";var a={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},cB=["%%bash","apply_patch","EOF","```"],A2;((Q)=>{Q.ADD="add";Q.DELETE="delete";Q.UPDATE="update"})(A2||={});class H0 extends Error{constructor($){super($);this.name="DiffError"}}function a0($){let W={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Z)=>W[Z]??Z).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class F3{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,W){this.lines=$;this.currentFiles=W}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(a.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(a.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(a.UPDATE)){this.parseUpdate($.substring(a.UPDATE.length).trim());return}if($?.startsWith(a.DELETE)){this.parseDelete($.substring(a.DELETE.length).trim());return}if($?.startsWith(a.ADD)){this.parseAdd($.substring(a.ADD.length).trim());return}throw new H0(`Unknown line while parsing: ${$}`)}checkDuplicate($,W){if($ in this.patch.actions)throw new H0(`Duplicate ${W} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let W=this.lines[this.index]?.startsWith(a.MOVE)?(this.lines[this.index++]??"").substring(a.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new H0(`Update File Error: Missing File: ${$}`);let Z=this.currentFiles[$]??"",Q=this.parseUpdateFile(Z,$);Q.movePath=W,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,W){let Z={type:"update",chunks:[]},Q=$.split(`
137
+ `),J=0,j=[a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(!j.some((X)=>this.lines[this.index]?.startsWith(X.trim()))){let X=this.lines[this.index],Y=X?.startsWith("@@ ")?X.substring(3):void 0;if(Y!==void 0||(X==="@@"?X:void 0)!==void 0)this.index++;else if(J!==0)throw new H0(`Invalid Line:
138
+ ${this.lines[this.index]}`);if(Y?.trim()){let U=a0(Y.trim());for(let f=J;f<Q.length;f++){let _=Q[f];if(_&&(a0(_)===U||a0(_.trim())===U)){if(J=f+1,a0(_.trim())===U&&a0(_)!==U)this.fuzz++;break}}}let[B,H,G,K]=rO(this.lines,this.index),[F,A,D]=pO(Q,B,J,K);if(F===-1){let U=B.join(`
139
+ `);this.addWarning({path:this.currentPath||W,chunkIndex:Z.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:U.length>200?`${U.substring(0,200)}...`:U}),this.index=G}else{this.fuzz+=A;for(let U of H)U.origIndex+=F,Z.chunks.push(U);J=F+B.length,this.index=G}}return Z}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new H0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new H0(`Add File Error: File already exists: ${$}`);this.index++;let W=[],Z=[a.END,a.UPDATE,a.DELETE,a.ADD];while(this.hasMoreLines()&&!Z.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new H0(`Invalid Add File line (missing '+'): ${Q}`);W.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:W.join(`
140
+ `),chunks:[]}}}function vB($,W){let Z=$.length>W.length?$:W,Q=$.length>W.length?W:$;if(Z.length===0)return 1;let J=lO(Q,Z);return(Z.length-J)/Z.length}function lO($,W){let Z=W.length+1,Q=$.length+1,J=Array(Z*Q).fill(0),j=(Y,V)=>J[Y*Q+V]??0,X=(Y,V,B)=>{J[Y*Q+V]=B};for(let Y=0;Y<=W.length;Y++)X(Y,0,Y);for(let Y=0;Y<=$.length;Y++)X(0,Y,Y);for(let Y=1;Y<=W.length;Y++)for(let V=1;V<=$.length;V++)if(W[Y-1]===$[V-1])X(Y,V,j(Y-1,V-1));else X(Y,V,1+Math.min(j(Y-1,V-1),j(Y,V-1),j(Y-1,V)));return j(W.length,$.length)}function pO($,W,Z,Q){if(W.length===0)return[Z,0,1];let J=0,j=(X)=>{let Y=a0(W.join(`
141
+ `));for(let B=X;B<$.length;B++){let H=a0($.slice(B,B+W.length).join(`
142
+ `));if(H===Y)return[B,0,1];let G=vB(H,Y);if(G>J)J=G}for(let B=X;B<$.length;B++){let H=a0($.slice(B,B+W.length).map((K)=>K.trimEnd()).join(`
143
+ `)),G=a0(W.map((K)=>K.trimEnd()).join(`
144
+ `));if(H===G)return[B,1,1]}for(let B=X;B<$.length;B++){let H=a0($.slice(B,B+W.length).map((K)=>K.trim()).join(`
145
+ `)),G=a0(W.map((K)=>K.trim()).join(`
146
+ `));if(H===G)return[B,100,1]}let V=0.66;for(let B=X;B<$.length;B++){let H=a0($.slice(B,B+W.length).join(`
147
+ `)),G=vB(H,Y);if(G>=V)return[B,1000,G];if(G>J)J=G}return[-1,0,J]};if(Q){let[X,Y,V]=j($.length-W.length);if(X!==-1)return[X,Y,V];return[X,Y,V]=j(Z),[X,Y+1e4,V]}return j(Z)}function rO($,W){let Z=W,Q=[],J=[],j=[],X=[],Y="keep",V=["@@",a.END,a.UPDATE,a.DELETE,a.ADD,a.END_FILE];while(Z<$.length){let B=$[Z];if(!B||V.some((K)=>B.startsWith(K.trim())))break;if(B==="***")break;if(B.startsWith("***"))throw new H0(`Invalid line: ${B}`);Z++;let H=Y,G=B;if(G[0]==="+")Y="add";else if(G[0]==="-")Y="delete";else if(G[0]===" ")Y="keep";else Y="keep",G=` ${G}`;if(G=G.slice(1),Y==="keep"&&H!==Y){if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});J=[],j=[]}if(Y==="delete")J.push(G),Q.push(G);else if(Y==="add")j.push(G);else Q.push(G)}if(j.length||J.length)X.push({origIndex:Q.length-J.length,delLines:J,insLines:j});if(Z<$.length&&$[Z]===a.END_FILE)return Z++,[Q,X,Z,!0];return[Q,X,Z,!1]}function A3($,W,Z){let Q=s0.isAbsolute(W),J=Q?s0.normalize(W):s0.resolve($,W);if(!Z||Q)return J;let j=s0.relative($,J);if(j.startsWith("..")||s0.isAbsolute(j))throw new H0(`Path must stay within cwd: ${W}`);return J}function iO($){return $.split(`
148
+ `).map((W)=>W.replace(/\r$/,""))}function uB($){if($.trim()==="")return!1;return cB.some((W)=>$.startsWith(W))}function nO($){let W=0,Z=$.length;while(W<Z&&uB($[W]??""))W++;while(Z>W&&uB($[Z-1]??""))Z--;return $.slice(W,Z)}function aO($){let W=iO($),Z=W.findIndex((X)=>X.startsWith(a.BEGIN)),Q=-1;for(let X=W.length-1;X>=0;X--)if(W[X]?.startsWith(a.END)){Q=X;break}if(Z!==-1||Q!==-1){if(Z===-1||Q===-1||Q<Z)throw new H0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:W.slice(Z,Q+1)}}let J=nO(W);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[a.BEGIN,...J,a.END]}}function oO($,W){let Z=new Set;for(let Q of $)for(let J of W)if(Q.startsWith(J)){Z.add(Q.substring(J.length).trim());break}return[...Z]}function sO($,W,Z){if(W.length===0)return $;let Q=$.split(`
149
+ `),J=[],j=0;for(let X of W){if(X.origIndex>Q.length)throw new H0(`${Z}: chunk.origIndex ${X.origIndex} > lines.length ${Q.length}`);if(j>X.origIndex)throw new H0(`${Z}: currentIndex ${j} > chunk.origIndex ${X.origIndex}`);J.push(...Q.slice(j,X.origIndex)),J.push(...X.insLines),j=X.origIndex+X.delLines.length}return J.push(...Q.slice(j)),J.join(`
150
+ `)}async function tO($,W,Z,Q){let J=oO($,[a.UPDATE,a.DELETE]),j={};for(let X of J){let Y=A3(W,X,Q),V;try{V=await o0.readFile(Y,Z)}catch{throw new H0(`File not found: ${X}`)}j[X]=V.replace(/\r\n/g,`
151
+ `)}return j}function eO($,W){let Z={};for(let[Q,J]of Object.entries($.actions))switch(J.type){case"delete":Z[Q]={type:"delete",oldContent:W[Q]};break;case"add":if(J.newFile===void 0)throw new H0("ADD action without file content");Z[Q]={type:"add",newContent:J.newFile};break;case"update":Z[Q]={type:"update",oldContent:W[Q],newContent:sO(W[Q]??"",J.chunks,Q),movePath:J.movePath};break}return Z}function $T($){let W=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Z of $){let Q=Z.chunkIndex===void 0?"unknown":String(Z.chunkIndex+1);if(W.push(`${Z.path}: hunk ${Q}: ${Z.message}`),Z.context)W.push(`Context:
152
152
  ${Z.context}`)}return W.join(`
153
- `)}async function sO($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=A3(W,j,Q);switch(X.type){case"delete":await i0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new G0(`Cannot create ${j} with no content`);await i0.mkdir(n0.dirname(Y),{recursive:!0}),await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new G0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=A3(W,X.movePath,Q);await i0.mkdir(n0.dirname(V),{recursive:!0}),await i0.writeFile(V,X.newContent,{encoding:Z}),await i0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await i0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function P8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=pO($),X=await nO(j.lines,W,Q,J),Y=new F3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new G0(oO(V.warnings));return{changes:aO(V,X),fuzz:B}}function U2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await P8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await sO(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
154
- `)}}import*as A1 from"node:fs/promises";import*as F1 from"node:path";function tO($,W,Z){let Q=F1.isAbsolute(W),J=Q?F1.normalize(W):F1.resolve($,W);if(!Z)return J;if(Q)return J;let j=F1.relative($,J);if(j.startsWith("..")||F1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function eO($,W){if(W.length===0)return 0;return $.split(W).length-1}function $T($,W,Z){let Q=$.split(`
153
+ `)}async function WT($,W,Z,Q){let J=[];for(let[j,X]of Object.entries($)){let Y=A3(W,j,Q);switch(X.type){case"delete":await o0.rm(Y,{force:!0}),J.push(`${j}: [deleted]`);break;case"add":if(X.newContent===void 0)throw new H0(`Cannot create ${j} with no content`);await o0.mkdir(s0.dirname(Y),{recursive:!0}),await o0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break;case"update":{if(X.newContent===void 0)throw new H0(`UPDATE change for ${j} has no new content`);if(X.movePath){let V=A3(W,X.movePath,Q);await o0.mkdir(s0.dirname(V),{recursive:!0}),await o0.writeFile(V,X.newContent,{encoding:Z}),await o0.rm(Y,{force:!0}),J.push(`${j} -> ${X.movePath}`)}else await o0.writeFile(Y,X.newContent,{encoding:Z}),J.push(j);break}}}return J}async function S8($,W,Z={}){let{encoding:Q="utf-8",restrictToCwd:J=!0}=Z,j=aO($),X=await tO(j.lines,W,Q,J),Y=new F3(j.lines,X),{patch:V,fuzz:B}=Y.parse();if(V.warnings&&V.warnings.length>0)throw new H0($T(V.warnings));return{changes:eO(V,X),fuzz:B}}function U2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0}=$;return async(Q,J,j)=>{let{changes:X,fuzz:Y}=await S8(Q.input,J,{encoding:W,restrictToCwd:Z}),V=await WT(X,J,W,Z),B=["Successfully applied patch to the following files:"];for(let H of V)B.push(H);if(Y>0)B.push(`Note: Patch applied with fuzz factor ${Y}`);return B.join(`
154
+ `)}}import*as D1 from"node:fs/promises";import*as U1 from"node:path";function ZT($,W,Z){let Q=U1.isAbsolute(W),J=Q?U1.normalize(W):U1.resolve($,W);if(!Z)return J;if(Q)return J;let j=U1.relative($,J);if(j.startsWith("..")||U1.isAbsolute(j))throw Error(`Path must stay within cwd: ${W}`);return J}function QT($,W){if(W.length===0)return 0;return $.split(W).length-1}function JT($,W,Z){let Q=$.split(`
155
155
  `),J=W.split(`
156
156
  `),j=0;while(j<Q.length&&j<J.length&&Q[j]===J[j])j++;let X=Q.length,Y=J.length;while(X>j&&Y>j&&Q[X-1]===J[Y-1])X--,Y--;let V=X-j,B=Y-j,H=V,G=B;if(V+B>Z)H=Math.min(V,Math.max(Math.ceil(Z/2),Z-B)),G=Math.min(B,Z-H);let K=["```diff"];for(let D=j;D<j+H;D++)K.push(`-${D+1}: ${Q[D]}`);for(let D=j;D<j+G;D++)K.push(`+${D+1}: ${J[D]}`);let F=V-H,A=B-G;if(F>0||A>0)K.push(`... diff truncated (${F} more removed, ${A} more added lines) ...`);return K.push("```"),K.join(`
157
- `)}async function WT($,W,Z){return await A1.mkdir(F1.dirname($),{recursive:!0}),await A1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function ZT($){try{return await A1.access($),!0}catch{return!1}}async function QT($,W,Z,Q,J){let j=await A1.readFile($,Q),X=eO(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await A1.writeFile($,Y,{encoding:Q});let V=$T(j,Y,J);return`Edited ${$}
158
- ${V}`}async function JT($,W,Z,Q){let j=(await A1.readFile($,Q)).split(`
157
+ `)}async function jT($,W,Z){return await D1.mkdir(U1.dirname($),{recursive:!0}),await D1.writeFile($,W,{encoding:Z}),`File created successfully at: ${$}`}async function XT($){try{return await D1.access($),!0}catch{return!1}}async function YT($,W,Z,Q,J){let j=await D1.readFile($,Q),X=QT(j,W);if(X===0)throw Error(`No replacement performed: text not found in ${$}.`);if(X>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let Y=j.replace(W,Z??"");await D1.writeFile($,Y,{encoding:Q});let V=JT(j,Y,J);return`Edited ${$}
158
+ ${V}`}async function VT($,W,Z,Q){let j=(await D1.readFile($,Q)).split(`
159
159
  `),X=j.length+1;if(W<1||W>X)throw Error(`Invalid insert_line: ${W}. insert_line must be a positive one-based boundary line in the range 1-${X}. Use ${X} to append at EOF.`);let Y=W-1;return j.splice(Y,0,...Z.split(`
160
- `)),await A1.writeFile($,j.join(`
161
- `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function D2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=tO(j,J.path,Z);if(J.insert_line!=null)return JT(Y,J.insert_line,J.new_text,W);if(!await ZT(Y))return WT(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return QT(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as jT}from"node:fs";import*as S9 from"node:fs/promises";import*as M$ from"node:path";import{createInterface as XT}from"node:readline";import{resolveExistingFilePath as YT}from"@cline/shared/storage";var VT=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),BT={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},uB=1e8,HT=50000;function dB($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function GT($,W,Z,Q,J,j){if(j?.aborted)throw dB(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+HT-1,H=[],G=0,K=0,F=!1,A=!1,D=Number.isFinite(Y)?Math.min(Y,X+w8-1):X+w8-1,U=Z?String(D).length+3:0,f=jT($,{encoding:W}),_=XT({input:f,crlfDelay:Number.POSITIVE_INFINITY}),R=j?()=>f.destroy(dB(j)):void 0;if(j&&R)j.addEventListener("abort",R,{once:!0});try{for await(let p of _){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=w8){F=!0;continue}let x=p;if(x.length>j3)x=`${x.slice(0,j3)} [line truncated]`;let P=G+x.length+U+1;if(P>P9&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:x}),G=P}}finally{if(j&&R)j.removeEventListener("abort",R);_.close(),f.destroy()}let T=String(H[H.length-1]?.lineNumber??K).length,O=H.map(({lineNumber:p,text:x})=>Z?`${String(p).padStart(T," ")} | ${x}`:x).join(`
160
+ `)),await D1.writeFile($,j.join(`
161
+ `),{encoding:Q}),`Inserted content at line ${W} in ${$}.`}function D2($={}){let{encoding:W="utf-8",restrictToCwd:Z=!0,maxDiffLines:Q=200}=$;return async(J,j,X)=>{let Y=ZT(j,J.path,Z);if(J.insert_line!=null)return VT(Y,J.insert_line,J.new_text,W);if(!await XT(Y))return jT(Y,J.new_text,W);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return YT(Y,J.old_text,J.new_text,W,Q)}}import{createReadStream as BT}from"node:fs";import*as S9 from"node:fs/promises";import*as R$ from"node:path";import{createInterface as HT}from"node:readline";import{resolveExistingFilePath as GT}from"@cline/shared/storage";var KT=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),FT={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},dB=1e8,AT=50000;function lB($){let{reason:W}=$;if(W instanceof Error)return W;if(W!==void 0)return Error(String(W));return Error("File read was aborted")}async function UT($,W,Z,Q,J,j){if(j?.aborted)throw lB(j);let X=Math.max(Q??1,1),Y=J??Number.POSITIVE_INFINITY,V=Number.isFinite(Y),B=V?Y:X+AT-1,H=[],G=0,K=0,F=!1,A=!1,D=Number.isFinite(Y)?Math.min(Y,X+C8-1):X+C8-1,U=Z?String(D).length+3:0,f=BT($,{encoding:W}),_=HT({input:f,crlfDelay:Number.POSITIVE_INFINITY}),R=j?()=>f.destroy(lB(j)):void 0;if(j&&R)j.addEventListener("abort",R,{once:!0});try{for await(let p of _){if(K+=1,K>Y){K=Y;break}if(!V&&F&&K>=B){A=!0;break}if(K<X||F)continue;if(H.length>=C8){F=!0;continue}let k=p;if(k.length>j3)k=`${k.slice(0,j3)} [line truncated]`;let P=G+k.length+U+1;if(P>P9&&H.length>0){F=!0;continue}H.push({lineNumber:K,text:k}),G=P}}finally{if(j&&R)j.removeEventListener("abort",R);_.close(),f.destroy()}let T=String(H[H.length-1]?.lineNumber??K).length,O=H.map(({lineNumber:p,text:k})=>Z?`${String(p).padStart(T," ")} | ${k}`:k).join(`
162
162
  `),L=H[H.length-1]?.lineNumber;if(L===void 0)return O;let C=Math.min(Y,K);if(L>=C)return O;let N=A?`${K}+ lines`:C;return`${O}
163
163
 
164
- [Showing lines ${X}-${L} of ${N}. Use start_line/end_line to read other sections.]`}function y4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...BT,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=M$.isAbsolute(X)?M$.normalize(X):M$.resolve(process.cwd(),X),H=YT(B)??B,G=M$.extname(H).toLowerCase(),K=VT.get(G),F=await S9.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await S9.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>uB)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${uB} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return GT(H,Z,Q,Y,V,j.signal)}}import{spawn as sB}from"node:child_process";import*as tB from"node:fs/promises";import*as h9 from"node:path";var aB={};w(aB,{prewarmFileIndex:()=>y9,getFileIndex:()=>r1,enrichPromptWithMentions:()=>b8});import{spawn as KT}from"node:child_process";import{readdir as FT}from"node:fs/promises";import D3 from"node:path";import{isMainThread as rB,parentPort as lB,Worker as AT}from"node:worker_threads";var UT=15000,DT=600000,_T=1000,fT=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function pB($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var S8=new Map;function LT(){if(!rB)return!1;return!0}function OT($){if(S8.size<=1)return;for(let[W,Z]of S8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>DT)S8.delete(W)}}function TT($,W){return D3.relative($,W).split(D3.sep).join("/")}async function zT($){let Z=(await new Promise((Q,J)=>{let j=KT("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function iB($,W,Z){let Q;try{Q=await FT(W,{withFileTypes:!0})}catch(J){if(pB(J))return;throw J}for(let J of Q){let j=D3.join(W,J.name);if(J.isDirectory()){if(fT.has(J.name))continue;try{await iB($,j,Z)}catch(X){if(pB(X))continue;throw X}continue}if(J.isFile())Z.add(TT($,j))}}async function qT($){let W=new Set;return await iB($,$,W),W}async function b9($){try{return await zT($)}catch{return qT($)}}function MT(){if(rB||!lB)return;let $=lB;$.on("message",(W)=>{if(W.type!=="index")return;b9(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class nB{worker=new AT(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},_T);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}MT();var U3;function RT(){if(!LT())return null;if(U3===void 0)U3=new nB;return U3}async function NT($){let W=RT();if(!W)return b9($);try{let Z=await W.requestIndex($);if(Z===null)return b9($);return new Set(Z)}catch{return b9($)}}async function r1($,W={}){let Z=W.ttlMs??UT,Q=Date.now();OT(Q);let J=S8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=NT($).then((X)=>{return S8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return S8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function y9($,W={}){await r1($,{...W,ttlMs:0})}import{stat as ET}from"node:fs/promises";import _2 from"node:path";var wT=/[),.:;!?`'"]+$/,CT=/^[(`'"]+/;function PT($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(CT,"").replace(wT,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function ST($,W){let Z=$.replace(/\\/g,"/"),Q=_2.isAbsolute(Z)?_2.resolve(Z):_2.resolve(W,Z),J=_2.relative(W,Q);if(J.startsWith("..")||_2.isAbsolute(J))return;return J.split(_2.sep).join("/")}async function b8($,W,Z={}){let Q=PT($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await r1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=ST(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=_2.join(W,F);try{if(!(await ET(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var bT=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],yT=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],f2=null;function hT(){if(f2!==null)return Promise.resolve(f2);return new Promise(($)=>{let W=sB("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{f2=Z===0,$(f2)}),W.on("error",()=>{f2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(f2===null)f2=!1,$(!1)},1000)})}function kT($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=sB("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],D=V.split(`
165
- `).filter((U)=>U.trim());for(let U of D){if(A.length>=Z)break;let f=JSON.parse(U);if(f.type==="match"){let _=f.data,R=[];if(f.data.submatches&&f.data.submatches.length>0){let T=f.data.submatches[0];A.push({file:_.path.text,line:_.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:R})}}else if(f.type==="context"&&A.length>0){let _=A[A.length-1],R=f.data.line_number===_.line?">":" ";_.context.push(`${R} ${f.data.line_number}: ${f.data.lines?.text??f.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function IT($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=h9.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function h4($={}){let{includeExtensions:W=bT,excludeDirs:Z=yT,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await hT(),K=null;if(G)K=await kT(V,B,Q,J,5000,H.signal);if(K){let _=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let R of K)_.push(`${R.file}:${R.line}:${R.column}`),_.push(...R.context),_.push("");if(K.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return oB(_.join(`
166
- `))}let F;try{F=new RegExp(V,"gim")}catch(_){throw Error(`Invalid regex pattern: ${V}. ${_ instanceof Error?_.message:""}`)}let A=[],D=0,U=await r1(B);for(let _ of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!IT(_,X,Y,j))continue;if(A.length>=Q)break;D++;let R=h9.join(B,_);try{let O=(await tB.readFile(R,"utf-8")).split(`
167
- `);for(let L=0;L<O.length;L++){let C=O[L];F.lastIndex=0;let N=F.exec(C);while(N!==null){if(A.length>=Q)break;let p=Math.max(0,L-J),x=Math.min(O.length-1,L+J),P=[];for(let r=p;r<=x;r++){let d=r===L?">":" ";P.push(`${d} ${r+1}: ${O[r]}`)}if(A.push({file:_,line:L+1,column:N.index+1,match:N[0],context:P}),N.index===F.lastIndex)F.lastIndex++;N=F.exec(C)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
168
- Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${D} files.`,""];for(let _ of A)f.push(`${_.file}:${_.line}:${_.column}`),f.push(..._.context),f.push("");if(A.length>=Q)f.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return oB(f.join(`
169
- `))}}function oB($){if($.length<=C8)return $;let W=Math.ceil(C8/2),Z=Math.max(1,C8-W);return`${$.slice(0,W)}
164
+ [Showing lines ${X}-${L} of ${N}. Use start_line/end_line to read other sections.]`}function h4($={}){let{maxFileSizeBytes:W,encoding:Z,includeLineNumbers:Q}={...FT,...$};return async(J,j)=>{let{path:X,start_line:Y,end_line:V}=J,B=R$.isAbsolute(X)?R$.normalize(X):R$.resolve(process.cwd(),X),H=GT(B)??B,G=R$.extname(H).toLowerCase(),K=KT.get(G),F=await S9.stat(H);if(!F.isFile())throw Error(`Path is not a file: ${H}`);if(K){if(F.size>W)throw Error(`Image file too large: ${F.size} bytes (max: ${W} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await S9.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>dB)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${dB} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return UT(H,Z,Q,Y,V,j.signal)}}import{spawn as tB}from"node:child_process";import*as eB from"node:fs/promises";import*as h9 from"node:path";var oB={};w(oB,{prewarmFileIndex:()=>y9,getFileIndex:()=>i1,enrichPromptWithMentions:()=>y8});import{spawn as DT}from"node:child_process";import{readdir as _T}from"node:fs/promises";import D3 from"node:path";import{isMainThread as iB,parentPort as pB,Worker as fT}from"node:worker_threads";var LT=15000,OT=600000,TT=1000,zT=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function rB($){let W=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return W==="EACCES"||W==="EPERM"||W==="ENOENT"}var b8=new Map;function qT(){if(!iB)return!1;return!0}function MT($){if(b8.size<=1)return;for(let[W,Z]of b8.entries()){if(Z.pending)continue;if($-Z.lastAccessedAt>OT)b8.delete(W)}}function RT($,W){return D3.relative($,W).split(D3.sep).join("/")}async function NT($){let Z=(await new Promise((Q,J)=>{let j=DT("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),X="",Y="";j.stdout.on("data",(V)=>{X+=V.toString()}),j.stderr.on("data",(V)=>{Y+=V.toString()}),j.on("error",J),j.on("close",(V)=>{if(V===0){Q(X);return}J(Error(Y||`rg exited with code ${V}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(Z)}async function nB($,W,Z){let Q;try{Q=await _T(W,{withFileTypes:!0})}catch(J){if(rB(J))return;throw J}for(let J of Q){let j=D3.join(W,J.name);if(J.isDirectory()){if(zT.has(J.name))continue;try{await nB($,j,Z)}catch(X){if(rB(X))continue;throw X}continue}if(J.isFile())Z.add(RT($,j))}}async function ET($){let W=new Set;return await nB($,$,W),W}async function b9($){try{return await NT($)}catch{return ET($)}}function wT(){if(iB||!pB)return;let $=pB;$.on("message",(W)=>{if(W.type!=="index")return;b9(W.cwd).then((Z)=>{let Q={type:"indexResult",requestId:W.requestId,files:Array.from(Z)};$.postMessage(Q)}).catch((Z)=>{let Q={type:"indexResult",requestId:W.requestId,error:Z instanceof Error?Z.message:"Failed to build file index"};$.postMessage(Q)})})}class aB{worker=new fT(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let W=this.pending.get($.requestId);if(!W)return;if(this.pending.delete($.requestId),$.error){W.reject(Error($.error));return}W.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let W=++this.nextRequestId,Z=new Promise((J,j)=>{let X=setTimeout(()=>{this.pending.delete(W),J(null)},TT);X.unref(),this.pending.set(W,{resolve:(Y)=>{clearTimeout(X),J(Y)},reject:(Y)=>{clearTimeout(X),j(Y)}})}),Q={type:"index",requestId:W,cwd:$};return this.worker.postMessage(Q),Z}flushPending($){for(let[W,Z]of this.pending.entries())Z.reject($),this.pending.delete(W)}}wT();var U3;function CT(){if(!qT())return null;if(U3===void 0)U3=new aB;return U3}async function PT($){let W=CT();if(!W)return b9($);try{let Z=await W.requestIndex($);if(Z===null)return b9($);return new Set(Z)}catch{return b9($)}}async function i1($,W={}){let Z=W.ttlMs??LT,Q=Date.now();MT(Q);let J=b8.get($);if(J&&Z>0&&Q-J.lastBuiltAt<=Z&&J.files.size>0)return J.lastAccessedAt=Q,J.files;if(J?.pending)return J.lastAccessedAt=Q,J.pending;let j=PT($).then((X)=>{return b8.set($,{files:X,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),X});return b8.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:Q,pending:j}),j}async function y9($,W={}){await i1($,{...W,ttlMs:0})}import{stat as ST}from"node:fs/promises";import _2 from"node:path";var bT=/[),.:;!?`'"]+$/,yT=/^[(`'"]+/;function hT($){let W=$.matchAll(/(^|[\s])@([^\s]+)/g),Z=[];for(let Q of W){let J=(Q[2]??"").trim();if(J.length===0)continue;let j=J.replace(yT,"").replace(bT,"");if(j.length===0||j.includes("@"))continue;Z.push(j)}return Array.from(new Set(Z))}function kT($,W){let Z=$.replace(/\\/g,"/"),Q=_2.isAbsolute(Z)?_2.resolve(Z):_2.resolve(W,Z),J=_2.relative(W,Q);if(J.startsWith("..")||_2.isAbsolute(J))return;return J.split(_2.sep).join("/")}async function y8($,W,Z={}){let Q=hT($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:j,maxTotalBytes:X}=Z,Y=await i1(W,{ttlMs:Z.ttlMs}),V=[],B=[],H=[],G=0;for(let K of Q){if(J&&H.length>=J){B.push(K);continue}let F=kT(K,W);if(!F||!Y.has(F)){B.push(K);continue}if(!j||!X){V.push(F);continue}let A=_2.join(W,F);try{if(!(await ST(A)).isFile()){B.push(K);continue}let U=G+j;if(U>X){B.push(K);continue}G=U,V.push(F)}catch{B.push(K)}}return{prompt:$,mentions:Q,matchedFiles:V,ignoredMentions:B}}var IT=["ts","tsx","js","jsx","mjs","cjs","json","md","mdx","txt","yaml","yml","toml","py","rb","go","rs","java","kt","swift","c","cpp","h","hpp","css","scss","less","html","vue","svelte","sql","sh","bash","zsh","fish","ps1","env","gitignore","dockerignore","editorconfig"],xT=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],f2=null;function gT(){if(f2!==null)return Promise.resolve(f2);return new Promise(($)=>{let W=tB("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});W.on("close",(Z)=>{f2=Z===0,$(f2)}),W.on("error",()=>{f2=!1,$(!1)}),setTimeout(()=>{if(!W.killed)W.kill("SIGTERM");if(f2===null)f2=!1,$(!1)},1000)})}function mT($,W,Z,Q,J=5000,j){return new Promise((X)=>{let Y=tB("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:W,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",B=!1,H=()=>{if(!Y.killed)Y.kill("SIGTERM")},G=setTimeout(()=>{if(!B)B=!0,H(),X(null)},J),K=(F)=>{if(!B)B=!0,clearTimeout(G),H(),X(F)};if(j?.aborted){H(),X(null);return}j?.addEventListener("abort",()=>{K(null)}),Y.stdout.on("data",(F)=>{V+=F.toString()}),Y.stderr.on("data",()=>{}),Y.on("close",(F)=>{if(F===0||F===1){try{let A=[],D=V.split(`
165
+ `).filter((U)=>U.trim());for(let U of D){if(A.length>=Z)break;let f=JSON.parse(U);if(f.type==="match"){let _=f.data,R=[];if(f.data.submatches&&f.data.submatches.length>0){let T=f.data.submatches[0];A.push({file:_.path.text,line:_.line_number,column:(T?.start??0)+1,match:T?.match?.text??"",context:R})}}else if(f.type==="context"&&A.length>0){let _=A[A.length-1],R=f.data.line_number===_.line?">":" ";_.context.push(`${R} ${f.data.line_number}: ${f.data.lines?.text??f.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),Y.on("error",()=>{K(null)})})}function vT($,W,Z,Q){let J=$.split("/"),j=J[J.length-1]??"";if(J.length-1>Q)return!1;for(let V=0;V<J.length-1;V++)if(W.has(J[V]??""))return!1;let Y=h9.posix.extname(j).slice(1).toLowerCase();return Z.has(Y)||!Y&&!j.startsWith(".")}function k4($={}){let{includeExtensions:W=IT,excludeDirs:Z=xT,maxResults:Q=100,contextLines:J=2,maxDepth:j=20}=$,X=new Set(Z),Y=new Set(W.map((V)=>V.toLowerCase()));return async(V,B,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let G=await gT(),K=null;if(G)K=await mT(V,B,Q,J,5000,H.signal);if(K){let _=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let R of K)_.push(`${R.file}:${R.line}:${R.column}`),_.push(...R.context),_.push("");if(K.length>=Q)_.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return sB(_.join(`
166
+ `))}let F;try{F=new RegExp(V,"gim")}catch(_){throw Error(`Invalid regex pattern: ${V}. ${_ instanceof Error?_.message:""}`)}let A=[],D=0,U=await i1(B);for(let _ of U){if(H.signal?.aborted)throw Error("Search operation aborted");if(!vT(_,X,Y,j))continue;if(A.length>=Q)break;D++;let R=h9.join(B,_);try{let O=(await eB.readFile(R,"utf-8")).split(`
167
+ `);for(let L=0;L<O.length;L++){let C=O[L];F.lastIndex=0;let N=F.exec(C);while(N!==null){if(A.length>=Q)break;let p=Math.max(0,L-J),k=Math.min(O.length-1,L+J),P=[];for(let r=p;r<=k;r++){let c=r===L?">":" ";P.push(`${c} ${r+1}: ${O[r]}`)}if(A.push({file:_,line:L+1,column:N.index+1,match:N[0],context:P}),N.index===F.lastIndex)F.lastIndex++;N=F.exec(C)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
168
+ Searched ${D} files.`;let f=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${D} files.`,""];for(let _ of A)f.push(`${_.file}:${_.line}:${_.column}`),f.push(..._.context),f.push("");if(A.length>=Q)f.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return sB(f.join(`
169
+ `))}}function sB($){if($.length<=P8)return $;let W=Math.ceil(P8/2),Z=Math.max(1,P8-W);return`${$.slice(0,W)}
170
170
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
171
- `+$.slice(-Z)}function xT($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
171
+ `+$.slice(-Z)}function cT($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
172
172
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(W,Z)=>String.fromCharCode(parseInt(Z,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
173
173
  `).replace(/\n{3,}/g,`
174
174
 
175
- `).trim()}function k4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",D=F.body?.getReader();if(!D)throw Error("Failed to read response body");let U=[],f=0;while(!0){let{done:C,value:N}=await D.read();if(C)break;if(f+=N.length,f>Z)throw D.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(N)}let _=new Uint8Array(f),R=0;for(let C of U)_.set(C,R),R+=C.length;let T=new TextDecoder("utf-8").decode(_),O;if(A.includes("text/html")||A.includes("application/xhtml"))O=xT(T);else if(A.includes("application/json"))try{let C=JSON.parse(T);O=JSON.stringify(C,null,2)}catch{O=T}else O=T;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${f} bytes`,"","--- Content ---",O.slice(0,50000)];if(O.length>50000)L.push(`
175
+ `).trim()}function I4($={}){let{timeoutMs:W=30000,maxResponseBytes:Z=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:j=!0}=$;return async(X,Y,V)=>{let B;try{B=new URL(X)}catch{throw Error(`Invalid URL: ${X}`)}if(!["http:","https:"].includes(B.protocol))throw Error(`Invalid protocol: ${B.protocol}. Only http and https are supported.`);let H=new AbortController,G=setTimeout(()=>H.abort(),W),K;if(V.signal)K=()=>H.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(X,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...J},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(G),!j&&F.status>=300&&F.status<400)return`Redirect to: ${F.headers.get("location")}`;if(!F.ok)throw Error(`HTTP ${F.status}: ${F.statusText}`);let A=F.headers.get("content-type")||"",D=F.body?.getReader();if(!D)throw Error("Failed to read response body");let U=[],f=0;while(!0){let{done:C,value:N}=await D.read();if(C)break;if(f+=N.length,f>Z)throw D.cancel(),Error(`Response too large: exceeded ${Z} bytes`);U.push(N)}let _=new Uint8Array(f),R=0;for(let C of U)_.set(C,R),R+=C.length;let T=new TextDecoder("utf-8").decode(_),O;if(A.includes("text/html")||A.includes("application/xhtml"))O=cT(T);else if(A.includes("application/json"))try{let C=JSON.parse(T);O=JSON.stringify(C,null,2)}catch{O=T}else O=T;let L=[`URL: ${X}`,`Content-Type: ${A}`,`Size: ${f} bytes`,"","--- Content ---",O.slice(0,50000)];if(O.length>50000)L.push(`
176
176
  [Content truncated: showing first 50000 of ${O.length} characters]`);return L.push("","--- Analysis Request ---",`Prompt: ${Y}`),L.join(`
177
- `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function I4($={}){return K2($)}function y8($={}){return{readFile:y4($.fileRead),search:h4($.search),bash:I4($.bash),webFetch:k4($.webFetch),applyPatch:U2($.applyPatch),editor:D2($.editor)}}var gT={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},h8=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function eB($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function mT($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return eB(W,$.providerIdIncludes)&&eB(Z,$.modelIdIncludes)}function k8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!mT(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[gT[X]]=Y;return j}var a0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function i1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function k9($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of L$)Z[Q]=W;return Z}function I9($,W){let Z=a0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return q$({...j,...W})}import{createTool as Kq,zodToJsonSchema as Fq}from"@cline/shared";import{z as P3}from"zod";U1();import{createAgentRuntime as $q}from"@cline/agents";import{createContributionRegistry as Wq,mergeModelOptions as SH}from"@cline/shared";import{createGateway as jz,createHandlerAsync as Xz,hasRegisteredHandler as Yz,MODEL_COLLECTIONS_BY_PROVIDER_ID as Vz,normalizeProviderId as Bz}from"@cline/llms";import{EMPTY_CONTENT_TEXT as oT}from"@cline/shared";function sT($){let W=eT($.content),Z=[],Q=$.id??Zz(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map($z),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:GH($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:oT}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:GH($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[FH(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function d9($){return $.flatMap(sT)}function tT($){let W=$.content.map(AH).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:Wz($.metrics)}}function I8($){return $.map(tT)}function l9($){let W=[];for(let Z of $){let Q=Z.content.map(AH).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function eT($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function $z($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return FH($)}}function FH($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function AH($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function GH($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function Wz($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var KH=0;function Zz(){return KH+=1,`msg_${Date.now().toString(36)}_${KH.toString(36)}`}function Qz($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:Jz($),error:$.error}];default:return[]}}function Jz($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function UH($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=l9(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of Qz(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function Hz($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function Gz($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function Kz($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(Gz($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return Hz(W)}function Fz($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function f3($){let W=$.providerConfig,Z=W?.knownModels?W.knownModels:$.knownModels??Vz[$.providerId]?.models??void 0,Q=Fz(W?.maxInputTokens),J=W?.modelInfo&&W.modelInfo.id===$.modelId?W.modelInfo:void 0;if(Q===void 0&&!J)return Z;return{...Z??{},[$.modelId]:{...Z?.[$.modelId],...Q!==void 0?{contextWindow:Q,maxInputTokens:Q}:{},...J,id:$.modelId}}}function Az($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function Uz($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:Az(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function DH($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:f3($),maxOutputTokens:$.maxTokensPerTurn,temperature:$.temperature,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(Yz(Bz(j.providerId)))return UH(()=>Xz(j));return jz({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,timeoutMs:j.timeoutMs,fetch:j.fetch,options:Kz(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>Uz(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens,temperature:j.temperature})}D0();import{createMediaBudgetState as Dz,IMAGE_OMITTED_PLACEHOLDER as _H,normalizeUserInput as fH,resolveMediaBudget as _z,validateAndReserveImageMedia as fz}from"@cline/shared";var Lz=8000,Oz=50000,Tz=6000000,zz=200000,qz=12000,Mz=65536,v4=2000,LH=40000,Rz=8,L3={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},Nz=new Set(["read","read_files"]),O2="[outdated - see the latest file content]",OH="Tool execution was interrupted before a result was produced.",TH=($)=>`
177
+ `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${W}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function x4($={}){return K2($)}function h8($={}){return{readFile:h4($.fileRead),search:k4($.search),bash:x4($.bash),webFetch:I4($.webFetch),applyPatch:U2($.applyPatch),editor:D2($.editor)}}var uT={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion",submit_and_exit:"enableSubmitAndExit"},k8=[{name:"openai-native-use-apply-patch",mode:"act",providerIdIncludes:["openai-native"],enableTools:["apply_patch"],disableTools:["editor"]},{name:"codex-and-gpt-use-apply-patch",mode:"act",modelIdIncludes:["codex","gpt"],enableTools:["apply_patch"],disableTools:["editor"]}];function $H($,W){if(!W||W.length===0)return!0;let Z=$.toLowerCase();return W.some((Q)=>Z.includes(Q.toLowerCase()))}function dT($,W,Z,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return $H(W,$.providerIdIncludes)&&$H(Z,$.modelIdIncludes)}function I8($,W,Z,Q){if(!Q||Q.length===0)return{};let J=new Map;for(let X of Q){if(!dT(X,$,W,Z))continue;for(let Y of X.disableTools??[])J.set(Y,!1);for(let Y of X.enableTools??[])J.set(Y,!0)}let j={};for(let[X,Y]of J.entries())j[uT[X]]=Y;return j}var t0={act:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!0,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},plan:{enableReadFiles:!0,enableSearch:!0,enableBash:!0,enableWebFetch:!0,enableApplyPatch:!1,enableEditor:!1,enableSkills:!0,enableAskQuestion:!0,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},search:{enableReadFiles:!0,enableSearch:!0,enableBash:!1,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!0},minimal:{enableReadFiles:!1,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!1,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!1,enableSpawnAgent:!0,enableAgentTeams:!1},yolo:{enableReadFiles:!0,enableSearch:!1,enableBash:!0,enableWebFetch:!1,enableApplyPatch:!1,enableEditor:!0,enableSkills:!1,enableAskQuestion:!1,enableSubmitAndExit:!0,enableSpawnAgent:!1,enableAgentTeams:!1}};function n1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function k9($){if($!=="yolo")return{};let W={enabled:!0,autoApprove:!0},Z={"*":W};for(let Q of O$)Z[Q]=W;return Z}function I9($,W){let Z=t0[$],{enableSpawnAgent:Q,enableAgentTeams:J,...j}=Z;return M$({...j,...W})}import{createTool as _q,zodToJsonSchema as fq}from"@cline/shared";import{z as P3}from"zod";_1();import{createAgentRuntime as Jq}from"@cline/agents";import{createContributionRegistry as jq,isLikelyAuthError as Xq,mergeModelOptions as bH}from"@cline/shared";import{createGateway as Bz,createHandlerAsync as Hz,hasRegisteredHandler as Gz,MODEL_COLLECTIONS_BY_PROVIDER_ID as Kz,normalizeProviderId as Fz}from"@cline/llms";import{EMPTY_CONTENT_TEXT as $z}from"@cline/shared";function Wz($){let W=Qz($.content),Z=[],Q=$.id??Xz(),J=0,j=[],X=()=>{if(j.length===0)return;let Y=J===0?Q:`${Q}_part_${J}`;J+=1,Z.push({id:Y,role:$.role,content:j.map(Jz),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:KH($.metrics)}),j=[]};if(W.length===0)return Z.push({id:Q,role:$.role,content:[{type:"text",text:$z}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:KH($.metrics)}),Z;for(let Y of W){if(Y.type!=="tool_result"){j.push(Y);continue}X(),Z.push({id:`${Q}_tool_${Y.tool_use_id}`,role:"tool",content:[AH(Y)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return X(),Z}function d9($){return $.flatMap(Wz)}function Zz($){let W=$.content.map(UH).filter((Z)=>Z!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:W,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:jz($.metrics)}}function x8($){return $.map(Zz)}function l9($){let W=[];for(let Z of $){let Q=Z.content.map(UH).filter((X)=>X!==void 0),J=Z.role==="tool"?"user":Z.role,j=W[W.length-1];if(J==="user"&&Q.length>0&&Q.every((X)=>X.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((X)=>X.type==="tool_result")){j.content.push(...Q);continue}W.push({role:J,content:Q})}return W}function Qz($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function Jz($){switch($.type){case"text":return{type:"text",text:$.text};case"thinking":return{type:"reasoning",text:$.thinking,metadata:$.signature?{signature:$.signature,details:$.details}:$.details?{details:$.details}:void 0};case"redacted_thinking":return{type:"reasoning",text:"",redacted:!0,metadata:{data:$.data}};case"image":return{type:"image",image:$.data,mediaType:$.mediaType};case"file":return{type:"file",path:$.path,content:$.content};case"tool_use":return{type:"tool-call",toolCallId:$.id,toolName:$.name,input:$.input,metadata:$.signature?{signature:$.signature}:void 0};case"tool_result":return AH($)}}function AH($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function UH($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let W=$.metadata;return{type:"thinking",thinking:$.text,signature:W?.signature,details:W?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":{let W=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:W?.thoughtSignature??W?.signature}}case"tool-result":{let W=$.output,Z=typeof W==="string"?W:Array.isArray(W)?W:JSON.stringify(W);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Z,is_error:$.isError}}}}function KH($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function jz($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var FH=0;function Xz(){return FH+=1,`msg_${Date.now().toString(36)}_${FH.toString(36)}`}function Yz($){switch($.type){case"text":return[{type:"text-delta",text:$.text}];case"reasoning":return[{type:"reasoning-delta",text:$.reasoning,metadata:$.signature?{thoughtSignature:$.signature,details:$.details}:{details:$.details}}];case"tool_calls":{let W=$.tool_call.function,Z=W.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??W.id,toolName:W.name,inputText:typeof Z==="string"?Z:void 0,input:typeof Z==="string"?void 0:Z,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,reasoningTokenCount:$.thoughtsTokenCount,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:Vz($),error:$.error}];default:return[]}}function Vz($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function DH($){return{async*stream(W){let Z=!1,Q=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(W.signal);let j=l9(W.messages),X=W.tools.map((Y)=>({name:Y.name,description:Y.description,inputSchema:Y.inputSchema}));for await(let Y of J.createMessage(W.systemPrompt??"",j,X))for(let V of Yz(Y)){if(V.type==="finish")Z=!0;else if(V.type==="tool-call-delta")Q=!0;yield V}if(!Z)yield{type:"finish",reason:Q?"tool-calls":"stop"}}catch(J){if(!Z)yield{type:"finish",reason:W.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function Az($){let W=Object.fromEntries(Object.entries($).filter(([,Z])=>Z!==void 0));return Object.keys(W).length>0?W:void 0}function Uz($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function Dz($){let W={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(Uz($))Object.assign(W,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(W,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Z=$.gcp?.region??$.region;Object.assign(W,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Z,region:Z})}if($.providerId==="sapaicore")Object.assign(W,$.sap);return Az(W)}function _z($){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):void 0}function f3($){let W=$.providerConfig,Z=W?.knownModels?W.knownModels:$.knownModels??Kz[$.providerId]?.models??void 0,Q=_z(W?.maxInputTokens),J=W?.modelInfo&&W.modelInfo.id===$.modelId?W.modelInfo:void 0;if(Q===void 0&&!J)return Z;return{...Z??{},[$.modelId]:{...Z?.[$.modelId],...Q!==void 0?{contextWindow:Q,maxInputTokens:Q}:{},...J,id:$.modelId}}}function fz($){if(!$?.length)return;let W=new Set;for(let Z of $)switch(Z){case"tools":case"reasoning":case"prompt-cache":case"images":W.add(Z);break;case"structured_output":W.add("structured-output");break;default:W.add("text")}return W.add("text"),[...W]}function Lz($,W){return{id:$,name:W.name??$,description:W.description,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxOutputTokens:W.maxTokens,capabilities:fz(W.capabilities),metadata:{family:W.family,pricing:W.pricing,status:W.status,releaseDate:W.releaseDate}}}function _H($,W,Z){let Q=$.providerConfig,J=Q?.providerId===$.providerId?Q:void 0,j={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:f3($),maxOutputTokens:$.maxTokensPerTurn,temperature:$.temperature,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:W,extensionContext:$.extensionContext};if(Gz(Fz(j.providerId)))return DH(()=>Hz(j));return Bz({fetch:j.fetch,providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,timeoutMs:j.timeoutMs,fetch:j.fetch,options:Dz(j),models:j.knownModels?Object.entries(j.knownModels).map(([X,Y])=>Lz(X,Y)):void 0}],logger:W,telemetry:Z??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens,temperature:j.temperature})}U0();import{createMediaBudgetState as Oz,IMAGE_OMITTED_PLACEHOLDER as fH,normalizeUserInput as LH,resolveMediaBudget as Tz,validateAndReserveImageMedia as zz}from"@cline/shared";var qz=8000,Mz=50000,Rz=6000000,Nz=200000,Ez=12000,wz=65536,c4=2000,OH=40000,Cz=8,L3={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},Pz=new Set(["read","read_files"]),O2="[outdated - see the latest file content]",TH="Tool execution was interrupted before a result was produced.",zH=($)=>`
178
178
 
179
179
  ...[truncated ${$} chars]...
180
180
 
181
- `,c4=($)=>`
181
+ `,u4=($)=>`
182
182
 
183
183
  ...[truncated ${$} chars to fit provider request budget]...
184
184
 
185
- `,Ez=($)=>`
185
+ `,Sz=($)=>`
186
186
 
187
187
  ...[assistant text truncated: omitted ${$} chars]...
188
188
 
189
- `,zH=($)=>`
189
+ `,qH=($)=>`
190
190
 
191
191
  ...[assistant text truncated: omitted ${$} chars to fit provider request budget]...
192
192
 
193
- `,wz=($)=>`
193
+ `,bz=($)=>`
194
194
 
195
195
  ...[assistant text truncated: omitted ${$} chars due to repeated tool-call markup]...
196
196
 
197
- `;function RH($=process.env){return{maxToolResultChars:MH($[L3.maxToolResultChars]),maxTotalTextBytes:MH($[L3.maxTotalTextBytes]),minOutdatedRewriteBytes:Pz($[L3.minOutdatedRewriteBytes])}}class T3{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=m4($.maxToolResultChars,Lz),this.maxFileContentChars=m4($.maxFileContentChars,Oz),this.maxTotalTextBytes=m4($.maxTotalTextBytes,Tz),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=m4($.maxAssistantTextChars,zz),this.maxAssistantToolMarkupChars=m4($.maxAssistantToolMarkupChars,qz),this.minOutdatedRewriteBytes=Sz($.minOutdatedRewriteBytes,Mz)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=fH(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=fH($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=x8($.content,this.maxFileContentChars,TH);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(R$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${OH} Tool: ${$}.`:OH}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(R$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??O2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:O2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:O2}}if(R$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:O2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=O2;else if(typeof Q.content==="string")Q.content=O2;else Q.result=O2;return Q}isReadTool($){return!!$&&Nz.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(R$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(z3($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return x8($,this.maxToolResultChars,TH)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return x8($,this.maxAssistantToolMarkupChars,wz);return x8($,this.maxAssistantTextChars,Ez)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(Cz))if(W+=1,W>=Rz)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>yz(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=bz(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=p9(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(R$(J))W+=p9(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:LH,makeMarker:zH,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){r9(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:LH,makeMarker:zH,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:v4,makeMarker:c4,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:v4,makeMarker:c4,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:v4,makeMarker:c4,get:()=>j.content,set:(X)=>{j.content=X}});else if(R$(j))r9(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=Dz(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return _z(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if(O3($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if(O3($))return this.limitImageContent($,W,Z);if(R$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if(O3($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!NH($))return{type:"text",text:_H};let Q=fz($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:_H};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var qH=String.raw`[\|\uFF5C]`,Cz=new RegExp(String.raw`<\s*(?:${qH}\s*)?DSML\s*(?:${qH}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function MH($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function Pz($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function m4($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function Sz($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function x8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function bz($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=x8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=x8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function yz($){if($.type==="tool_use")return{...$,input:i9($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>R$(W)?i9(W):{...W})}}function R$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function O3($){return $!==null&&typeof $==="object"&&$.type==="image"}function NH($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function z3($){return NH($)}function p9($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=p9(Z);return W}if($!==null&&typeof $==="object"){if(z3($))return 0;let W=0;for(let Z of Object.values($))W+=p9(Z);return W}return 0}function r9($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:v4,makeMarker:c4,get:()=>$[Q],set:(J)=>{$[Q]=J}});else r9(Z,W)});return}if($!==null&&typeof $==="object"){if(z3($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:v4,makeMarker:c4,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else r9(J,W)}}}function i9($){if(Array.isArray($))return $.map(i9);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=i9(Q);return W}return $}function q3(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class M3{messages=[];conversationId=q3();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=q3(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=q3(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function EH($){let{agentConfig:W}=$,Z=hz(W),Q=kz(W),J=$.hooks,j=Iz(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function hz($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.temperature!==void 0)W.temperature=$.temperature;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function kz($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function Iz($){if($===void 0)return;return $>=2?"parallel":"sequential"}var wH={};w(wH,{normalizeConnectionUpdate:()=>T2,buildConnectionUpdate:()=>R3});function R3($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function T2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function xz(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function gz($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function N3($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(N3);let W={};for(let Z of Object.keys($).sort())W[Z]=N3($[Z]);return W}function mz($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(N3($))}catch{return String($)}}function vz($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var CH={softThreshold:3,hardThreshold:5};class E3{config;state=xz();constructor($){this.config={softThreshold:$?.softThreshold??CH.softThreshold,hardThreshold:$?.hardThreshold??CH.hardThreshold}}inspect($){let W=mz($.input),Z=vz(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){gz(this.state)}}class w3{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J={iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details};this.options.onLimitTelemetry?.(J);let j=await uz(J,this.options.onLimitReached);if(j.action==="continue"){let X=j.guidance?.trim();if(X)this.options.appendRecoveryNotice(X,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:X}}return{action:"stop",reason:j.reason?.trim()||void 0,message:cz({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:j.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function cz($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function uz($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function dz($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function lz($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function pz($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function rz($){return $.content.find((W)=>W.type==="tool-result")}function iz($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function nz($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class C3{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:dz($.metadata?.reason),metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let W=[],Z=lz($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=pz($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=rz($.message),J=Q?.output,j=nz(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:iz($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function Zq($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function Qq($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function Jq($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
197
+ `;function NH($=process.env){return{maxToolResultChars:RH($[L3.maxToolResultChars]),maxTotalTextBytes:RH($[L3.maxTotalTextBytes]),minOutdatedRewriteBytes:hz($[L3.minOutdatedRewriteBytes])}}class T3{indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;maxToolResultChars;maxFileContentChars;maxTotalTextBytes;mediaBudget;maxAssistantTextChars;maxAssistantToolMarkupChars;minOutdatedRewriteBytes;committedOutdatedRewrites=new Map;constructor($={}){this.maxToolResultChars=v4($.maxToolResultChars,qz),this.maxFileContentChars=v4($.maxFileContentChars,Mz),this.maxTotalTextBytes=v4($.maxTotalTextBytes,Rz),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=v4($.maxAssistantTextChars,Nz),this.maxAssistantToolMarkupChars=v4($.maxAssistantToolMarkupChars,Ez),this.minOutdatedRewriteBytes=kz($.minOutdatedRewriteBytes,wz)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Z=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let Y=LH(J.content);if(Y!==J.content)return{...J,content:Y}}if(J.role==="assistant"&&typeof J.content==="string"){let Y=this.truncateAssistantText(J.content);if(Y!==J.content)return{...J,content:Y}}return J}let j=!1,X=J.content.map((Y)=>{let V=this.transformBlock(Y,J.role);if(V!==Y)j=!0;return V});return j?{...J,content:X}:J}),Q=this.applyMediaBudget(Z);return this.truncateToTotalTextBudget(Q)}transformBlock($,W){if(W==="user"&&$.type==="text"&&typeof $.text==="string"){let J=LH($.text);if(J!==$.text)return{...$,text:J};return $}if(W==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=g8($.content,this.maxFileContentChars,zH);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Z=this.resolveToolName($),Q=$.content;if(this.isReadTool(Z)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let X=this.getReadLocators($).filter((Y)=>J.has(this.toReadLocatorKey(Y))&&this.isOutdatedReadLocator(Y,$.tool_use_id));if(X.length>0)Q=this.replaceOutdatedReadContent(Q,X)}}return Q=this.truncateToolResultContent(Q),Q===$.content?$:{...$,content:Q}}reindex($){let W=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!W)this.resetIndexes();for(let Z=this.indexedMessageCount;Z<$.length;Z++){let Q=$[Z];if(!Array.isArray(Q.content))continue;for(let J=0;J<Q.content.length;J++){let j=Q.content[J];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Z}:${J}`);else if(j.type==="tool_use"){let X=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,X),this.isReadTool(X)){let Y=this.extractLocatorsFromReadToolInput(j.input);if(Y.length>0)this.readLocatorsByToolUseIdCache.set(j.id,Y)}}else if(j.type==="tool_result"){let X=this.resolveToolName(j);if(!this.isReadTool(X)||j.is_error===!0)continue;let Y=this.getReadLocators(j);for(let V of Y)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),j.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let W=new Map,Z=new Set,Q=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let j of J.content){if(j.type!=="tool_result"||j.is_error===!0)continue;let X=this.resolveToolName(j);if(!this.isReadTool(X))continue;Z.add(j.tool_use_id);let Y=this.committedOutdatedRewrites.get(j.tool_use_id),V=new Set,B=new Set;for(let G of this.getReadLocators(j)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,j.tool_use_id))continue;if(B.add(K),!Y?.has(K))V.add(K)}if(Y){for(let G of Y)if(!B.has(G))Y.delete(G);if(Y.size===0)this.committedOutdatedRewrites.delete(j.tool_use_id)}if(V.size===0)continue;let H=W.get(j.tool_use_id);if(!H)H=new Set,W.set(j.tool_use_id,H);for(let G of V)H.add(G);Q+=this.estimateOutdatedReclaimBytes(j.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Z.has(J))this.committedOutdatedRewrites.delete(J);if(W.size===0||Q<this.minOutdatedRewriteBytes)return;for(let[J,j]of W){let X=this.committedOutdatedRewrites.get(J);if(!X)X=new Set,this.committedOutdatedRewrites.set(J,X);for(let Y of j)X.add(Y)}}estimateOutdatedReclaimBytes($,W){let Z=this.extractReadLocatorsFromToolResultContent($),Q=Z.length>0&&Z.every((V)=>W.has(this.toReadLocatorKey(V))),J=(V)=>{let B;try{B=JSON.parse(V)}catch{return Q||Z.length===0?j0(this.truncateMiddle(V)):0}let H=Array.isArray(B)?B:[B],G=0;for(let K of H){let F=this.extractLocatorFromResultEntry(K);if(F&&W.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let j=new Set(W),X=0;for(let V of $)if(V.type==="text")X+=this.countOutdatedImageEntries(V.text,j);let Y=0;for(let V of $)if(V.type==="text")Y+=J(V.text);else if(V.type==="image"){if(X>0)X-=1,Y+=j0(V.data)}else if(N$(V)){let B=this.extractLocatorFromResultEntry(V);if(B&&W.has(this.toReadLocatorKey(B)))Y+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(W.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))Y+=j0(this.truncateMiddle(V.content))}return Y}providerBoundEntryBytes($){let W=this.truncateNestedStrings($);return j0(JSON.stringify(W))}addMissingToolResults($){let W=this.collectToolResultIds($),Z=[],Q=new Map,J=!1,j=()=>{if(Q.size===0)return;X(this.createMissingToolResultMessage(Q)),Q.clear(),J=!0},X=(Y)=>{let V=Z.at(-1);if(this.shouldMergeUserAfterToolResults(V,Y)){Z[Z.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(Y.content)]},J=!0;return}Z.push(Y)};for(let Y of $){if(this.isToolResultOnlyMessage(Y)){if(X(this.appendMissingToolResults(Y,Q)),Q.size>0)Q.clear(),J=!0;continue}if(Array.isArray(Y.content)){let V=Y.content.filter((H)=>H.type==="tool_result"),B=Y.content.filter((H)=>H.type!=="tool_result");if(V.length>0){let H=this.appendMissingToolResults({...Y,role:"user",content:V},Q);if(X(H),Q.size>0)Q.clear();J=!0}if(B.length>0||V.length===0){if(V.length===0)j();let H=V.length>0?{...Y,content:B}:Y;if(X(H),H.role==="assistant")this.trackMissingToolCalls(H,W,Q)}continue}j(),X(Y)}return j(),J?Z:$}appendMissingToolResults($,W){if(W.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(W)]}}shouldMergeUserAfterToolResults($,W){return $?.role==="user"&&W.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(W.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let W=new Set;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content)if(Q.type==="tool_result")W.add(Q.tool_use_id)}return W}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((W)=>W.type==="tool_result")}trackMissingToolCalls($,W,Z){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||W.has(Q.id))continue;Z.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([W,Z])=>({type:"tool_result",tool_use_id:W,name:Z,content:[{type:"text",text:this.formatMissingToolResultText(Z)}],is_error:!0}))}formatMissingToolResultText($){return $?`${TH} Tool: ${$}.`:TH}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let W=$,Z=this.readResultLocatorCache.get(W);if(Z===void 0)Z=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(W,Z);if(Z.length>0)return Z;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let W=$,Z=[],Q=this.extractLocatorFromReadRequest(W);if(Q)Z.push(Q);if(Array.isArray(W.files))for(let J of W.files){let j=this.extractLocatorFromReadRequest(J);if(j)Z.push(j)}if(Array.isArray(W.file_paths)){for(let J of W.file_paths)if(typeof J==="string"&&J.length>0)Z.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Z)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let W=[];for(let Z of $){if(Z.type==="text"){W.push(...this.tryParseReadLocators(Z.text));continue}if(N$(Z)){let Q=this.extractLocatorFromResultEntry(Z);if(Q)W.push(Q)}}return this.dedupeReadLocators(W)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Z=[];for(let Q of $){let J=this.extractLocatorFromResultEntry(Q);if(J)Z.push(J)}return this.dedupeReadLocators(Z)}let W=this.extractLocatorFromResultEntry($);return W?[W]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(!Z)return;return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let W=$,Z=this.extractPath(W);if(Z)return{path:Z,startLine:this.extractLineNumber(W.start_line),endLine:this.extractLineNumber(W.end_line)};if(typeof W.query==="string"&&W.query.length>0)return this.parseReadQuery(W.query);return}extractPath($){let W=[$.path,$.file_path,$.filePath];for(let Z of W)if(typeof Z==="string"&&Z.length>0)return Z;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let W=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!W)return{path:$,startLine:null,endLine:null};return{path:W[1],startLine:Number(W[2]),endLine:W[3]==="EOF"?null:Number(W[3])}}dedupeReadLocators($){let W=new Map;for(let Z of $)W.set(this.toReadLocatorKey(Z),Z);return Array.from(W.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,W){let Z=this.latestFullContentOwnerByPathCache.get($.path);if(Z&&Z!==W)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==W}replaceOutdatedReadContent($,W){let Z=new Set(W.map((j)=>this.toReadLocatorKey(j))),Q=new Set(W.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Z)??O2;let J=0;for(let j of $)if(j.type==="text")J+=this.countOutdatedImageEntries(j.text,Z);return $.map((j)=>{if(j.type==="file"){if(!Q.has(j.path))return j;return{...j,content:O2}}if(j.type==="image"){if(J===0)return j;return J-=1,{type:"text",text:O2}}if(N$(j))return this.replaceOutdatedReadEntry(j,Z);if(j.type!=="text")return j;let X=this.replaceOutdatedInString(j.text,Z);if(X===null)return{...j,text:O2};return X===j.text?j:{...j,text:X}})}countOutdatedImageEntries($,W){let Z;try{Z=JSON.parse($)}catch{return 0}let Q=Array.isArray(Z)?Z:[Z],J=0;for(let j of Q){if(!j||typeof j!=="object")continue;let X=j,Y=this.extractLocatorFromResultEntry(X);if(!Y)continue;if(!W.has(this.toReadLocatorKey(Y)))continue;if(X.result==="Successfully read image"||X.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,W){let Z;try{Z=JSON.parse($)}catch{return null}let Q=Array.isArray(Z)?Z.map((J)=>this.replaceOutdatedReadEntry(J,W)):this.replaceOutdatedReadEntry(Z,W);return JSON.stringify(Q)}replaceOutdatedReadEntry($,W){if(!$||typeof $!=="object")return $;let Z=this.extractLocatorFromResultEntry($);if(!Z||!W.has(this.toReadLocatorKey(Z)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=O2;else if(typeof Q.content==="string")Q.content=O2;else Q.result=O2;return Q}isReadTool($){return!!$&&Pz.has($)}resolveToolName($){let W=this.toolNameByIdCache.get($.tool_use_id);if(W!==void 0)return W;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((W)=>{if(W.type==="file"){let Z=this.truncateMiddle(W.content);return Z===W.content?W:{...W,content:Z}}if(W.type==="text"){let Z=this.truncateMiddle(W.text);return Z===W.text?W:{...W,text:Z}}if(N$(W))return this.truncateNestedStrings(W);return W})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let W=!1,Z=$.map((Q)=>{let J=this.truncateNestedStrings(Q);if(J!==Q)W=!0;return J});return W?Z:$}if($!==null&&typeof $==="object"){if(z3($))return $;let W=!1,Z={};for(let[Q,J]of Object.entries($)){let j=this.truncateNestedStrings(J);if(j!==J)W=!0;Z[Q]=j}return W?Z:$}return $}truncateMiddle($){return g8($,this.maxToolResultChars,zH)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return g8($,this.maxAssistantToolMarkupChars,bz);return g8($,this.maxAssistantTextChars,Sz)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let W=0;for(let Z of $.matchAll(yz))if(W+=1,W>=Cz)return!0;return!1}truncateToTotalTextBudget($){let W=this.countMessageTextBytes($);if(W<=this.maxTotalTextBytes)return $;let Z=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((j)=>xz(j))}}),Q=this.collectTruncationCandidates(Z);for(let J of Q){if(W<=this.maxTotalTextBytes)break;let j=J.byteLength;if(j<=J.minBytes)continue;let X=W-this.maxTotalTextBytes,Y=Math.max(J.minBytes,j-X),V=Iz(J.get(),Y,J.makeMarker);J.set(V),W-=j-j0(V)}return Z}countMessageTextBytes($){let W=0;for(let Z of $){if(typeof Z.content==="string"){W+=j0(Z.content);continue}for(let Q of Z.content)if(Q.type==="text")W+=j0(Q.text);else if(Q.type==="thinking")W+=j0(Q.thinking);else if(Q.type==="file")W+=j0(Q.content);else if(Q.type==="tool_use")W+=p9(Q.input);else if(Q.type==="tool_result"){if(typeof Q.content==="string")W+=j0(Q.content);else for(let J of Q.content)if(J.type==="text")W+=j0(J.text);else if(J.type==="file")W+=j0(J.content);else if(N$(J))W+=p9(J)}}return W}collectTruncationCandidates($){let W=[],Z=[];for(let Q of $){if(Q.role==="assistant"&&typeof Q.content==="string"){W.push({byteLength:j0(Q.content),minBytes:OH,makeMarker:qH,get:()=>Q.content,set:(J)=>{Q.content=J}});continue}if(!Array.isArray(Q.content))continue;for(let J of Q.content){if(J.type==="tool_use"){r9(J.input,Z);continue}if(Q.role==="assistant"&&J.type==="text"){W.push({byteLength:j0(J.text),minBytes:OH,makeMarker:qH,get:()=>J.text,set:(j)=>{J.text=j}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){W.push({byteLength:j0(J.content),minBytes:c4,makeMarker:u4,get:()=>J.content,set:(j)=>{J.content=j}});continue}for(let j of J.content)if(j.type==="text")W.push({byteLength:j0(j.text),minBytes:c4,makeMarker:u4,get:()=>j.text,set:(X)=>{j.text=X}});else if(j.type==="file")W.push({byteLength:j0(j.content),minBytes:c4,makeMarker:u4,get:()=>j.content,set:(X)=>{j.content=X}});else if(N$(j))r9(j,W)}}return W.sort((Q,J)=>J.byteLength-Q.byteLength),Z.sort((Q,J)=>J.byteLength-Q.byteLength),[...W,...Z]}applyMediaBudget($){let W=this.resolveMediaBudget();if(W.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&W.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&W.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Z=Oz(),Q=!1,J=$.map((j)=>{if(!Array.isArray(j.content))return j;let X=!1,Y=j.content.map((V)=>{let B=this.applyMediaBudgetToBlock(V,W,Z);if(B!==V)X=!0;return B});if(!X)return j;return Q=!0,{...j,content:Y}});return Q?J:$}resolveMediaBudget(){return Tz(this.mediaBudget)}applyMediaBudgetToBlock($,W,Z){if(O3($))return this.limitImageContent($,W,Z);if($.type!=="tool_result"||typeof $.content==="string")return $;let Q=!1,J=$.content.map((j)=>{let X=this.applyMediaBudgetToToolResultEntry(j,W,Z);if(X!==j)Q=!0;return X});return Q?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,W,Z){if(O3($))return this.limitImageContent($,W,Z);if(N$($))return this.limitNestedMedia($,W,Z);return $}limitNestedMedia($,W,Z){if(O3($)){let Q=this.limitImageContent($,W,Z);return Q.type==="text"?Q.text:Q}if(Array.isArray($)){let Q=!1,J=$.map((j)=>{let X=this.limitNestedMedia(j,W,Z);if(X!==j)Q=!0;return X});return Q?J:$}if($!==null&&typeof $==="object"){let Q=!1,J={};for(let[j,X]of Object.entries($)){let Y=this.limitNestedMedia(X,W,Z);if(Y!==X)Q=!0;J[j]=Y}return Q?J:$}return $}limitImageContent($,W,Z){if(!EH($))return{type:"text",text:fH};let Q=zz($.mediaType,$.data,{maxImageEncodedBytes:W.maxImageEncodedBytes,maxImageDecodedBytes:W.maxImageDecodedBytes,maxTotalMediaBytes:W.maxTotalMediaBytes},Z);if(!Q.ok)return{type:"text",text:fH};return{...$,data:Q.base64,mediaType:Q.mediaType}}}var MH=String.raw`[\|\uFF5C]`,yz=new RegExp(String.raw`<\s*(?:${MH}\s*)?DSML\s*(?:${MH}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function j0($){return Buffer.byteLength($,"utf8")}function RH($){if($===void 0)return;let W=Number.parseInt($,10);return Number.isFinite(W)&&W>0?W:void 0}function hz($){if($===void 0)return;let W=$.trim().toLowerCase();if(W==="infinity"||W==="disable")return Number.POSITIVE_INFINITY;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>=0?Z:void 0}function v4($,W){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):W}function kz($,W){if(typeof $!=="number"||Number.isNaN($)||$<0)return W;return Number.isFinite($)?Math.floor($):$}function g8($,W,Z){if($.length<=W)return $;let Q=Z($.length-W),J=Math.max(0,Math.floor((W-Q.length)/2)),j=Math.max(0,$.length-J*2),X=Z(j),Y=Math.max(0,Math.floor((W-X.length)/2)),V=$.slice(0,Y),B=Y>0?$.slice(-Y):"";return`${V}${X}${B}`}function Iz($,W,Z){if(j0($)<=W)return $;let Q=0,J=$.length,j=g8($,0,Z);while(Q<=J){let X=Q+J>>>1,Y=g8($,X,Z);if(j0(Y)<=W)j=Y,Q=X+1;else J=X-1}return j}function xz($){if($.type==="tool_use")return{...$,input:i9($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((W)=>N$(W)?i9(W):{...W})}}function N$($){if($===null||typeof $!=="object")return!1;let W=$.type;return W!=="text"&&W!=="image"&&W!=="file"}function O3($){return $!==null&&typeof $==="object"&&$.type==="image"}function EH($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function z3($){return EH($)}function p9($){if(typeof $==="string")return j0($);if(Array.isArray($)){let W=0;for(let Z of $)W+=p9(Z);return W}if($!==null&&typeof $==="object"){if(z3($))return 0;let W=0;for(let Z of Object.values($))W+=p9(Z);return W}return 0}function r9($,W){if(Array.isArray($)){$.forEach((Z,Q)=>{if(typeof Z==="string")W.push({byteLength:j0(Z),minBytes:c4,makeMarker:u4,get:()=>$[Q],set:(J)=>{$[Q]=J}});else r9(Z,W)});return}if($!==null&&typeof $==="object"){if(z3($))return;let Z=$;for(let Q of Object.keys(Z)){let J=Z[Q];if(typeof J==="string")W.push({byteLength:j0(J),minBytes:c4,makeMarker:u4,get:()=>Z[Q],set:(j)=>{Z[Q]=j}});else r9(J,W)}}}function i9($){if(Array.isArray($))return $.map(i9);if($!==null&&typeof $==="object"){let W={};for(let[Z,Q]of Object.entries($))W[Z]=i9(Q);return W}return $}function q3(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class M3{messages=[];conversationId=q3();sessionStarted=!1;constructor($){if(($?.length??0)>0)this.restore($??[])}getConversationId(){return this.conversationId}getMessages(){return[...this.messages]}appendMessage($){this.messages.push($)}appendMessages($){if($.length===0)return;this.messages.push(...$)}replaceMessages($){this.messages=[...$]}resetForRun(){this.messages=[],this.conversationId=q3(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=q3(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function wH($){let{agentConfig:W}=$,Z=gz(W),Q=mz(W),J=$.hooks,j=vz(W.maxParallelToolCalls);return{sessionId:$.sessionId??W.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??W.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:Z,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:W.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??W.logger,telemetry:$.telemetry??W.telemetry,initialMessages:$.initialMessages,completionPolicy:W.completionPolicy,maxIterations:W.maxIterations,toolExecution:j,toolPolicies:W.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:W.requestToolApproval}}function gz($){let W={};if($.thinking!==void 0)W.thinking=$.thinking;if($.reasoningEffort!==void 0)W.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)W.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)W.maxTokensPerTurn=$.maxTokensPerTurn;if($.temperature!==void 0)W.temperature=$.temperature;if($.apiTimeoutMs!==void 0)W.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(W).length>0?W:void 0}function mz($){let W=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:W}}function vz($){if($===void 0)return;return $>=2?"parallel":"sequential"}var CH={};w(CH,{normalizeConnectionUpdate:()=>T2,buildConnectionUpdate:()=>R3});function R3($){let W={};if($.providerId!==void 0)W.providerId=$.providerId;if($.modelId!==void 0)W.modelId=$.modelId;if($.apiKey!==void 0)W.apiKey=$.apiKey;if($.baseUrl!==void 0)W.baseUrl=$.baseUrl;if($.headers!==void 0)W.headers=$.headers;if($.providerConfig!==void 0)W.providerConfig=$.providerConfig;if($.thinking===!1)return W.thinking=!1,W.reasoningEffort=null,W.thinkingBudgetTokens=null,W;if($.thinking===!0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort??null,W.thinkingBudgetTokens=null;else if($.reasoningEffort!==void 0)W.thinking=!0,W.reasoningEffort=$.reasoningEffort;if(typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0,W.thinkingBudgetTokens=Math.trunc($.thinkingBudgetTokens);return W}function T2($){let W={...$},Z=Object.hasOwn($,"thinking"),Q=Object.hasOwn($,"thinkingBudgetTokens");if($.thinking===!1||$.thinking===null)return W.reasoningEffort=void 0,W.thinkingBudgetTokens=void 0,W;if(!Z&&Q&&typeof $.thinkingBudgetTokens==="number"&&Number.isFinite($.thinkingBudgetTokens)&&$.thinkingBudgetTokens>0)W.thinking=!0;return W}function cz(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function uz($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function N3($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(N3);let W={};for(let Z of Object.keys($).sort())W[Z]=N3($[Z]);return W}function dz($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(N3($))}catch{return String($)}}function lz($,W,Z,Q){if(W===$.lastToolName&&Z===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=W,$.lastToolSignature=Z,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var PH={softThreshold:3,hardThreshold:5};class E3{config;state=cz();constructor($){this.config={softThreshold:$?.softThreshold??PH.softThreshold,hardThreshold:$?.hardThreshold??PH.hardThreshold}}inspect($){let W=dz($.input),Z=lz(this.state,$.name,W,this.config);if(Z.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Z.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){uz(this.state)}}class w3{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let W=this.options.maxConsecutiveMistakes,Z=$.forceAtLimit&&W?W:this.consecutiveMistakes+1;this.consecutiveMistakes=Z;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Z,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!W||Z<W)return{action:"continue"};let J={iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details};this.options.onLimitTelemetry?.(J);let j=await rz(J,this.options.onLimitReached);if(j.action==="continue"){let X=j.guidance?.trim();if(X)this.options.appendRecoveryNotice(X,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:X}}return{action:"stop",reason:j.reason?.trim()||void 0,message:pz({iteration:$.iteration,consecutiveMistakes:Z,maxConsecutiveMistakes:W,reason:$.reason,details:$.details,stopReason:j.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function pz($){let W=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Z=$.details?.trim();if(Z)W.push(`Error: ${Z}`);let Q=$.stopReason?.trim();if(Q)W.push(`Decision: ${Q}`);return W.push("Session state was preserved. Send a new prompt to resume from the latest state."),W.join(" ")}async function rz($,W){if(!W)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await W($)}catch(Z){return{action:"stop",reason:Z instanceof Error?Z.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function iz($){switch($){case"auto_compaction":case"manual_compaction":case"compaction_budget_emergency":return $;default:return}}function nz($){let W=$.content.filter((Z)=>Z.type==="text");if(W.length===0)return;return W.map((Z)=>Z.text).join("")}function az($){let W=$.content.filter((Z)=>Z.type==="reasoning");if(W.length===0)return;return{reasoning:W.map((Z)=>Z.text).join(""),redacted:W.some((Z)=>Z.redacted===!0)}}function oz($){return $.content.find((W)=>W.type==="tool-result")}function sz($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function tz($){if(!$||$.isError!==!0)return;if(typeof $.output==="string")return $.output;if($.output instanceof Error)return $.output.message;try{return JSON.stringify($.output)}catch{return String($.output)}}class C3{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:iz($.metadata?.reason),metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let W=[],Z=nz($);if(Z!==void 0)W.push({type:"content_end",contentType:"text",text:Z});let Q=az($);if(Q!==void 0)W.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return W}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=W===void 0?void 0:Date.now()-W;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=oz($.message),J=Q?.output,j=tz(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:j,durationMs:Z}]}translateUsage($){let W=$.inputTokens-this.lastUsage.inputTokens,Z=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,Y=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,W),outputTokens:Math.max(0,Z),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:Y===0?void 0:Y,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let W={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:sz($.status),text:$.outputText,iterations:$.iterations,usage:W}]}}function Yq($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function Vq($){let Z=(typeof $.content==="function"?await $.content():$.content).trim();return Z.length>0?Z:void 0}function Bq($,W){let Z=$.trim(),Q=W.map((J)=>J.trim()).filter(Boolean).join(`
198
198
 
199
199
  `);if(Z&&Q)return`${Z}
200
200
 
201
- ${Q}`;return Z||Q}function jq($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function Xq($,W){return $.filter((Z)=>jq(Z.name,W))}function Yq($,W){return n1(Xq($,W))}function Vq($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:SH(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:SH(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class N${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new C3;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??$q,this.conversation=new M3($.initialMessages),this.messageBuilder=new T3(RH()),this.contributionRegistry=Wq({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new w3({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,onLimitTelemetry:(j)=>{W9(this.telemetry,{ulid:this.config.sessionId??this.conversation.getConversationId(),model:this.config.modelId,provider:this.config.providerId,reason:j.reason,consecutiveMistakes:j.consecutiveMistakes,maxConsecutiveMistakes:j.maxConsecutiveMistakes,agentId:this.agentId,conversationId:this.conversation.getConversationId(),parentAgentId:this.parentAgentId,isSubagent:Boolean(this.parentAgentId)})},emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>Bq(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new E3(J)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=T2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await Qq(W);if(Z)$.push(Z)}return Jq(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await Gq(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=DH(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=Yq([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=bH(this.config),H=Array.from(Y.values()),G=d9(this.conversation.getMessages()),K=EH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[R9]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=I8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=Vq([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=I8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:d9(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(l9($));return d9(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?Zq(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(I8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=I8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":Hq(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?I8(W.messages):this.conversation.getMessages(),H=bH(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function Bq($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function Hq($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function Gq($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => PH);return J($,W,Z,Q)}function bH($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=f3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as yH}from"@cline/shared";function hH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return yH({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
202
- ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function kH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return yH({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function E$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function z2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?hH($.prompt,W):kH($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function w$($){let W=z2($),Z=new N$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var Aq=P3.object({systemPrompt:P3.string().describe("System prompt defining the sub-agent's behavior"),task:P3.string().describe("Task for the sub-agent to complete")});function C$($){return Kq({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:Fq(Aq),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=w$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as _0,TEAM_AWAIT_TIMEOUT_MS as Uq,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as Dq,TEAM_RUN_TEXT_PREVIEW_LIMIT as _q,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as fq,TeamAttachOutcomeFragmentInputSchema as IH,TeamAwaitRunsInputSchema as xH,TeamBroadcastInputSchema as gH,TeamBroadcastToolResultSchema as Lq,TeamCancelRunInputSchema as mH,TeamCancelRunToolResultSchema as Oq,TeamCleanupInputSchema as vH,TeamCleanupToolResultSchema as Tq,TeamCreateOutcomeInputSchema as cH,TeamCreateOutcomeToolResultSchema as zq,TeamFinalizeOutcomeInputSchema as uH,TeamFinalizeOutcomeToolResultSchema as qq,TeamListOutcomesInputSchema as dH,TeamListRunsInputSchema as lH,TeamMailboxMessageToolResultSchema as Mq,TeamMissionLogInputSchema as pH,TeamMissionLogToolResultSchema as Rq,TeamOutcomeFragmentToolResultSchema as rH,TeamOutcomeToolResultSchema as Nq,TeamReadMailboxInputSchema as iH,TeamReviewOutcomeFragmentInputSchema as nH,TeamRunTaskInputSchema as aH,TeamRunTaskToolResultSchema as S3,TeamRunToolSummarySchema as b3,TeamSendMessageInputSchema as oH,TeamSendMessageToolResultSchema as Eq,TeamShutdownTeammateInputSchema as sH,TeamSimpleAgentStatusToolResultSchema as tH,TeamSpawnTeammateInputSchema as eH,TeamStatusInputSchema as $G,TeamStatusToolResultSchema as wq,TeamTaskInputSchema as WG,TeamTaskToolResultSchema as d4,validateWithZod as g,zodToJsonSchema as f0}from"@cline/shared";function ZG($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function q2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function Cq($){let W=$.result;if(!W)return;return{textPreview:ZG(W.text,_q),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function n9($){return $?.toISOString()}function y3($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:ZG($.message,Dq),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:n9($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:n9($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:n9($.heartbeatAt),lastProgressAt:n9($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:Cq($)}}function Pq($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var g8=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function QG($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...M2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:z2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function m8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=M2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;QG({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function M2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(_0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:f0(eH),execute:async(X)=>{let Y=g(eH,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(QG({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(M2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return g(tH,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(_0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:f0(sH),execute:async(X)=>{let Y=g(sH,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),g(tH,{agentId:Y.agentId,status:"stopped"})}})),J.push(_0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:f0($G),execute:async(X)=>{return g($G,X),g(wq,$.runtime.getSnapshot())}})),J.push(_0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:f0(WG),execute:async(X)=>{let Y=g(WG,X);switch(Y.action){case"create":{let V=new Set(fq.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:q2(Y.title,"title"),description:q2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return g(d4,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return g(d4,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(q2(Y.taskId,"taskId"),$.requesterId);return g(d4,{action:"claim",taskId:V.id,status:V.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let V=$.runtime.completeTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.summary,"summary"));return g(d4,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.reason,"reason"));return g(d4,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(_0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:f0(aH),execute:async(X)=>{let Y=g(aH,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return g(S3,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return g(S3,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>g(S3,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(_0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:f0(mH),execute:async(X)=>{let Y=g(mH,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return g(Oq,{runId:V.id,status:V.status})}})),J.push(_0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:f0(lH),execute:async(X)=>g(b3.array(),$.runtime.listRuns(g(lH,X)).map(y3))})),J.push(_0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:f0(xH),timeoutMs:Uq,execute:async(X)=>{let Y=g(xH,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return Pq(H),g(b3,y3(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return g(b3.array(),V.map(y3))}})),J.push(_0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:f0(oH),execute:async(X)=>{let Y=g(oH,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return g(Eq,{id:V.id,toAgentId:V.toAgentId})}})),J.push(_0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:f0(gH),execute:async(X)=>{let Y=g(gH,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return g(Lq,{delivered:V.length})}})),J.push(_0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:f0(iH),execute:async(X)=>{let Y=g(iH,X);return g(Mq.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(_0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:f0(pH),execute:async(X)=>{let Y=g(pH,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return g(Rq,{id:V.id})}})),J.push(_0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:f0(vH),execute:async(X)=>{if(g(vH,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),g(Tq,{status:"cleaned"})}})),J.push(_0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:f0(cH),execute:async(X)=>{let Y=g(cH,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return g(zq,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(_0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:f0(IH),execute:async(X)=>{let Y=g(IH,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return g(rH,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:f0(nH),execute:async(X)=>{let Y=g(nH,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return g(rH,{fragmentId:V.id,status:V.status})}})),J.push(_0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:f0(uH),execute:async(X)=>{let Y=g(uH,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return g(qq,{outcomeId:V.id,status:V.status})}})),J.push(_0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:f0(dH),execute:async(X)=>{return g(dH,X),g(Nq.array(),$.runtime.listOutcomes())}})),J}function a9($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function JG($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var Sq=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:C$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...g8]}],bq={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function yq($){return $==="plan"||$==="yolo"?$:"act"}function XG($){let W=yq($.mode),Z=a0[i1({mode:W})],Q=k8($.providerId??"",$.modelId??"",W,h8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function jG($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=XG(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=bq[$];return Q?Z[Q]===!0:!1}function hq($,W){if($.id==="editor"){let{flags:Z}=XG(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:jG($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:jG($.id,W)}}function R2($={}){return Sq.map((W)=>hq(W,$))}function o9($={}){return R2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function s9($){if(!$.enabled)return new Set;let W=R2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function l4($,W={}){return R2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function t9($,W={}){return l4($,W)}function N2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J={...y8(W),...Z??{}};return q$({...Q,executors:J})}import{mkdirSync as vq,writeFileSync as cq}from"node:fs";import{dirname as uq}from"node:path";import{normalizeUserInput as dq,stripModeNotices as lq}from"@cline/shared";import{nanoid as pq}from"nanoid";var VG={};w(VG,{sanitizeSessionToken:()=>E2,parseTeamTaskSubSessionId:()=>c8,parseSubSessionId:()=>r4,makeTeamTaskSubSessionId:()=>p4,makeSubSessionId:()=>v8,deriveSubsessionStatus:()=>i4});import{nanoid as xq}from"nanoid";function E2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function v8($,W){let Z=E2($),Q=E2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function p4($,W){let Z=E2($),Q=E2(W);return`${Z}__teamtask__${Q}__${xq(6)}`}function c8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function r4($){if(c8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function i4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var GG={};w(GG,{isTerminalSessionStatus:()=>HG,isNonTerminalSessionStatus:()=>K0,SessionSource:()=>F0,SESSION_STATUSES:()=>n4,NON_TERMINAL_SESSION_STATUSES:()=>BG});import{SESSION_STATUS_VALUES as gq}from"@cline/shared";var n4=gq,BG=["idle","running","pending"];function HG($){return!BG.includes($)}function K0($){return!HG($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var mq=Z0.enum(n4),x0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:mq,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function KG($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function k3($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function FG($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function a1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function h3($,W){let Z={...$};Z.id=a1(Z.id)??pq();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:a1(Q?.id)??a1(Z.modelId)??a1(W?.id),provider:a1(Q?.provider)??a1(Z.providerId)??a1(W?.provider),family:a1(Q?.family)??a1(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function e9($){return $.map((W)=>h3(W))}function $Z($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return h3(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...h3(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function a4($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var rq=120;function w2($){let W=$?.trim();return W?W.slice(0,rq):void 0}function I3($){let W=lq(dq($??"")).trim();if(!W)return;return w2(W.split(`
203
- `)[0]?.trim())}function P$($){if(!$)return;let W={...$},Z=w2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function o4($){let W=P$($.metadata)??{},Z=$.title!==void 0?w2($.title):I3($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function x3($){let W=c8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=r4($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function g3($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:e9($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function AG($,W,Z){vq(uq($),{recursive:!0}),cq($,`${JSON.stringify(g3({updatedAt:W,context:Z,messages:[]}),null,2)}
204
- `,"utf8")}function UG($,W){return x0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function DG($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}D0();var _G={};w(_G,{summarizeUsageFromMessages:()=>d8,sumUsageTotals:()=>s4,getCurrentContextSize:()=>m3,createInitialAccumulatedUsage:()=>q0,accumulateUsageTotals:()=>L0});function q0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function L0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function s4($){let W=q0();for(let Z of $)W=L0(W,Z);return W}function u8($){return typeof $==="number"&&Number.isFinite($)?$:0}function d8($){let W=q0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=L0(W,{inputTokens:u8(Q.inputTokens),outputTokens:u8(Q.outputTokens),cacheReadTokens:u8(Q.cacheReadTokens),cacheWriteTokens:u8(Q.cacheWriteTokens),totalCost:u8(Q.cost)})}return W}function m3($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=u8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function iq($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function v3($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function o1($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function nq($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function aq($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function c3($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=v3(W),G=o1({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=iq(W.input);if(K)eW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(_8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))$9(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")W4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=nq(W);if(B){j.turnPrimaryUsage=L0(j.turnPrimaryUsage??q0(),K);let A=L0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),D8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),sW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=aq({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,L0(D.get(A)??q0(),K))}let F=L0(j.turnPrimaryUsage??q0(),s4(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,L0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:FG(W),ts:Date.now()}})}function s1($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as jN}from"@cline/llms";import{hasRuntimeConfigExtension as XN}from"@cline/shared";var l8="0.0.64";var t4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:l8,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};U1();import{existsSync as XZ,readFileSync as IM,statSync as xM}from"node:fs";import{basename as gM,dirname as JZ,join as YZ,resolve as jZ}from"node:path";import{discoverPluginModulePaths as mM,resolveConfiguredPluginModulePaths as mG,resolvePluginConfigSearchPaths as vM,SKILLS_CONFIG_DIRECTORY_NAME as cM}from"@cline/shared/storage";import{resolve as UM}from"node:path";import{normalizePluginManifest as DM}from"@cline/shared";import{existsSync as E0,readFileSync as r8}from"node:fs";import{builtinModules as oq,createRequire as p3}from"node:module";import{dirname as S$,extname as $5,isAbsolute as sq,resolve as o}from"node:path";import{fileURLToPath as OG}from"node:url";import{PLUGIN_FILE_EXTENSIONS as tq}from"@cline/shared";var TG=S$(OG(import.meta.url)),eq=p3(import.meta.url),$M=o(TG,"..","..","..","..",".."),u3=QM($M),WM=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],r3=new Set(oq.flatMap(($)=>[$,$.replace(/^node:/,"")])),e4=new Set(tq),ZM=["development","node","import","require","default"];function QM($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(E0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!E0(j))continue;try{let X=JSON.parse(r8(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(E0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=JM(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function JM($,W){let Z=i3(W);if(!Z)return null;let Q=zG($,Z);for(let J of Q)if(E0(J))return J;return null}function i3($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of ZM){let J=i3(Z[Q],W);if(J)return J}return null}function zG($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function jM($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function WZ($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function p8($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function XM($){let W=p8($);if($===W)return".";return`.${$.slice(W.length)}`}function qG($){return p8($).startsWith("@cline/")}function d3($,W){let Z=p8(W),Q=S$($);while(!0){let J=o(Q,"node_modules",Z);if(E0(J)||E0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function LG($){return l3($)!==null}function l3($){try{return eq.resolve($)}catch{}return YM($)}function YM($){let W=p8($),Z=MG(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(r8(Q,"utf8")),j=XM($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=i3(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...zG(Z,Y).filter((H)=>H!==V)];for(let H of B)if(E0(H))return H;return null}catch{return null}}function VM(){let $=[TG],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(S$(S$(W)));let Z=process.execPath?.trim();if(Z)$.push(S$(Z));return[...new Set($.map((Q)=>o(Q)))]}function BM($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(E0(Q))try{if(JSON.parse(r8(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(E0(J))return S$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function MG($){for(let W of VM()){let Z=BM(W,$);if(Z)return Z}return null}function HM($){let Z=S$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(E0(J))try{let X=JSON.parse(r8(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function RG($,W){let Z=W.startsWith("file:")?OG(W):sq(W)?W:o(S$($),W);if(E0(Z)&&e4.has($5(Z)))return Z;for(let Q of e4){let J=`${Z}${Q}`;if(E0(J))return J}for(let Q of e4){let J=o(Z,`index${Q}`);if(E0(J))return J}return null}function NG($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function GM($){return $5($)!==".ts"}function EG($,W,Z=new Set){if(Z.has($)||!E0($))return;if(Z.add($),!e4.has($5($)))return;let Q=r8($,"utf8"),J=GM($);for(let j of NG(Q)){if(j.startsWith("node:")||r3.has(j))continue;if(WZ(j)){if(!J)continue;if(Object.hasOwn(u3,j)||Object.hasOwn(u3,p8(j))||d3($,j)||qG(j)&&LG(j)||W&&LG(j))continue;throw Error(`Cannot find module '${p8(j)}'`)}let X=RG($,j);if(X)EG(X,W,Z)}}function wG($,W=new Set,Z=new Set){if(W.has($)||!E0($))return Z;if(W.add($),!e4.has($5($)))return Z;let Q=r8($,"utf8");for(let J of NG(Q)){if(Z.add(J),WZ(J))continue;let j=RG($,J);if(j)wG(j,W,Z)}return Z}function KM($,W){let Z=p3($),Q={},J=wG($),j=new Set(WM);for(let[X,Y]of Object.entries(u3)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(WZ(X)&&(qG(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||d3($,X))continue;let Y=l3(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!WZ(X)||Object.hasOwn(Q,X)||d3($,X)||X.startsWith("node:")||r3.has(X))continue;let Y=l3(X);if(Y)Q[X]=Y}return Q}function FM($){let W=$5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var C2;function AM(){if(C2!==void 0)return C2;let $=MG("jiti");if(!$)return C2=null,null;let W=o($,"dist","babel.cjs");if(!E0(W))return C2=null,null;try{let Q=p3(W)(W);C2=typeof Q==="function"?Q:null}catch{C2=null}return C2}async function CG($,W={}){let Z=!HM($);EG($,Z);let Q=KM($,Z),J=jM(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>FM(G)).map(([G])=>G),V=AM(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...r3],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function PG($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function SG($){return typeof $==="object"&&$!==null}function n3($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function _M($,W){if(!SG($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!n3($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!n3($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!n3($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function fM($,W){if(!SG($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);_M($,W)}async function W5($,W={}){let Z=UM(W.cwd??process.cwd(),$),Q=await CG(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];fM(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:DM(X.manifest),setup:V}}async function ZZ($,W={}){return(await P2($,W)).plugins}async function P2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await W5(Y,W);if(!PG(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as t3}from"node:fs";import{createRequire as gG}from"node:module";import{dirname as QZ,join as n8}from"node:path";import{fileURLToPath as qM}from"node:url";var IG={};w(IG,{resolveSubprocessRuntimeExecutable:()=>a3,buildSubprocessSandboxCommand:()=>kG,SubprocessSandbox:()=>i8,CLINE_JS_RUNTIME_PATH_ENV:()=>hG});import{spawn as LM}from"node:child_process";import{basename as OM}from"node:path";import{augmentNodeCommandForDebug as TM,withResolvedClineBuildEnv as zM}from"@cline/shared";function bG($){if($ instanceof Error)return $;return Error(String($))}var hG="CLINE_JS_RUNTIME_PATH";function yG($){let W=$?.trim();if(!W)return!1;let Z=OM(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function a3($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[hG]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(yG(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&yG(j))return j}return"node"}function kG($,W={}){let Z=a3({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return TM([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class i8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=kG($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=LM(W[0]??a3(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:zM(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${bG(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${bG(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function MM($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Z5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function RM(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function NM(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=gG($).resolve(`${RM()}/package.json`),Q=n8(QZ(Z),"extensions","plugin-sandbox-bootstrap.js");return t3(Q)?Q:void 0}catch{return}}function EM(){let $=process.execPath?.trim();if(!$)return;let W=n8(QZ(QZ($)),"extensions","plugin-sandbox-bootstrap.js");return t3(W)?W:void 0}function wM(){let $=QZ(qM(import.meta.url)),W=gG(import.meta.url),Z=[n8($,"plugin-sandbox-bootstrap.js"),n8($,"extensions","plugin-sandbox-bootstrap.js"),n8($,"agents","plugin-sandbox-bootstrap.js"),NM(),EM()];for(let j of Z.filter((X)=>typeof X==="string"))if(t3(j))return{file:j};let Q=n8($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
205
- `)}}var o3=wM();function s3($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function a8($){let W=new i8({name:"plugin-sandbox",..."file"in o3?{bootstrapFile:o3.file}:{bootstrapScript:o3.script},onEvent:$.onEvent}),Z=s3($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=s3($.hookTimeoutMs,3000),J=s3($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(MM);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{CM(F,W,G,J,Y),PM(F,W,G,J,Y),SM(F,W,G,J,Y),yM(F,W,G,J,Y),bM(F,G)}};return K.hooks=kM(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function CM($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!Z5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function PM($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!Z5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function SM($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!Z5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function bM($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function yM($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return xG(Y)?Y:X}catch(Y){if(!Z5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return xG(V)?V:X}}})}function xG($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function hM($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!Z5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function kM($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=hM($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var $J="package.json",uM="package";function Q5($){return vM($)}function J5($){return mM($)}function dM($){try{return XZ($)&&xM($).isDirectory()}catch{return!1}}function WJ($){let W=[],Z=new Set;for(let Q of $){let J=jZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function vG($){let W=WJ($);return c9(W)}function cG($){return Q5($).flatMap((W)=>J5(W)).filter((W)=>XZ(W))}function lM($,W){let Z=[];for(let Q of $)try{Z.push(...mG([Q],W))}catch{}return Z}function e3($){return typeof $==="object"&&$!==null}function pM($){try{let W=JSON.parse(IM(YZ($,$J),"utf8"));if(!e3(W)||!e3(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!e3(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function uG($,W){let Z=jZ(W);return pM($).some((Q)=>jZ($,Q)===Z)}function rM($,W){return gM($)===uM&&XZ(YZ(JZ($),$J))&&uG(JZ($),W)}function iM($){let W=jZ($),Z=[],Q=JZ(W);while(!0){if(rM(Q,W)){Z.push(Q);break}if(XZ(YZ(Q,$J))){if(uG(Q,W))Z.push(Q);break}let J=JZ(Q);if(J===Q)break;Q=J}return WJ(Z)}function t1($={}){let W=$.cwd??process.cwd(),Z=cG($.workspacePath),Q=mG($.pluginPaths??[],W);return vG([...Q,...Z])}function nM($={}){let W=$.cwd??process.cwd(),Z=cG($.workspacePath),Q=lM($.pluginPaths??[],W);return vG([...Q,...Z])}function e1($){let W=[];for(let Z of $)for(let Q of iM(Z)){let J=YZ(Q,cM);if(dM(J))W.push(J)}return WJ(W)}function dG($={}){return e1(nM($))}async function o8($={}){let W=t1($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await P2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await a8({pluginPaths:W,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as aM}from"node:child_process";import{promisify as oM}from"node:util";var sM=oM(aM);function ZJ($,W){$?.log(W,{severity:"warn"})}function tM($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function S2($,W){let Z=await sM("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function QJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await S2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
206
- `).filter(Boolean);await Promise.allSettled(J.map((j)=>S2($,["update-ref","-d",j])))}catch{}}async function lG($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>S2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function eM($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function pG($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await S2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await S2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){ZJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await S2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return ZJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await S2($.cwd,["update-ref",V,Y])}catch(B){ZJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=tM(Y);if(V?.latest.ref===X.ref)return;let B=eM(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as VR}from"node:child_process";import{appendFileSync as BR,readFileSync as HR}from"node:fs";import{join as GR}from"node:path";import{augmentNodeCommandForDebug as nG,withResolvedClineBuildEnv as XJ}from"@cline/shared";import{ensureHookLogDir as rG}from"@cline/shared/storage";function s8($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as $R,readdirSync as WR}from"node:fs";import{basename as ZR,extname as QR,join as JR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as VZ,resolveHooksConfigSearchPaths as jR}from"@cline/shared/storage";function j5($){return jR($)}var t8;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(t8||={});var X5={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},XR=new Map(Object.values(t8).map(($)=>[$.toLowerCase(),$])),YR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function Y5($){let W=QR($).toLowerCase();if(!YR.has(W))return;let Z=ZR($,W).trim().toLowerCase();return XR.get(Z)}function b$($){let W=[],Z=new Set,Q=j5($).filter((J)=>$R(J));for(let J of Q)try{for(let j of WR(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=Y5(j.name);if(!X)continue;let Y=JR(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:X5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function HZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function BZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function KR($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
207
- `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function FR($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function JJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function w0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function AR($){let W=$.trim();if(!W)return{};let Q=W.split(`
208
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function UR($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function aG($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await iG($,W)}catch(Z){let Q=fR(W.command,process.platform,Z);if(!Q)throw Z;return await iG($,{...W,command:Q})}}async function iG($,W){let Z=nG(W.command,{env:W.env,debugRole:"hook"}),Q=VR(Z[0],Z.slice(1),{cwd:W.cwd,env:XJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await UR(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=AR(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,j])}function DR($){try{let Z=HR($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function _R($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function fR($,W=process.platform,Z){if(W!=="win32"||!_R(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function oG($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return oG(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function LR($){let W=DR($);if(W&&W.length>0)return[...oG(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return nG(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function OR($){let W={};for(let Z of b$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(LR(Z.path)),W[Q]=J}return W}async function TR($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await aG($.payload,{command:Z,cwd:$.cwd,env:XJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){BZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){BZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=KR(W,FR(J?.parsedJson))}catch(J){BZ($.logger,`hook command failed: ${Q}`,J)}}return W}function b2($){for(let W of $.commands){let Z=W.join(" ");aG($.payload,{command:W,cwd:$.cwd,env:XJ(process.env),detached:!0}).catch((Q)=>{BZ($.logger,`hook command failed: ${Z}`,Q)})}}function y$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function jJ($,W){return{...y$($.snapshot),userMessage:W}}function sG($){return{...y$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function tG($){return{...y$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function eG($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function zR($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function e8($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
209
- `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??GR(rG(),"hooks.jsonl");rG(X),BR(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=jJ(Q,"");Z({...w0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=sG(Q);Z({...w0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:HZ(J.call.input)}});return},afterTool:async(Q)=>{let J=tG(Q);Z({...w0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:HZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=y$(Q);if(J.status==="completed"){Z({...w0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||JJ(J.error?.message)){Z({...w0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...w0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=jJ({snapshot:Q.snapshot},eG(Q.message.content));Z({...w0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function V5($){let W=OR($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;b2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...w0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...w0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return TR({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...w0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:HZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:HZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(JJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)b2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...w0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(y$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(jJ({snapshot:G.snapshot},eG(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(sG(G));return zR(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(tG(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...y$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||JJ(A.error?.message)){await B({...y$(F),reason:A.error?.message});return}if(A.error)await V({...y$(F),iteration:A.iterations,error:A.error})}}return H}function $6($){return s8("core.hook_config_files",V5($))}function y2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function h2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:y2(W,"beforeRun"),afterRun:y2(W,"afterRun"),beforeModel:y2(W,"beforeModel"),afterModel:y2(W,"afterModel"),beforeTool:y2(W,"beforeTool"),afterTool:y2(W,"afterTool"),onEvent:y2(W,"onEvent")}}var $K={};w($K,{normalizeRuntimeCapabilities:()=>C0});function C0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var BK={};w(BK,{toProviderConfig:()=>s0,emptyStoredProviderSettings:()=>I$,StoredProviderSettingsSchema:()=>J6,StoredProviderSettingsEntrySchema:()=>yZ,ProviderSettingsSchemaTyped:()=>Q6});import{z as k$}from"zod";var VK={};w(VK,{toProviderConfig:()=>s0,safeParseSettings:()=>bZ,safeCreateProviderConfig:()=>DJ,parseSettings:()=>SZ,normalizeProviderId:()=>Z6,isBuiltInProviderId:()=>AJ,createProviderConfig:()=>UJ,SapSettingsSchema:()=>wZ,ReasoningSettingsSchema:()=>MZ,ProviderSettingsSchema:()=>h$,ProviderProtocolSchema:()=>TZ,ProviderIdSchema:()=>F5,ProviderClientSchema:()=>zZ,OcaSettingsSchema:()=>CZ,ModelCatalogSettingsSchema:()=>PZ,GcpSettingsSchema:()=>NZ,BUILT_IN_PROVIDER_IDS:()=>FJ,BUILT_IN_PROVIDER:()=>K5,AzureSettingsSchema:()=>EZ,AwsSettingsSchema:()=>RZ,AuthSettingsSchema:()=>qZ});import*as o0 from"@cline/llms";import{z as E}from"zod";var YK={};w(YK,{resolveProviderConfig:()=>G5,getProviderConfig:()=>OZ,getLiveModelsCatalog:()=>W6,clearPublicModelsCatalogCache:()=>pR,clearPrivateModelsCatalogCache:()=>KJ,clearLiveModelsCatalogCache:()=>GJ,OPENAI_COMPATIBLE_PROVIDERS:()=>H5,DEFAULT_MODELS_CATALOG_URL:()=>DZ});import*as $0 from"@cline/llms";function YJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function qR($,W){let Z=YJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=YJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=YJ(j.models??j);if(Y.length>0)return Y}return[]}async function GZ($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return qR(await Z.json(),W)}function WK($){return $.replace(/\/+$/,"")}function KZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=WK(X.pathname),B=WK(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function MR($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function RR($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var NR=Object.values($0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:MR($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),QK=Object.fromEntries(NR.map(($)=>[$.id,$]));function ER($){return QK[$]}function wR(){return Object.fromEntries(Object.entries(QK).filter(([,$])=>RR($)))}function JK($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var DZ="https://models.dev/api.json",CR=600000,jK=300000,PR=5000,UZ=new Map,B5=new Map,VJ=new Map,FZ=new Map;async function SR(){return $0.getGeneratedProviderModels()}async function bR($,W={},Z={},Q={},J={},j={}){if($==="litellm")return $0.sortModelsByReleaseDate(Q);let X=await SR(),Y=$0.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((G)=>X[G]??{}));if(Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl))return $0.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return $0.sortModelsByReleaseDate({...W,...$0.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let H=$0.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return $0.sortModelsByReleaseDate({...$0.preferCanonicalModelIds(H,$0.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return $0.sortModelsByReleaseDate({...H,...j})}function yR($,W){let Z=$0.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function _Z($){let W=$?.trim();return W&&W.length>0?W:""}function HJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function hR($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function kR($,W){return`${$}:${_Z(W.baseUrl)}:${hR(HJ(W)??"")}`}async function fZ($,W,Z=PR){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function k2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function LZ($,W){let Z=["streaming","tools"];return k2(Z,"images",Boolean(W.supportsImages)),k2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),k2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function IR($,W){let Z=await fZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=LZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function ZK($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function xR($,W){let Z=await fZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=LZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function gR($,W){let Q=`${(_Z($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await fZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];k2(F,"tools",H.includes("tools")),k2(F,"reasoning",H.includes("reasoning")),k2(F,"temperature",G.includes("temperature")),k2(F,"images",K.includes("image"));let A={input:ZK(V.pricing?.prompt),output:ZK(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function mR($){let W=_Z($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function vR($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function cR($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function uR($,W){let Z=mR($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of vR(Z))for(let[X,Y]of J)try{let V=await fZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),D=K.litellm_params?.model?.trim()||F;if(!D)continue;let U=K.model_info,f=LZ(D,{name:F??D,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[D]=f,F)G[F]={...f,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await cR(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var XK={baseten:IR,hicap:xR,litellm:uR,poolside:gR},BJ=new Map,AZ=new Map;function dR($,W){return`${$}:${_Z(W.baseUrl)}`}async function lR($,W,Z){let Q=$0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=KZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??jK,X=dR($,Z),Y=Date.now(),V=BJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=AZ.get(X);if(B)return B;let H=GZ(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,LZ(F,{name:F})]));return BJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{AZ.delete(X)});return AZ.set(X,H),H}function pR(){BJ.clear(),AZ.clear()}async function rR($,W){let Z=HJ(W);if(!Z)return{};let Q=XK[$];if(!Q)return{};return Q(W,Z)}function iR($,W,Z){if(!Z)return!1;if(!XK[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(HJ(Z))}async function nR($,W,Z){let Q=W?.cacheTtlMs??jK,J=kR($,Z),j=Date.now(),X=VJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=FZ.get(J);if(Y)return Y;let V=rR($,Z).then((B)=>{return VJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{FZ.delete(J)});return FZ.set(J,V),V}async function aR($){return $0.fetchLiveProviderModels($,globalThis.fetch)}async function W6($={}){let W=$.url??DZ,Z=$.cacheTtlMs??CR,Q=Date.now(),J=UZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=B5.get(W);if(j)return j;let X=aR(W).then((Y)=>{return UZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{B5.delete(W)});return B5.set(W,X),X}function GJ($){if($){UZ.delete($),B5.delete($);return}UZ.clear(),B5.clear()}function KJ(){VJ.clear(),FZ.clear()}function oR($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:JK(Z.capabilities)}]))}var H5=oR(wR());function OZ($){let W=ER($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:JK(W.capabilities)}}async function G5($,W,Z){let Q=OZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await W6(W):void 0,j=J?yR($,J):{},X=Z&&iR($,W,Z)?await nR($,W,Z):{},V=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await lR($,W,V).catch(()=>({})):{},H=await bR($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var K5=o0.BUILT_IN_PROVIDER,FJ=o0.BUILT_IN_PROVIDER_IDS,AJ=o0.isBuiltInProviderId,Z6=o0.normalizeProviderId,F5=E.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),TZ=E.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),zZ=E.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),qZ=E.object({apiKey:E.string().optional(),accessToken:E.string().optional(),refreshToken:E.string().optional(),expiresAt:E.number().int().positive().optional(),accountId:E.string().optional(),organizationId:E.string().optional(),organizationName:E.string().optional(),memberId:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()}),sR=E.enum(["none","low","medium","high","xhigh"]),MZ=E.object({enabled:E.boolean().optional(),effort:sR.optional(),budgetTokens:E.number().int().positive().optional()}),RZ=E.object({accessKey:E.string().optional(),secretKey:E.string().optional(),sessionToken:E.string().optional(),region:E.string().optional(),profile:E.string().optional(),authentication:E.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:E.boolean().optional(),useCrossRegionInference:E.boolean().optional(),useGlobalInference:E.boolean().optional(),endpoint:E.string().url().optional(),customModelBaseId:E.string().optional()}),NZ=E.object({projectId:E.string().optional(),region:E.string().optional()}),EZ=E.object({apiVersion:E.string().optional(),useIdentity:E.boolean().optional()}),wZ=E.object({clientId:E.string().optional(),clientSecret:E.string().optional(),tokenUrl:E.string().url().optional(),resourceGroup:E.string().optional(),deploymentId:E.string().optional(),useOrchestrationMode:E.boolean().optional(),api:E.enum(["orchestration","foundation-models"]).optional(),defaultSettings:E.record(E.string(),E.unknown()).optional()}),CZ=E.object({mode:E.enum(["internal","external"]).optional(),usePromptCache:E.boolean().optional()}),PZ=E.object({loadLatestOnInit:E.boolean().optional(),loadPrivateOnAuth:E.boolean().optional(),url:E.string().url().optional(),cacheTtlMs:E.number().int().positive().optional(),failOnError:E.boolean().optional()}),h$=E.object({provider:F5,apiKey:E.string().optional(),auth:qZ.optional(),model:E.string().optional(),protocol:TZ.optional(),client:zZ.optional(),routingProviderId:F5.optional(),maxTokens:E.number().int().positive().optional(),contextWindow:E.number().int().positive().optional(),baseUrl:E.string().url().optional(),headers:E.record(E.string(),E.string()).optional(),timeout:E.number().int().positive().optional(),reasoning:MZ.optional(),aws:RZ.optional(),gcp:NZ.optional(),azure:EZ.optional(),sap:wZ.optional(),oca:CZ.optional(),region:E.string().optional(),apiLine:E.enum(["china","international"]).optional(),capabilities:E.array(E.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:PZ.optional()});function SZ($){return h$.parse($)}function bZ($){return h$.safeParse($)}function tR($){return $.protocol==="openai-responses"||$.client==="openai"}function s0($,W={}){let Z=$.provider,Q=Z6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=H5[Q],V=Object.assign({},...o0.resolveProviderModelCatalogKeys(Q).map((D)=>o0.getGeneratedModelsForProvider(D))),B=Object.keys(V)[0],H=q8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?U9:D9:Y?.baseUrl),K=$.routingProviderId??(tR($)&&Q!==K5.OPENAI_NATIVE?K5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??Y?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(A).filter(([D,U])=>U!==void 0))}function UJ($){let W=SZ($);return s0(W)}function DJ($){let W=bZ($);if(W.success)return{success:!0,config:s0(W.data)};return{success:!1,error:W.error}}var Q6=h$;var yZ=k$.object({settings:h$,updatedAt:k$.string().datetime(),tokenSource:k$.enum(["manual","oauth","migration"]).default("manual")}),J6=k$.object({version:k$.literal(1),lastUsedProvider:k$.string().min(1).optional(),providers:k$.record(k$.string(),yZ)});function I$(){return{version:1,providers:{}}}U1();var _K={};w(_K,{InMemoryWorkspaceManager:()=>X6});import{upsertWorkspaceInfo as WN,WorkspaceManifestSchema as OJ}from"@cline/shared";var DK={};w(DK,{withSessionGitMetadata:()=>kZ,readSessionGitMetadata:()=>AK,readGitWorkspaceState:()=>fJ,normalizeWorkspacePath:()=>N1,hasCurrentSessionGitMetadata:()=>_J,generateWorkspaceInfoWithDiagnostics:()=>A5,generateWorkspaceInfo:()=>j6,buildWorkspaceMetadataWithInfo:()=>LJ,buildWorkspaceMetadata:()=>U5});import{basename as eR,resolve as $N}from"node:path";import{performance as HK}from"node:perf_hooks";import{processWorkspaceInfo as KK}from"@cline/shared";import FK from"simple-git";function AK($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function kZ($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function _J($,W){let Z=AK($);return Z.url===W.url&&Z.branch===W.branch}function UK($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function N1($){return $N($)}async function j6($){return(await A5($)).info}function GK($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function hZ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function A5($){let W=N1($),Z={rootPath:W,hint:eR(W)},Q={},J;try{let j=FK({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=UK(Y);if(B)Q.url=B}}catch(Y){J??=hZ(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!GK(Y))J??=hZ(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!GK(Y))J??=hZ(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:hZ(j)}}}async function fJ($){try{let W=FK({baseDir:N1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=UK(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function U5($){let W=await j6($);return KK(W)}async function LJ($){let W=HK.now(),Z=await A5($),Q=HK.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:KK(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}class X6{manifest;listeners=new Set;constructor($){this.manifest=OJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await j6($);return this.manifest=WN(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=N1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=OJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=OJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=N1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}D0();import{createHash as ZN}from"node:crypto";var fK=new Set,LK=new Set;function QN($){return ZN("sha256").update($).digest("hex")}function JN($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function OK($){if(!$.telemetry)return;let W=QN($.rootPath),Z=$.rootCount??1;if(!fK.has(W))fK.add(W),iW($.telemetry,{root_count:Z,vcs_types:JN($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!LK.has(W)){LK.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",nW($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function YN($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function VN($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(YN).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function BN($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function TK($,W){return XN($,W)}function HN($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function GN($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=jN({providerId:$.providerId,sessionId:W,source:Z,defaultSource:F0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:l8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:BN($,X?.reasoning),modelCatalog:Y},G={...s0(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function zK($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,D=s1(W.config),{modelCatalogDefaults:U,userInstructionService:f,configExtensions:_,onTeamRestored:R,...T}=K??{},O=Object.keys(T).length>0?T:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:N,durationMs:p,vcsType:x,initError:P}=await LJ(D),r=O?.extensionContext,d={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??O?.logger,telemetry:r?.telemetry??O?.telemetry??J};OK({telemetry:d.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:x,durationMs:p,initError:P,featureFlagEnabled:!0});let x1=$6({cwd:W.config.cwd,workspacePath:D,rootSessionId:Z,logger:O?.logger,workspaceInfo:L}),W2=KG(O?.hooks)?void 0:e8({rootSessionId:Z,workspacePath:D,workspaceInfo:L}),A$=h2([O?.hooks,W2]),I0;if(TK(_,"plugins"))try{I0=await o8({pluginPaths:O?.pluginPaths,workspacePath:D,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:d.session,client:d.client,user:d.user,logger:d.logger,telemetry:d.telemetry,automation:d.automation}),VN(I0.failures,I0.warnings,O?.logger)}catch(e6){let U8=e6 instanceof Error?e6.message:String(e6);O?.logger?.log?.(`plugin loading failed; continuing without plugins (${U8})`)}let O1=k3(x1?[x1]:void 0,k3(O?.extensions,u9(I0?.extensions))),A8=TK(_,"plugins")?e1(I0?.pluginPaths??[]):void 0,V0={...W.config,...O??{},sessionId:Z,hooks:A$,extensions:O1,extensionContext:d,telemetry:d.telemetry},l0=GN(V0,Z,W.source,Q,U,Y),V1=h2([V0.hooks,V0.checkpoint?.enabled===!0?pG({cwd:V0.cwd,sessionId:Z,logger:V0.logger,createCheckpoint:V0.checkpoint?.createCheckpoint,initialRunCount:HN(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),y={...V0,providerConfig:l0,workspaceMetadata:C,hooks:V1},B1=W.toolPolicies??V0.toolPolicies??X,k=C0(j,W.capabilities),W0=k?.requestToolApproval,T0=k?.toolExecutors,M0=H?.(y),pW=new X6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:y,providerConfig:l0,workspaceMetadata:C,workspaceInfo:L,gitState:N,extensions:O1,hooks:V1,toolPolicies:B1,requestToolApproval:W0,pluginSandboxShutdown:I0?.shutdown,runtimeBuilderInput:{config:y,hooks:V1,extensions:O1,onTeamEvent:B,createSpawnTool:G,onTeamRestored:R,onSubAgentEvent:M0?.onSubAgentEvent,onSubAgentStart:M0?.onSubAgentStart,onSubAgentEnd:M0?.onSubAgentEnd,userInstructionService:f,pluginSkillDirectories:A8,configExtensions:_,toolExecutors:T0,toolPolicies:B1,workspaceManager:pW,logger:y.logger,telemetry:y.telemetry,requestToolApproval:W0}}}import{existsSync as IZ,mkdirSync as KN,readdirSync as FN,rmdirSync as AN,rmSync as UN,unlinkSync as DN}from"node:fs";import{dirname as qK,join as D5}from"node:path";function X0(){return new Date().toISOString()}function _5($){if(!$||!IZ($))return;try{DN($)}catch{}}function _N($){let W=c8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=r4($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class TJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return D5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!IZ(W))KN(W,{recursive:!0});return W}sessionMessagesPath($){return D5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return D5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return D5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!IZ(W)){W=qK(W);continue}try{if(FN(W).length>0)break;AN(W)}catch{break}W=qK(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!IZ($))return;try{UN($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=_N($),j=this.sessionArtifactsDir(Q);return{messagesPath:D5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as fN}from"@cline/shared/storage";D0();function MK($,W,Z,Q,J){if(Z)oW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else aW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});LN($.telemetry,{workspacePath:Q})}function LN($,W){let Z=fN("Hooks"),Q=b$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())X9($,j,X.global,X.workspace)}function RK($,W){for(let Z of W.mentions)J9($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)Z9($,"file",Z.length);for(let Z of W.ignoredMentions)Q9($,"file","not_found",Z)}var qf={};w(qf,{ProviderSettingsManager:()=>X1});import{chmodSync as Rf,existsSync as IY,mkdirSync as Hv,readFileSync as Gv,renameSync as Kv,rmSync as Fv,writeFileSync as Av}from"node:fs";import{basename as Nf,dirname as xY}from"node:path";import{resolveProviderSettingsPath as Uv}from"@cline/shared/storage";var q={};w(q,{writeModelsFileSync:()=>IW,writeHubDiscovery:()=>GQ,writeGlobalSettings:()=>M1,withHubStartupLock:()=>KQ,verifyHubConnection:()=>w1,updateMcpSettingsFileSync:()=>D1,updateMcpSettingsFile:()=>F6,updateMcpServerOAuthStateAsync:()=>k5,updateMcpServerOAuthState:()=>v2,updateLocalProvider:()=>_7,uninstallPlugin:()=>wW,uninstallMarketplaceSkill:()=>Z7,uninstallMarketplacePlugin:()=>Q7,uninstallMarketplaceMcpServerFromSettings:()=>$7,uninstallMarketplaceEntry:()=>oX,truncateNotificationBody:()=>fW,truncateCommandOutput:()=>G2,toggleDisabledTool:()=>v9,toTeamProgressLifecycleEvent:()=>w6,toProviderConfig:()=>s0,toHubStatusUrl:()=>Kj,toHubHealthUrl:()=>FQ,toHookConfigFileName:()=>Y5,syncStoredProviderRegistration:()=>BY,syncPluginMcpServersToSettings:()=>NW,summarizeUsageFromMessages:()=>d8,stripUtf8Bom:()=>Yv,stopLocalHubServerGracefully:()=>Mj,startLocalOAuthServer:()=>G1,startHubWebSocketServer:()=>V8,startHubServer:()=>$_,startClineDeviceAuth:()=>v7,splitCoreSessionConfig:()=>u5,spawnDetachedHubServerWithRetry:()=>O6,spawnDetachedHubServer:()=>fj,setTelemetryOptOutGlobally:()=>ZH,setSdkLogger:()=>y7,setMcpServerDisabled:()=>g2,setDisabledTools:()=>_3,setDisabledPlugin:()=>HH,setCompactionStrategyGlobally:()=>XH,setAutoUpdateEnabledGlobally:()=>JH,sendHubCommand:()=>iU,sdkDebug:()=>s,saveProviderOAuthCredentials:()=>j2,saveLocalProviderSettings:()=>DY,saveLocalProviderOAuthCredentials:()=>OY,sanitizeSessionToken:()=>E2,safeParseSettings:()=>bZ,safeCreateProviderConfig:()=>DJ,runSubprocessEvent:()=>k6,runHook:()=>x6,reviveTeamStateDates:()=>a9,restartLocalHubIfIdleAfterStartupTimeout:()=>fQ,resolveWorkspaceHubOwnerContext:()=>TA,resolveWorkflowsConfigSearchPaths:()=>w5,resolveSkillsConfigSearchPaths:()=>N5,resolveSharedHubOwnerContext:()=>v0,resolveSessionBackend:()=>pj,resolveRulesConfigSearchPaths:()=>E5,resolveProviderConfig:()=>G5,resolveProviderApiKeyFromSettings:()=>i7,resolveProductionHubOwnerContext:()=>Q1,resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>Q5,resolveModelsRegistryPath:()=>I1,resolveMcpServerRegistrations:()=>t0,resolveMarketplaceMcpServerName:()=>PW,resolveLocalClineAuthToken:()=>zY,resolveHubUrl:()=>WX,resolveHubOwnerContext:()=>J$,resolveHubEndpointOptions:()=>Z1,resolveHubBuildId:()=>HQ,resolveHooksConfigSearchPaths:()=>j5,resolveDisabledToolNames:()=>R1,resolveDisabledPluginPaths:()=>g4,resolveDefaultMcpSettingsPath:()=>Q0,resolveDefaultHubPort:()=>L6,resolveDefaultHubPathname:()=>_j,resolveDefaultHubHost:()=>Dj,resolveCoreSelectedToolIds:()=>s9,resolveCoreDistinctId:()=>c0,resolveCompatibleLocalHubUrl:()=>WW,resolveClineDir:()=>_A,resolveClineDataDir:()=>n2,resolveAndLoadAgentPlugins:()=>o8,resolveAgentPluginPaths:()=>t1,requestHubShutdown:()=>$W,requestDesktopToolApproval:()=>hX,removePluginMcpServersFromSettings:()=>EW,rememberRecoverableLocalHubUrl:()=>l$,registerRemoteConfigSessionBlobUpload:()=>pQ,registerMcpServersFromSettingsFile:()=>c2,registerDisposable:()=>jv,refreshProviderModelsFromSource:()=>_Y,refreshOpenAICodexToken:()=>A9,refreshOcaToken:()=>f9,refreshClineToken:()=>K9,readSessionCheckpointHistory:()=>Q8,readRemoteConfigSessionBlobUploadMetadata:()=>RX,readModelsFileSync:()=>s6,readHubDiscovery:()=>O0,readGlobalSettings:()=>N0,readCompactionStrategyGlobally:()=>jH,readBearerToken:()=>gQ,projectSessionCompactionState:()=>X2,probeHubServer:()=>j$,probeHubConnection:()=>rU,prewarmFileIndex:()=>y9,prewarmDetachedHubServer:()=>UQ,prepareRemoteConfigCoreIntegration:()=>EX,parseWorkflowConfigFromMarkdown:()=>R5,parseUserCommandEnvelope:()=>Jv,parseSkillConfigFromMarkdown:()=>q5,parseSettings:()=>SZ,parseSessionCompactionState:()=>K1,parseRuleConfigFromMarkdown:()=>M5,parsePluginSource:()=>K7,parseMcpInstallArgs:()=>RW,parseHookEventPayload:()=>I6,parseConfiguredAgentConfig:()=>jW,normalizeWorkspacePath:()=>N1,normalizeUserInput:()=>Qv,normalizeSdkError:()=>Zv,normalizeRuntimeCapabilities:()=>C0,normalizeProviderId:()=>Z6,normalizeOAuthProvider:()=>fY,normalizeHubWebSocketUrl:()=>p$,noopBasicLogger:()=>Wv,migrateLegacyProviderSettings:()=>cW,mergeRulesForSystemPrompt:()=>G6,mergeAgentHooks:()=>h2,marketplaceEntryKey:()=>aX,markLocalProviderEnabled:()=>FY,makeTeamTaskSubSessionId:()=>p4,makeSubSessionId:()=>v8,loginOpenAICodex:()=>j4,loginOcaOAuth:()=>B4,loginLocalProvider:()=>LY,loginClineOAuth:()=>Q4,loginAndSaveProviderOAuthCredentials:()=>G4,loginAndSaveLocalProviderOAuthCredentials:()=>TY,loadOpenTelemetryAdapter:()=>wm,loadMcpSettingsFile:()=>x2,loadLlmsConfigFromFile:()=>yY,loadConfiguredAgentConfigs:()=>R6,loadAgentPluginsFromPathsWithDiagnostics:()=>P2,loadAgentPluginsFromPaths:()=>ZZ,loadAgentPluginFromPath:()=>W5,listSessionHistoryFromBackend:()=>Vj,listPluginToolsWithDiagnostics:()=>QQ,listPluginTools:()=>g5,listMcpServerOAuthStatuses:()=>I5,listLocalProviders:()=>AY,listHookConfigFiles:()=>b$,isToolDisabledGlobally:()=>YH,isTelemetryOptedOutGlobally:()=>m9,isSessionNotFoundError:()=>Q$,isRuleEnabled:()=>rZ,isPluginDisabledGlobally:()=>BH,isOfficialPluginSlug:()=>G7,isOAuthProvider:()=>J2,isMarketplaceSkillInstalled:()=>W7,isLocalHubOrigin:()=>MX,isLocalHubHostName:()=>mQ,isHubReconnectableTransportError:()=>zj,isHubCommandTimeoutError:()=>_Q,isDiscoveryFilePresent:()=>LA,isClinePassLimitMessage:()=>um,isClinePassLimitError:()=>cm,isClineOrgIndividualInferenceSubscriptionMessage:()=>vm,isClineOrgIndividualInferenceSubscriptionError:()=>mm,isClineNotSubscribedMessage:()=>gm,isClineNotSubscribedError:()=>xm,isClineAccountActionRequest:()=>xZ,isBuiltInProviderId:()=>AJ,isAutoUpdateEnabledGlobally:()=>QH,installPlugin:()=>ZY,installMcpServer:()=>kX,identifyAccount:()=>H1,hashSecret:()=>R0,hasMcpSettingsFile:()=>W$,getValidOpenAICodexCredentials:()=>X4,getValidOcaCredentials:()=>H4,getValidClineCredentials:()=>J4,getProviderOAuthCredentialsFromSettings:()=>K4,getProviderConfigFields:()=>qY,getProviderConfig:()=>OZ,getProviderAuthStorageId:()=>r7,getProviderAuthHandler:()=>H0,getPersistedProviderApiKey:()=>q8,getMcpServerOAuthState:()=>m2,getMarketplaceSkillCandidates:()=>SW,getLocalProviderModels:()=>UY,getLiveModelsCatalog:()=>W6,getGlobalMarketplaceSkillPaths:()=>bW,getFileIndex:()=>r1,getCurrentContextSize:()=>m3,getCoreHeadlessToolNames:()=>l4,getCoreDefaultEnabledToolIds:()=>o9,getCoreBuiltinToolCatalog:()=>R2,getCoreAcpToolNames:()=>t9,getClinePassSubscriptionUrl:()=>Im,getClineOrgIndividualInferenceSubscriptionMessage:()=>km,getClineNotSubscribedMessage:()=>hm,getClineDefaultSystemPrompt:()=>dm,generateWorkspaceInfoWithDiagnostics:()=>A5,generateWorkspaceInfo:()=>j6,formatRulesForSystemPrompt:()=>H6,formatProviderOAuthApiKey:()=>n7,formatDisplayUserInput:()=>$v,findInstalledGlobalMarketplaceSkillName:()=>yW,findCheckpointForRun:()=>y6,filterExtensionToolRegistrations:()=>u9,filterDisabledTools:()=>n1,filterDisabledPluginPaths:()=>c9,fetchClineRecommendedModels:()=>SY,extractClinePassLimitMessage:()=>ym,executeClineAccountAction:()=>gZ,ensureHubWebSocketServer:()=>vQ,ensureHubServer:()=>W_,ensureDetachedHubServer:()=>EA,ensureCustomProvidersLoadedSync:()=>mW,ensureCustomProvidersLoaded:()=>vW,ensureCompatibleLocalHubUrl:()=>s2,enrichPromptWithMentions:()=>b8,emptyWorkspaceManifest:()=>sm,emptyStoredProviderSettings:()=>I$,discoverPluginModulePaths:()=>J5,disablePluginMcpServersInSettings:()=>mX,deriveSubsessionStatus:()=>i4,deleteLocalProvider:()=>f7,defineLlmsConfig:()=>bY,createWorkflowsConfigDefinition:()=>S5,createUserInstructionConfigService:()=>x$,createToolPoliciesWithPreset:()=>k9,createTool:()=>om,createTeamName:()=>nQ,createSubprocessHooks:()=>CQ,createSpawnAgentTool:()=>C$,createSkillsConfigDefinition:()=>C5,createShellTool:()=>b4,createShellExecutor:()=>K2,createSessionHost:()=>S6,createSessionCompactionState:()=>M8,createRuntimeHost:()=>S6,createRulesConfigDefinition:()=>P5,createRemoteConfigSessionMessagesArtifactUploader:()=>NX,createProviderConfig:()=>UJ,createOpenTelemetryTelemetryService:()=>DW,createOAuthClientCallbacks:()=>Y6,createMcpTools:()=>_6,createLocalHubScheduleRuntimeHandlers:()=>cQ,createLlmsSdk:()=>kY,createInitialAccumulatedUsage:()=>q0,createInMemoryHubOwnerContext:()=>fA,createHubServerUrl:()=>_1,createHubAuthToken:()=>BQ,createHookConfigFileHooks:()=>V5,createHookConfigFileExtension:()=>$6,createHookAuditHooks:()=>e8,createEditorExecutor:()=>D2,createDisabledMcpToolPolicy:()=>x5,createDisabledMcpToolPolicies:()=>ZQ,createDelegatedAgentConfigProvider:()=>E$,createDelegatedAgent:()=>w$,createDefaultToolsWithPreset:()=>I9,createDefaultTools:()=>q$,createDefaultShellExecutor:()=>I4,createDefaultMcpServerClientFactory:()=>U6,createDefaultExecutors:()=>y8,createCoreSettingsService:()=>d2,createCoreSessionSnapshot:()=>C1,createContributionRegistry:()=>am,createContextCompactionPrepareTurn:()=>T4,createConfiguredTelemetryService:()=>H$,createConfiguredTelemetryHandle:()=>n$,createConfiguredAgentTools:()=>N6,createCompactionStateAwarePrepareTurn:()=>z4,createClineTelemetryServiceMetadata:()=>nm,createClineTelemetryServiceConfig:()=>im,createCheckpointComparePlan:()=>RQ,createBuiltinTools:()=>N2,createApplyPatchExecutor:()=>U2,createAgentTeamsTools:()=>M2,createAgentRuntime:()=>Bv,createAgentHooksExtension:()=>s8,connectToHub:()=>bQ,computePatchChanges:()=>P8,completeClineDeviceAuth:()=>c7,compareCheckpointToWorkspace:()=>KW,collectPluginMcpOAuthCandidates:()=>F7,clearPrivateModelsCatalogCache:()=>KJ,clearLiveModelsCatalogCache:()=>GJ,clearHubDiscovery:()=>m0,captureWorkspacePathResolved:()=>QV,captureWorkspaceInitialized:()=>iW,captureWorkspaceInitError:()=>nW,captureToolUsage:()=>_8,captureTokenUsage:()=>sW,captureTaskRestarted:()=>oW,captureTaskCreated:()=>aW,captureTaskCompleted:()=>$4,captureSubagentExecution:()=>Z4,captureSkillUsed:()=>eW,captureSdkError:()=>rm,captureProviderConfigured:()=>JV,captureProviderApiError:()=>W4,captureModeSwitch:()=>tW,captureMistakeLimitReached:()=>W9,captureMentionUsed:()=>Z9,captureMentionSearchResults:()=>J9,captureMentionFailed:()=>Q9,captureHookDiscovery:()=>X9,captureExtensionActivated:()=>ZV,captureDiffEditFailure:()=>$9,captureConversationTurnEvent:()=>D8,captureCompactionSkipped:()=>V9,captureCompactionExecuted:()=>Y9,captureAuthSucceeded:()=>v1,captureAuthStarted:()=>m1,captureAuthLoggedOut:()=>D$,captureAuthFailed:()=>c1,captureAgentUnexpectedReasoningTokens:()=>WV,captureAgentTeamCreated:()=>j9,captureAgentCreated:()=>_$,buildWorkspaceMetadata:()=>U5,buildTeamProgressSummary:()=>E6,buildSdkErrorProperties:()=>lm,buildRemoteConfigSessionBlobUploadMetadata:()=>dQ,buildMcpInstallTransport:()=>aQ,buildDelegatedAgentConfig:()=>z2,buildConnectionUpdate:()=>R3,buildConfiguredAgentToolName:()=>XW,buildConfiguredAgentToolDescriptors:()=>YW,buildCheckpointWorkspaceDiff:()=>NQ,bootstrapAgentTeams:()=>m8,authorizeMcpServerOAuth:()=>tZ,addLocalProvider:()=>KY,accumulateUsageTotals:()=>L0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>z5,UnifiedConfigFileWatcher:()=>I2,ToolPresets:()=>a0,TelemetryService:()=>v6,TelemetryLoggerSink:()=>UW,TEAM_TOOL_NAMES:()=>g8,SubprocessSandbox:()=>i8,StructuredCommandInputSchema:()=>B2,StoredProviderSettingsSchema:()=>J6,StoredProviderSettingsEntrySchema:()=>yZ,SqliteTeamStore:()=>B8,SqliteSessionStore:()=>S1,SessionVersioningService:()=>s$,SessionVersioningError:()=>d0,SessionSource:()=>F0,SessionNotFoundError:()=>Z$,SapSettingsSchema:()=>wZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>T5,SESSION_STATUSES:()=>n4,SESSION_NOT_FOUND_ERROR_CODE:()=>l2,SDK_ERROR_TELEMETRY_EVENT:()=>Xv,RpcClineAccountService:()=>L5,RemoteRuntimeHost:()=>q6,ReasoningSettingsSchema:()=>MZ,RULES_CONFIG_DIRECTORY_NAME:()=>pZ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>lQ,ProviderSettingsSchema:()=>h$,ProviderSettingsManager:()=>X1,ProviderProtocolSchema:()=>TZ,ProviderIdSchema:()=>F5,ProviderClientSchema:()=>zZ,PatchActionType:()=>A2,OpenTelemetryProvider:()=>c6,OcaSettingsSchema:()=>CZ,OPENAI_COMPATIBLE_PROVIDERS:()=>H5,NodeHubClient:()=>f1,NoOpFeatureFlagsProvider:()=>Z8,NativeHubTransportAdapter:()=>qW,ModelCatalogSettingsSchema:()=>PZ,McpSettingsUpdateSkippedError:()=>K6,McpSettingsMutatorPurityError:()=>g$,McpSettingsLockTimeoutError:()=>m$,MAX_COMMAND_OUTPUT_CHARS:()=>d1,LocalRuntimeHost:()=>h1,Llms:()=>Cm,InMemoryWorkspaceManager:()=>X6,InMemoryMcpManager:()=>u2,HubUIClient:()=>JX,HubTransportError:()=>y0,HubSessionClient:()=>QX,HubServerTransport:()=>d6,HubScheduleService:()=>m6,HubScheduleCommandService:()=>g6,HubRuntimeHost:()=>X$,HubCommandError:()=>T6,HookEventPayloadSchema:()=>wQ,HookEventNameSchema:()=>EQ,HookConfigFileName:()=>t8,HOOK_CONFIG_FILE_EVENT_MAP:()=>X5,HOOKS_CONFIG_DIRECTORY_NAME:()=>VZ,GlobalSettingsSchema:()=>x4,GcpSettingsSchema:()=>NZ,FileTeamPersistenceStore:()=>T7,FeatureFlagsService:()=>W8,FeatureFlagDefaultValue:()=>em,FEATURE_FLAGS:()=>tm,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>E7,DefaultToolNames:()=>z0,DefaultRuntimeBuilder:()=>r6,DefaultLlmsSdk:()=>dW,DEFAULT_MODELS_CATALOG_URL:()=>DZ,DEFAULT_HUB_PORT:()=>Aj,DEFAULT_HUB_PATHNAME:()=>Uj,DEFAULT_HUB_HOST:()=>Fj,CoreSettingsService:()=>v$,CoreSessionService:()=>y1,ContributionRegistry:()=>pm,CommandExitError:()=>l1,ClinePassLimitError:()=>bm,ClineOrgIndividualInferenceSubscriptionError:()=>Sm,ClineNotSubscribedError:()=>Pm,ClineCore:()=>FW,ClineAccountService:()=>f5,ChatViewStateSchema:()=>CY,ChatSummarySchema:()=>N7,ChatSessionStatusSchema:()=>q7,ChatSessionConfigSchema:()=>z7,ChatMessageSchema:()=>R7,ChatMessageRoleSchema:()=>M7,CORE_TELEMETRY_EVENTS:()=>v,CORE_BUILD_VERSION:()=>uW,BrowserWebSocketHubAdapter:()=>zW,BUILT_IN_PROVIDER_IDS:()=>FJ,BUILT_IN_PROVIDER:()=>K5,AzureSettingsSchema:()=>EZ,AwsSettingsSchema:()=>RZ,AuthSettingsSchema:()=>qZ,AgentTeamsRuntime:()=>$8,AgentTeam:()=>P6,Agent:()=>Vv,ALL_DEFAULT_TOOL_NAMES:()=>L$});M(q,Y20);import*as Cm from"@cline/llms";import{ClineNotSubscribedError as Pm,ClineOrgIndividualInferenceSubscriptionError as Sm,ClinePassLimitError as bm,extractClinePassLimitMessage as ym,getClineNotSubscribedMessage as hm,getClineOrgIndividualInferenceSubscriptionMessage as km,getClinePassSubscriptionUrl as Im,isClineNotSubscribedError as xm,isClineNotSubscribedMessage as gm,isClineOrgIndividualInferenceSubscriptionError as mm,isClineOrgIndividualInferenceSubscriptionMessage as vm,isClinePassLimitError as cm,isClinePassLimitMessage as um}from"@cline/llms";import{buildClineSystemPrompt as dm,buildSdkErrorProperties as lm,ContributionRegistry as pm,captureSdkError as rm,createClineTelemetryServiceConfig as im,createClineTelemetryServiceMetadata as nm,createContributionRegistry as am,createTool as om,emptyWorkspaceManifest as sm,FEATURE_FLAGS as tm,FeatureFlagDefaultValue as em,formatDisplayUserInput as $v,noopBasicLogger as Wv,normalizeSdkError as Zv,normalizeUserInput as Qv,parseUserCommandEnvelope as Jv,registerDisposable as jv,SDK_ERROR_TELEMETRY_EVENT as Xv,stripUtf8Bom as Yv}from"@cline/shared";import"@cline/shared/storage";var EK={};w(EK,{isClineAccountActionRequest:()=>xZ,executeClineAccountAction:()=>gZ,RpcClineAccountService:()=>L5,ClineAccountService:()=>f5});function ON($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function NK($,W,Z){let Q=ON(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class f5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(NK(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(NK(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function xZ($){return $.action==="clineAccount"}async function gZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class L5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var wK={};w(wK,{createOAuthClientCallbacks:()=>Y6});function Y6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var xU={};w(xU,{ClineCore:()=>FW});function CK($){if($===!0)return{};if(!$)return;return $}function PK($){if($==="user")return"global";return $}class zJ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function SK($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Z6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:qN(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:zN(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function mZ($){let W=TN($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function TN($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function zN($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function qN($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var kF={};w(kF,{createCoreSettingsService:()=>d2,CoreSettingsService:()=>v$});import{existsSync as v5,readFileSync as Hw}from"node:fs";import{basename as mJ,dirname as wF,extname as Gw,isAbsolute as SF,join as Kw,relative as bF,resolve as CF}from"node:path";var rK={};w(rK,{resolveWorkflowsConfigSearchPaths:()=>w5,resolveSkillsConfigSearchPaths:()=>N5,resolveRulesConfigSearchPaths:()=>E5,parseWorkflowConfigFromMarkdown:()=>R5,parseSkillConfigFromMarkdown:()=>q5,parseRuleConfigFromMarkdown:()=>M5,createWorkflowsConfigDefinition:()=>S5,createUserInstructionConfigService:()=>x$,createSkillsConfigDefinition:()=>C5,createRulesConfigDefinition:()=>P5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>z5,UnifiedConfigFileWatcher:()=>I2,SKILLS_CONFIG_DIRECTORY_NAME:()=>T5,RULES_CONFIG_DIRECTORY_NAME:()=>pZ});import{createHash as MN}from"node:crypto";import{watch as RN}from"node:fs";import{readdir as NN,readFile as EN}from"node:fs/promises";import{join as wN}from"node:path";function CN($){return MN("sha1").update($).digest("hex")}function hK($){return Boolean($&&typeof $==="object"&&"code"in $)}function bK($){return hK($)&&$.code==="ENOENT"}function yK($){return hK($)&&($.code==="EACCES"||$.code==="EPERM")}class I2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=RN(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!bK(Z)&&!yK(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await EN(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:CN(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await NN($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:wN($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(bK(W)||yK(W))return[];throw W}}}import{readdir as MJ,readFile as PN,stat as qJ}from"node:fs/promises";import{basename as $$,dirname as SN,extname as cZ,join as g0,resolve as O5}from"node:path";import{stripUtf8Bom as bN}from"@cline/shared";import{AGENTS_RULES_FILE_NAME as kK,RULES_CONFIG_DIRECTORY_NAME as pZ,resolveGlobalAgentsRulesPath as yN,resolveRulesConfigSearchPaths as hN,resolveSkillsConfigSearchPaths as kN,resolveWorkflowsConfigSearchPaths as IN,SKILLS_CONFIG_DIRECTORY_NAME as T5,WORKFLOWS_CONFIG_DIRECTORY_NAME as z5}from"@cline/shared/storage";import xN from"yaml";var vZ="SKILL.md",gN="managed.json",mN=new Set([".md",".markdown",".txt"]);function RJ($){return $.trim().toLowerCase()}function V6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function uZ($){return mN.has(cZ($).toLowerCase())}function IK($){let W=[],Z=new Set;for(let Q of $){let J=O5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function vN($){let W=[...$?.directories??N5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...dG({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return IK(W)}async function NJ($){try{let W=await MJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=g0($,Q.name),j=g0(J,gN);try{let X=await PN(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(V6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(V6(W))return[];throw W}}function EJ($){let W=bN($),Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=W.match(Z);if(!Q)return{data:{},body:W,hadFrontmatter:!1};let[,J,j]=Q;try{let X=xN.parse(J);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:j,hadFrontmatter:!0}}catch(X){let Y=X instanceof Error?X.message:String(X);return{data:{},body:W,hadFrontmatter:!0,parseError:Y}}}function dZ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function B6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function cN($,W){if($$($.filePath).toLowerCase()!==kK.toLowerCase())return $$($.filePath,cZ($.filePath));if(W&&O5($.filePath)===O5(W,kK))return"Workspace AGENTS.md";if(O5($.filePath)===O5(yN()))return"Global AGENTS.md";return $$($.filePath,cZ($.filePath))}function q5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=dZ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:dZ(Z.description,"description",!1),disabled:B6(Z.disabled,"disabled")??(B6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function M5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=dZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:B6(Z.disabled,"disabled")??(B6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function R5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=dZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:B6(Z.disabled,"disabled")??(B6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function N5($){return kN($)}function E5($){return hN($)}function w5($){return IN($)}async function xK($){if($$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>xK(g0(Q,T5))))).flat()}try{let W=await MJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===vZ){Z.push({directoryPath:$,fileName:Q.name,filePath:g0($,Q.name)});continue}let J=g0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await qJ(J).then((X)=>X.isDirectory()).catch((X)=>{if(V6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:vZ,filePath:g0(J,vZ)})}return Z}catch(W){if(V6(W))return[];throw W}}async function lZ($){if($$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>lZ(g0(Q,"rules.md"))))).flat()}try{if((await qJ($)).isFile())return[{directoryPath:SN($),fileName:$$($),filePath:$}]}catch(W){if(!V6(W))throw W}try{let Z=(await MJ($,{withFileTypes:!0})).filter((J)=>J.isFile()&&uZ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:g0($,J.name)})),Q=g0($,"AGENTS.md");try{if((await qJ(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(V6(W))return[];throw W}}async function uN($){if($$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>lZ(g0(Q,z5))))).flat()}return lZ($)}function C5($){let W=vN($),Z=$?.workspacePath?g0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?IK([...W,Z]):W,discoverFiles:xK,includeFile:(Q)=>Q===vZ,parseFile:(Q)=>q5(Q.content,$$(Q.directoryPath)),resolveId:(Q)=>RJ(Q.name)}}function P5($){let W=$?.directories??E5($?.workspacePath),Z=$?.workspacePath?g0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:lZ,includeFile:(Q,J)=>Q===".clinerules"||uZ(Q)||uZ(J),parseFile:(Q)=>M5(Q.content,cN(Q,$?.workspacePath)),resolveId:(Q)=>RJ(Q.name)}}function S5($){let W=$?.directories??w5($?.workspacePath),Z=$?.workspacePath?g0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:uN,includeFile:(Q)=>uZ(Q),parseFile:(Q)=>R5(Q.content,$$(Q.filePath,cZ(Q.filePath))),resolveId:(Q)=>RJ(Q.name)}}function gK($){let W=[C5($?.skills),P5($?.rules),S5($?.workflows)];return new I2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as mK}from"@cline/shared";function dN($,W){if($.description?.trim())return mK($.description,".");if(W==="workflow")return;return mK($.instructions,".")}function lN($){return $.disabled!==!0}function vK($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>lN(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:dN(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function b5($){let W=new Map;for(let Z of[...vK($,"workflow"),...vK($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function cK($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=b5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}var dK={};w(dK,{mergeRulesForSystemPrompt:()=>G6,loadRulesForSystemPromptFromWatcher:()=>wJ,listEnabledRulesFromWatcher:()=>uK,isRuleEnabled:()=>rZ,formatRulesForSystemPrompt:()=>H6});function rZ($){return $.disabled!==!0}function H6($){if($.length===0)return"";return`
201
+ ${Q}`;return Z||Q}function Hq($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function Gq($,W){return $.filter((Z)=>Hq(Z.name,W))}function Kq($,W){return a1(Gq($,W))}function Fq($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return{};return{beforeRun:async(Z)=>{for(let Q of W){let J=await Q.beforeRun?.(Z);if(J?.stop)return J}return},afterRun:async(Z)=>{for(let Q of W)await Q.afterRun?.(Z)},beforeModel:async(Z)=>{let Q=Z.request,J;for(let j of W){let X=await j.beforeModel?.({...Z,request:Q});if(!X)continue;if(X.stop)return X;J={...J,...X,options:bH(J?.options,X.options)},Q={...Q,...X.messages?{messages:X.messages}:{},...X.tools?{tools:X.tools}:{},...X.options?{options:bH(Q.options,X.options)}:{}}}return J},afterModel:async(Z)=>{for(let Q of W){let J=await Q.afterModel?.(Z);if(J?.stop)return J}return},beforeTool:async(Z)=>{let Q=Z.input,J;for(let j of W){let X=await j.beforeTool?.({...Z,input:Q});if(!X)continue;if(X.stop||X.skip)return X;if(J={...J,...X},Object.hasOwn(X,"input"))Q=X.input}return J},afterTool:async(Z)=>{let Q=Z.result,J;for(let j of W){let X=await j.afterTool?.({...Z,result:Q});if(!X)continue;if(X.stop)return X;if(J={...J,...X},X.result)Q=X.result}return J},onEvent:async(Z)=>{for(let Q of W)await Q.onEvent?.(Z)}}}class E${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new C3;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,W={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=W.logger??$.logger,this.telemetry=W.telemetry??$.telemetry,this.createAgentRuntimeImpl=W.createAgentRuntimeImpl??Jq,this.conversation=new M3($.initialMessages),this.messageBuilder=new T3(NH()),this.contributionRegistry=jq({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Z=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new w3({maxConsecutiveMistakes:Z,onLimitReached:$.onConsecutiveMistakeLimitReached,onLimitTelemetry:(j)=>{W9(this.telemetry,{ulid:this.config.sessionId??this.conversation.getConversationId(),model:this.config.modelId,provider:this.config.providerId,reason:j.reason,consecutiveMistakes:j.consecutiveMistakes,maxConsecutiveMistakes:j.maxConsecutiveMistakes,agentId:this.agentId,conversationId:this.conversation.getConversationId(),parentAgentId:this.parentAgentId,isSubagent:Boolean(this.parentAgentId)})},emit:(j)=>this.emitLegacyEvent(j),log:(j,X,Y)=>Aq(this.logger,j,X,Y),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,X)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let J=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new E3(J)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let W=new Set(this.config.tools.map((Q)=>Q.name)),Z=[...this.config.tools];for(let Q of $)if(!W.has(Q.name))Z.push(Q),W.add(Q.name);this.config={...this.config,tools:Z}}updateConnection($){let W=T2($),Z={...this.config};if(W.providerId!==void 0)Z.providerId=W.providerId;if(W.modelId!==void 0)Z.modelId=W.modelId;if(W.apiKey!==void 0)Z.apiKey=W.apiKey;if(W.baseUrl!==void 0)Z.baseUrl=W.baseUrl;if(W.headers!==void 0)Z.headers=W.headers;if(W.providerConfig!==void 0)Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"reasoningEffort"))Z.reasoningEffort=W.reasoningEffort??void 0;if(Object.hasOwn(W,"thinkingBudgetTokens"))Z.thinkingBudgetTokens=W.thinkingBudgetTokens??void 0;if(Object.hasOwn(W,"thinking")){if(Z.thinking=W.thinking??void 0,W.thinking===!1||W.thinking===null)Z.reasoningEffort=void 0,Z.thinkingBudgetTokens=void 0}this.config=Z}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.messageBuilder.resetConversationState(),this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let W=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=W,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(W)}async shutdown($,W){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,W,Z){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!1})}continue($,W,Z){return this.executeRun({userMessage:$,userImages:W,userFiles:Z,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let W of this.contributionRegistry.getRegisteredRules()){let Z=await Vq(W);if(Z)$.push(Z)}return Bq(this.config.systemPrompt,$)}executeRun($){let W;return W=this.executeRunWithAuthRetry($).finally(()=>{if(this.activeRunPromise===W)this.activeRunPromise=null}),this.activeRunPromise=W,W}async executeRunWithAuthRetry($){let W=await this.executeRunInternal($);if(W.finishReason!=="error"||!this.config.onAuthError||!Xq(W.text))return W;if(!await this.config.onAuthError().catch(()=>!1))return W;let Q=await this.executeRunInternal({isContinue:!0});return JV(this.telemetry,this.config.providerId,{recovered:Q.finishReason!=="error"}),Q}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let W=new Date,Z=$.userMessage;if(Z!==void 0){let _=await Dq(Z,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:_})}let Q=await this.composeSystemPrompt(),J=_H(this.config,this.logger,this.telemetry),j=new Map;for(let _ of this.contributionRegistry.getRegisteredTools())j.set(_.name,_);let X=Kq([...j.values()],this.config.toolPolicies),Y=new Map;for(let _ of X)Y.set(_.name,_);for(let _ of this.config.tools)Y.set(_.name,_);let V=this.conversation.getConversationId(),B=yH(this.config),H=Array.from(Y.values()),G=d9(this.conversation.getMessages()),K=wH({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:B?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[R9]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(B,H),initialMessages:G,systemPrompt:Q}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((_)=>{this.handleRuntimeEvent(_)}),D,U;try{if($.isContinue)D=await F.continue(void 0);else D=await F.run("")}catch(_){U=_ instanceof Error?_:Error(String(_))}finally{A();try{await this.activeTrackerWork}catch(_){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:_})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(D&&D.messages.length>0){let _=x8(D.messages);this.conversation.replaceMessages(_)}let f=new Date;try{return this.buildLegacyResult({runResult:D,thrownError:U,startedAt:W,endedAt:f})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=Fq([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((W)=>W.hooks)]);return{...$,beforeModel:async(W)=>{let Z=await $.beforeModel?.(W);if(Z?.stop)return Z;let Q=Z?.messages??W.request.messages,J=await this.prepareMessagesForModelRequest(Q);return{...Z,messages:J}}}}createRuntimePrepareTurn($,W){let Z=this.config.prepareTurn;if(!Z)return;return async(Q)=>{let J=x8(Q.messages),j=await this.prepareProviderMessagesForApi(J),X=await Z({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:J,apiMessages:j,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:W,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!X)return;return{...X.messages?{messages:d9(X.messages)}:{},...X.systemPrompt!==void 0?{systemPrompt:X.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let W=await this.prepareProviderMessagesForApi(l9($));return d9(W)}async prepareProviderMessagesForApi($){let W=$,Z=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of Z)W=await Q.build(W);return this.messageBuilder.buildForApi(W)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let W=this.toolStartedAt.get($.toolCall.toolCallId),Z=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let J=$.message.content.find((V)=>V.type==="tool-result"),j=J?.type==="tool-result"&&J.isError===!0,X=j?Yq(J?.type==="tool-result"?J.output:void 0):void 0,Y={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:J?.type==="tool-result"?J.output:void 0,error:X,durationMs:W===void 0?0:Z.getTime()-W.getTime(),startedAt:W??Z,endedAt:Z};if(this.currentRunToolCalls.push(Y),j){if(this.currentTurnFailedTools+=1,X)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${X}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let W=this.currentTurnFailedTools,Z=this.currentTurnSuccessfulTools;if(W>0&&Z===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${W} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(Z>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let W of this.eventAdapter.translate($))this.emitLegacyEvent(W)}syncConversationFromRuntimeMessage($,W){if($.length>0){this.conversation.replaceMessages(x8($));return}if(W.length===0)return;let Z=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),Q=x8(W).filter((J)=>!J.id||!Z.has(J.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let W of this.listeners)try{W($)}catch(Z){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Z})}}inspectLoopForToolCall($,W,Z){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:W});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:Z,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let W=await this.mistakeTracker.record($);if(W.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]}),this.activeRuntime?.abort(W.reason??W.message)})}buildLegacyResult($){let{runResult:W,thrownError:Z,startedAt:Q,endedAt:J}=$,j=J.getTime()-Q.getTime(),X=Z?"error":Uq(W),Y=(W?.status==="failed"?W.error?.message:void 0)||W?.outputText||"",V=W?{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens>0?W.usage.cacheReadTokens:void 0,cacheWriteTokens:W.usage.cacheWriteTokens>0?W.usage.cacheWriteTokens:void 0,totalCost:W.usage.totalCost}:this.currentRunUsage,B=W?x8(W.messages):this.conversation.getMessages(),H=yH(this.config);if(Z)throw Z;return{text:Y,usage:V,messages:B,toolCalls:this.currentRunToolCalls,iterations:W?.iterations??0,finishReason:X,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Q,endedAt:J,durationMs:j}}}function Aq($,W,Z,Q){if(!$)return;if(W==="debug"){$.debug(Z,Q);return}if(W==="error"&&$.error){$.error(Z,Q);return}let J=W==="warn"?"warn":W==="error"?"error":"info";$.log(Z,{...Q,severity:J})}function Uq($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function Dq($,W,Z,Q){let{buildInitialUserContent:J}=await Promise.resolve().then(() => SH);return J($,W,Z,Q)}function yH($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let W=f3($);if(W?.[$.modelId])return W[$.modelId];return}import{buildClineSystemPrompt as hH}from"@cline/shared";function kH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return hH({ide:W.clineIdeName?.trim()||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,rules:`# Team Teammate Role
202
+ ${Z}`,platform:W.clinePlatform,metadata:W.workspaceMetadata})}function IH($,W){let Z=$.trim();if(W.providerId.toLowerCase()!=="cline")return Z;return hH({ide:W.clineIdeName||"Terminal",workspaceRoot:W.cwd?.trim()||"/",providerId:W.providerId,overridePrompt:Z,metadata:W.workspaceMetadata,platform:W.clinePlatform})}function w$($){let W={...$};return{getRuntimeConfig:()=>W,getConnectionConfig:()=>({providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,onAuthError:W.onAuthError,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature}),updateConnectionDefaults:(Z)=>{W={...W,...Z}}}}function z2($){let W=$.configProvider.getRuntimeConfig(),Z=$.kind==="teammate"?kH($.prompt,W):IH($.prompt,W);return{...$.configProvider.getConnectionConfig(),systemPrompt:Z,tools:$.tools,maxIterations:$.maxIterations??W.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:W.hooks,extensions:W.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:W.logger,role:$.role}}function C$($){let W=z2($),Z=new E$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);return Z}var Lq=P3.object({systemPrompt:P3.string().describe("System prompt defining the sub-agent's behavior"),task:P3.string().describe("Task for the sub-agent to complete")});function P$($){return _q({name:"spawn_agent",description:"Spawn a sub-agent with a custom system prompt for specialized tasks. Use when delegating work that benefits from focused expertise.",inputSchema:fq(Lq),execute:async(W,Z)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(W,Z):$.subAgentTools??[],J=C$({kind:"subagent",prompt:W.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:Z.agentId,abortSignal:Z.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=J.getAgentId(),X=J.getConversationId(),Y=Z.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:X,parentAgentId:Y,input:W})}catch{}try{let V=await J.run(W.task),B={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,result:B,agentResult:V})}catch{}return B}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:X,parentAgentId:Y,input:W,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as D0,TEAM_AWAIT_TIMEOUT_MS as Oq,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as Tq,TEAM_RUN_TEXT_PREVIEW_LIMIT as zq,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as qq,TeamAttachOutcomeFragmentInputSchema as xH,TeamAwaitRunsInputSchema as gH,TeamBroadcastInputSchema as mH,TeamBroadcastToolResultSchema as Mq,TeamCancelRunInputSchema as vH,TeamCancelRunToolResultSchema as Rq,TeamCleanupInputSchema as cH,TeamCleanupToolResultSchema as Nq,TeamCreateOutcomeInputSchema as uH,TeamCreateOutcomeToolResultSchema as Eq,TeamFinalizeOutcomeInputSchema as dH,TeamFinalizeOutcomeToolResultSchema as wq,TeamListOutcomesInputSchema as lH,TeamListRunsInputSchema as pH,TeamMailboxMessageToolResultSchema as Cq,TeamMissionLogInputSchema as rH,TeamMissionLogToolResultSchema as Pq,TeamOutcomeFragmentToolResultSchema as iH,TeamOutcomeToolResultSchema as Sq,TeamReadMailboxInputSchema as nH,TeamReviewOutcomeFragmentInputSchema as aH,TeamRunTaskInputSchema as oH,TeamRunTaskToolResultSchema as S3,TeamRunToolSummarySchema as b3,TeamSendMessageInputSchema as sH,TeamSendMessageToolResultSchema as bq,TeamShutdownTeammateInputSchema as tH,TeamSimpleAgentStatusToolResultSchema as eH,TeamSpawnTeammateInputSchema as $G,TeamStatusInputSchema as WG,TeamStatusToolResultSchema as yq,TeamTaskInputSchema as ZG,TeamTaskToolResultSchema as l4,validateWithZod as x,zodToJsonSchema as _0}from"@cline/shared";function QG($,W){let Z=$.replace(/\s+/g," ").trim();if(Z.length<=W)return Z;return`${Z.slice(0,Math.max(0,W-3)).trimEnd()}...`}function q2($,W){if($===void 0)throw Error(`Missing required field: ${W}`);return $}function hq($){let W=$.result;if(!W)return;return{textPreview:QG(W.text,zq),iterations:W.iterations,finishReason:W.finishReason,durationMs:W.durationMs,usage:{inputTokens:W.usage.inputTokens,outputTokens:W.usage.outputTokens,cacheReadTokens:W.usage.cacheReadTokens,cacheWriteTokens:W.usage.cacheWriteTokens,totalCost:W.usage.totalCost}}}function n9($){return $?.toISOString()}function y3($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:QG($.message,Tq),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:n9($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:n9($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:n9($.heartbeatAt),lastProgressAt:n9($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:hq($)}}function kq($){if($.status==="failed")throw Error(`Run "${$.id}" failed${$.error?`: ${$.error}`:""}`);if($.status==="cancelled")throw Error(`Run "${$.id}" was cancelled${$.error?`: ${$.error}`:""}`);if($.status==="interrupted")throw Error(`Run "${$.id}" was interrupted${$.error?`: ${$.error}`:""}`)}var m8=["team_spawn_teammate","team_shutdown_teammate","team_status","team_task","team_run_task","team_cancel_run","team_list_runs","team_await_runs","team_send_message","team_broadcast","team_read_mailbox","team_mission_log","team_cleanup","team_create_outcome","team_attach_outcome_fragment","team_review_outcome_fragment","team_finalize_outcome","team_list_outcomes"];function JG($){let W=[];if($.createBaseTools)W.push(...$.createBaseTools());W.push(...M2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1,includeSpawnTool:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:z2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:W,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function v8($){let W=$.leadAgentId??"lead",Z=$.restoredFromPersistence===!0,Q=M2({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;JG({runtime:$.runtime,requesterId:W,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),J.push(j.agentId)}return{tools:Q,restoredFromPersistence:Z,restoredTeammates:J}}function M2($){let W=$.allowSpawn??!0,Z=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,J=[];if(Z)J.push(D0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:_0($G),execute:async(X)=>{let Y=x($G,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!W)throw Error("Spawning teammates is disabled in this context.");let V={agentId:Y.agentId,rolePrompt:Y.rolePrompt};if(JG({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!Q)$.onLeadToolsUnlocked?.(M2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return x(eH,{agentId:Y.agentId,status:"spawned"})}}));if(!Q)return J;J.push(D0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:_0(tH),execute:async(X)=>{let Y=x(tH,X);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(Y.agentId,Y.reason),x(eH,{agentId:Y.agentId,status:"stopped"})}})),J.push(D0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:_0(WG),execute:async(X)=>{return x(WG,X),x(yq,$.runtime.getSnapshot())}})),J.push(D0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:_0(ZG),execute:async(X)=>{let Y=x(ZG,X);switch(Y.action){case"create":{let V=new Set(qq.create??[]),B=Object.entries(X).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),H=$.runtime.createTask({title:q2(Y.title,"title"),description:q2(Y.description,"description"),dependsOn:Y.dependsOn,assignee:Y.assignee,createdBy:$.requesterId});return x(l4,{action:"create",taskId:H.id,status:H.status,...B.length>0?{ignoredFields:B,note:`Ignored fields for action=create: ${B.join(", ")}`}:{}})}case"list":return x(l4,{action:"list",tasks:$.runtime.listTaskItems({status:Y.status,assignee:Y.assignee})});case"claim":{let V=$.runtime.claimTask(q2(Y.taskId,"taskId"),$.requesterId);return x(l4,{action:"claim",taskId:V.id,status:V.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let V=$.runtime.completeTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.summary,"summary"));return x(l4,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(q2(Y.taskId,"taskId"),$.requesterId,q2(Y.reason,"reason"));return x(l4,{action:"block",taskId:V.id,status:V.status})}}}}));let j=new Map;return J.push(D0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:_0(oH),execute:async(X)=>{let Y=x(oH,X);if(Y.runMode==="async"){let H=$.runtime.startTeammateRun(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0});return x(S3,{agentId:Y.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${Y.agentId} and queued as ${H.id}.`,runId:H.id})}let V=j.get(Y.agentId);if(V){let H=await V;return x(S3,{...H,status:"joined",deduped:!0,message:`Task for ${Y.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let B=$.runtime.routeToTeammate(Y.agentId,Y.task,{taskId:Y.taskId||void 0,fromAgentId:$.requesterId,continueConversation:Y.continueConversation||void 0}).then((H)=>x(S3,{agentId:Y.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${Y.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(Y.agentId)});return j.set(Y.agentId,B),await B}})),J.push(D0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:_0(vH),execute:async(X)=>{let Y=x(vH,X),V=$.runtime.cancelRun(Y.runId,Y.reason);return x(Rq,{runId:V.id,status:V.status})}})),J.push(D0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:_0(pH),execute:async(X)=>x(b3.array(),$.runtime.listRuns(x(pH,X)).map(y3))})),J.push(D0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:_0(gH),timeoutMs:Oq,execute:async(X)=>{let Y=x(gH,X);if(Y.runId){let H=await $.runtime.awaitRun(Y.runId);return kq(H),x(b3,y3(H))}let V=await $.runtime.awaitAllRuns(),B=V.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(B.length>0){let H=B.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return x(b3.array(),V.map(y3))}})),J.push(D0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:_0(sH),execute:async(X)=>{let Y=x(sH,X),V=$.runtime.sendMessage($.requesterId,Y.toAgentId,Y.subject,Y.body,Y.taskId??void 0);return x(bq,{id:V.id,toAgentId:V.toAgentId})}})),J.push(D0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:_0(mH),execute:async(X)=>{let Y=x(mH,X),V=$.runtime.broadcast($.requesterId,Y.subject,Y.body,{taskId:Y.taskId??void 0});return x(Mq,{delivered:V.length})}})),J.push(D0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:_0(nH),execute:async(X)=>{let Y=x(nH,X);return x(Cq.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:Y.unreadOnly,markRead:!0}))}})),J.push(D0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:_0(rH),execute:async(X)=>{let Y=x(rH,X),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:Y.taskId||void 0,kind:Y.kind,summary:Y.summary,evidence:Y.evidence?.length?Y.evidence:void 0,nextAction:Y.nextAction||void 0});return x(Pq,{id:V.id})}})),J.push(D0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:_0(cH),execute:async(X)=>{if(x(cH,X),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),x(Nq,{status:"cleaned"})}})),J.push(D0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:_0(uH),execute:async(X)=>{let Y=x(uH,X),V=$.runtime.createOutcome({title:Y.title,requiredSections:Y.requiredSections,createdBy:$.requesterId});return x(Eq,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(D0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:_0(xH),execute:async(X)=>{let Y=x(xH,X),V=$.runtime.attachOutcomeFragment({outcomeId:Y.outcomeId,section:Y.section,sourceAgentId:$.requesterId,sourceRunId:Y.sourceRunId||void 0,content:Y.content});return x(iH,{fragmentId:V.id,status:V.status})}})),J.push(D0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:_0(aH),execute:async(X)=>{let Y=x(aH,X),V=$.runtime.reviewOutcomeFragment({fragmentId:Y.fragmentId,reviewedBy:$.requesterId,approved:Y.approved});return x(iH,{fragmentId:V.id,status:V.status})}})),J.push(D0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:_0(dH),execute:async(X)=>{let Y=x(dH,X),V=$.runtime.finalizeOutcome(Y.outcomeId);return x(wq,{outcomeId:V.id,status:V.status})}})),J.push(D0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:_0(lH),execute:async(X)=>{return x(lH,X),x(Sq.array(),$.runtime.listOutcomes())}})),J}function a9($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}function jG($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var Iq=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:P$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...m8]}],xq={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function gq($){return $==="plan"||$==="yolo"?$:"act"}function YG($){let W=gq($.mode),Z=t0[n1({mode:W})],Q=I8($.providerId??"",$.modelId??"",W,k8);return{mode:W,flags:{...Z,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function XG($,W){if(W.disabledToolIds?.has($))return!1;let{flags:Z}=YG(W);if($==="spawn_agent")return Z.enableSpawnAgent===!0;if($==="teams")return Z.enableAgentTeams===!0;if($==="editor")return Z.enableEditor===!0||Z.enableApplyPatch===!0;let Q=xq[$];return Q?Z[Q]===!0:!1}function mq($,W){if($.id==="editor"){let{flags:Z}=YG(W),Q=Z.enableApplyPatch===!0&&Z.enableEditor!==!0;return{...$,defaultEnabled:XG($.id,W),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:XG($.id,W)}}function R2($={}){return Iq.map((W)=>mq(W,$))}function o9($={}){return R2($).filter((W)=>W.defaultEnabled).map((W)=>W.id)}function s9($){if(!$.enabled)return new Set;let W=R2($.availabilityContext),Z=new Set(W.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(W.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!Z.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${W.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function p4($,W={}){return R2(W).filter((Z)=>$.has(Z.id)).flatMap((Z)=>Z.headlessToolNames)}function t9($,W={}){return p4($,W)}import{getDefaultShell as vq}from"@cline/shared";function N2($={}){let{executorOptions:W={},executors:Z,...Q}=$,J=Q.shell??W.bash?.shell??vq(process.platform),j={...W,bash:{...W.bash,shell:J}},X={...h8(j),...Z??{}};return M$({...Q,shell:J,executors:X})}import{mkdirSync as rq,writeFileSync as iq}from"node:fs";import{dirname as nq}from"node:path";import{normalizeUserInput as aq,stripModeNotices as oq}from"@cline/shared";import{nanoid as sq}from"nanoid";var BG={};w(BG,{sanitizeSessionToken:()=>E2,parseTeamTaskSubSessionId:()=>u8,parseSubSessionId:()=>i4,makeTeamTaskSubSessionId:()=>r4,makeSubSessionId:()=>c8,deriveSubsessionStatus:()=>n4});import{nanoid as dq}from"nanoid";function E2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function c8($,W){let Z=E2($),Q=E2(W),J=`${Z}__${Q}`;return J.length>180?J.slice(0,180):J}function r4($,W){let Z=E2($),Q=E2(W);return`${Z}__teamtask__${Q}__${dq(6)}`}function u8($){let Z=$.indexOf("__teamtask__");if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+12),j=J.lastIndexOf("__");if(j<=0)return null;let X=J.slice(0,j),Y=J.slice(j+2);if(!Q||!X||!Y)return null;return{rootSessionId:Q,agentId:X,teamTaskId:Y}}function i4($){if(u8($))return null;let W="__",Z=$.indexOf(W);if(Z<=0)return null;let Q=$.slice(0,Z),J=$.slice(Z+W.length);if(!Q||!J)return null;return{rootSessionId:Q,agentId:J}}function n4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let W=String($.reason??"").toLowerCase();if(W.includes("cancel")||W.includes("abort")||W.includes("interrupt"))return"cancelled";if(W.includes("fail")||W.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as Z0}from"zod";var KG={};w(KG,{isTerminalSessionStatus:()=>GG,isNonTerminalSessionStatus:()=>G0,SessionSource:()=>K0,SESSION_STATUSES:()=>a4,NON_TERMINAL_SESSION_STATUSES:()=>HG});import{SESSION_STATUS_VALUES as lq}from"@cline/shared";var a4=lq,HG=["idle","running","pending"];function GG($){return!HG.includes($)}function G0($){return!GG($)}var K0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var pq=Z0.enum(a4),m0=Z0.object({version:Z0.literal(1),session_id:Z0.string().min(1),source:Z0.string().min(1),pid:Z0.number().int(),started_at:Z0.string().min(1),ended_at:Z0.string().min(1).optional(),exit_code:Z0.number().int().nullable().optional(),status:pq,interactive:Z0.boolean(),provider:Z0.string().min(1),model:Z0.string().min(1),cwd:Z0.string().min(1),workspace_root:Z0.string().min(1),team_name:Z0.string().min(1).optional(),enable_tools:Z0.boolean(),enable_spawn:Z0.boolean(),enable_teams:Z0.boolean(),prompt:Z0.string().optional(),metadata:Z0.record(Z0.string(),Z0.unknown()).optional(),messages_path:Z0.string().min(1).optional(),compaction_path:Z0.string().min(1).optional()});function FG($){if(!$)return!1;return Object.values($).some((W)=>typeof W==="function")}function k3($,W){let Z=[...$??[],...W??[]];if(Z.length===0)return;let Q=[],J=new Set;for(let j of Z){if(J.has(j.name))continue;J.add(j.name),Q.push(j)}return Q}function AG($){return JSON.stringify($,(W,Z)=>{if(Z instanceof Error)return{name:Z.name,message:Z.message,stack:Z.stack};return Z})}function o1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function h3($,W){let Z={...$};Z.id=o1(Z.id)??sq();let Q=Z.modelInfo&&typeof Z.modelInfo==="object"?{...Z.modelInfo}:void 0,J={id:o1(Q?.id)??o1(Z.modelId)??o1(W?.id),provider:o1(Q?.provider)??o1(Z.providerId)??o1(W?.provider),family:o1(Q?.family)??o1(W?.family)};if(delete Z.providerId,delete Z.modelId,J.id&&J.provider)Z.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Z.modelInfo;return Z}function e9($){return $.map((W)=>h3(W))}function $Z($,W,Z=[]){let Q=$.map((V,B)=>{let H=Z[B],K=H?.role===V.role&&JSON.stringify(H.content)===JSON.stringify(V.content)?{...H,...V}:{...V};return h3(K)}),J=Z.length,j=[];for(let V=J;V<Q.length;V+=1)if(Q[V]?.role==="assistant")j.push(V);if(j.length===0){let V=[...Q].reverse().findIndex((B)=>B.role==="assistant");if(V===-1)return Q;j.push(Q.length-1-V)}let X=j[j.length-1],Y=j.some((V)=>Q[V]?.metrics);for(let V of j){let B=Q[V],H=B.metrics;if(!H&&V===X&&!Y){let G=W.usage;H={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}Q[V]={...h3(B,{id:W.model.id,provider:W.model.provider,family:W.model.info?.family}),...H?{metrics:H}:{},ts:B.ts??W.endedAt.getTime()}}return Q}function o4($){return{sessionId:$.sessionId,source:$.source,pid:$.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??void 0,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:$.parentSessionId??void 0,parentAgentId:$.parentAgentId??void 0,agentId:$.agentId??void 0,conversationId:$.conversationId??void 0,isSubagent:$.isSubagent,prompt:$.prompt??void 0,metadata:$.metadata??void 0,messagesPath:$.messagesPath??void 0,updatedAt:$.updatedAt}}var tq=120;function w2($){let W=$?.trim();return W?W.slice(0,tq):void 0}function I3($){let W=oq(aq($??"")).trim();if(!W)return;return w2(W.split(`
203
+ `)[0]?.trim())}function S$($){if(!$)return;let W={...$},Z=w2(typeof W.title==="string"?W.title:void 0);if(Z)W.title=Z;else delete W.title;return Object.keys(W).length>0?W:void 0}function s4($){let W=S$($.metadata)??{},Z=$.title!==void 0?w2($.title):I3($.prompt);if(Z)W.title=Z;return Object.keys(W).length>0?W:void 0}function x3($){let W=u8($);if(W)return{agent:"teammate",sessionId:W.rootSessionId,taskType:"team"};let Z=i4($);if(Z)return{agent:"subagent",sessionId:Z.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function g3($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:e9($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function UG($,W,Z){rq(nq($),{recursive:!0}),iq($,`${JSON.stringify(g3({updatedAt:W,context:Z,messages:[]}),null,2)}
204
+ `,"utf8")}function DG($,W){return m0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:W?.endedAt??$.endedAt??void 0,exit_code:W?.exitCode??$.exitCode??void 0,status:W?.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:W?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function _G($,W,Z){let Q=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let j=await W(J);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Q+=1,Q>=Z)return j;continue}return j}}U0();var fG={};w(fG,{summarizeUsageFromMessages:()=>l8,sumUsageTotals:()=>t4,getCurrentContextSize:()=>m3,createInitialAccumulatedUsage:()=>z0,accumulateUsageTotals:()=>f0});function z0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function f0($,W){return{inputTokens:$.inputTokens+Math.max(0,W.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,W.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,W.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,W.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,W.totalCost??0)}}function t4($){let W=z0();for(let Z of $)W=f0(W,Z);return W}function d8($){return typeof $==="number"&&Number.isFinite($)?$:0}function l8($){let W=z0();for(let Z of $){let Q=Z.metrics;if(!Q)continue;W=f0(W,{inputTokens:d8(Q.inputTokens),outputTokens:d8(Q.outputTokens),cacheReadTokens:d8(Q.cacheReadTokens),cacheWriteTokens:d8(Q.cacheWriteTokens),totalCost:d8(Q.cost)})}return W}function m3($){for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(Z?.role!=="assistant")continue;let Q=d8(Z.metrics?.inputTokens);return Q>0?Q:void 0}return}function eq($){if(!$||typeof $!=="object")return;let W=$,Z=W.skill??W.skill_name??W.skillName;if(typeof Z!=="string")return;let Q=Z.trim();return Q.length>0?Q:void 0}function v3($){if(!$||typeof $!=="object")return{};let W=$;return{agentId:typeof W.agentId==="string"?W.agentId:void 0,conversationId:typeof W.conversationId==="string"?W.conversationId:void 0,parentAgentId:typeof W.parentAgentId==="string"?W.parentAgentId:void 0}}function s1($){let W=$.agentId?.trim();if(!W)return;let Z=$.parentAgentId?.trim()||void 0,Q=$.teamRole,J="root";if(Q==="teammate")J="team_teammate";else if(Q==="lead")J="team_lead";else if(Z)J="subagent";return{agentId:W,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Z,createdByAgentId:$.createdByAgentId?.trim()||Z||void 0,isSubagent:Boolean(Z),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function $M($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function WM($){let W=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Z of W){let Q=Z?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function c3($,W,Z){let{sessionId:Q,config:J,liveSession:j,emit:X}=$,Y=J.telemetry,V=j?.runtime.teamRuntime,B=Z?.isPrimaryAgentEvent??!0,H=v3(W),G=s1({agentId:Z?.agentId??H.agentId,conversationId:Z?.conversationId??H.conversationId,parentAgentId:Z?.parentAgentId??H.parentAgentId,createdByAgentId:Z?.createdByAgentId,teamId:Z?.teamId??V?.getTeamId(),teamName:Z?.teamName??V?.getTeamName(),teamRole:Z?.teamRole,teamAgentId:Z?.teamAgentId});if(W.type==="content_start"&&W.contentType==="tool"&&W.toolName==="skills"){let K=eq(W.input);if(K)eW(Y,{ulid:Q,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(W.type==="content_end"&&W.contentType==="tool"){let K=W.toolName??"unknown",F=!W.error;if(f8(Y,{ulid:Q,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))$9(Y,{ulid:Q,modelId:J.modelId,provider:J.providerId,errorType:W.error,...G})}if(W.type==="notice"&&W.reason==="api_error")Z4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.message,...G});if(W.type==="error")Z4(Y,{ulid:Q,model:J.modelId,provider:J.providerId,errorMessage:W.error?.message??"unknown error",...G});if(W.type==="usage"&&j?.turnUsageBaseline){let K=$M(W);if(B){j.turnPrimaryUsage=f0(j.turnPrimaryUsage??z0(),K);let A=f0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Q,A),_8(Y,{ulid:Q,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),sW(Y,{ulid:Q,tokensIn:W.inputTokens,tokensOut:W.outputTokens,cacheWriteTokens:W.cacheWriteTokens,cacheReadTokens:W.cacheReadTokens,totalCost:W.cost,model:J.modelId,...G})}else{let A=WM({isPrimaryAgentEvent:B,overrides:Z,eventMetadata:H}),D=j.turnUsageByAgent??new Map;j.turnUsageByAgent=D,D.set(A,f0(D.get(A)??z0(),K))}let F=f0(j.turnPrimaryUsage??z0(),t4(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,f0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,F))}if(W.type==="iteration_end"&&B)$.persistMessages(Q,j?.agent.getMessages()??[],j?.config.systemPrompt);X({type:"agent_event",payload:{sessionId:Q,event:W,teamAgentId:Z?.teamAgentId,teamRole:Z!==void 0?Z.teamRole??(B?"lead":void 0):void 0}}),X({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:AG(W),ts:Date.now()}})}function t1($){return $.workspaceRoot??$.cwd}import{resolveProviderRequestHeaders as GN}from"@cline/llms";import{hasRuntimeConfigExtension as KN}from"@cline/shared";var p8="0.0.65";var e4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:p8,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};_1();import{existsSync as XZ,readFileSync as uM,statSync as dM}from"node:fs";import{basename as lM,dirname as JZ,join as YZ,resolve as jZ}from"node:path";import{discoverPluginModulePaths as pM,resolveConfiguredPluginModulePaths as vG,resolvePluginConfigSearchPaths as rM,SKILLS_CONFIG_DIRECTORY_NAME as iM}from"@cline/shared/storage";import{resolve as TM}from"node:path";import{normalizePluginManifest as zM}from"@cline/shared";import{existsSync as N0,readFileSync as i8}from"node:fs";import{builtinModules as ZM,createRequire as p3}from"node:module";import{dirname as b$,extname as W5,isAbsolute as QM,resolve as o}from"node:path";import{fileURLToPath as TG}from"node:url";import{PLUGIN_FILE_EXTENSIONS as JM}from"@cline/shared";var zG=b$(TG(import.meta.url)),jM=p3(import.meta.url),XM=o(zG,"..","..","..","..",".."),u3=BM(XM),YM=["@cline/sdk","@cline/agents","@cline/core","@cline/core/hub","@cline/core/hub/daemon-entry","@cline/core/telemetry","@cline/llms","@cline/llms/browser","@cline/shared","@cline/shared/automation","@cline/shared/browser","@cline/shared/storage","@cline/shared/db","@cline/shared/types"],r3=new Set(ZM.flatMap(($)=>[$,$.replace(/^node:/,"")])),$5=new Set(JM),VM=["development","node","import","require","default"];function BM($){let W={},Z={"@cline/sdk":o($,"packages/sdk/src/index.ts"),"@cline/agents":o($,"packages/agents/src/index.ts"),"@cline/core":o($,"packages/core/src/index.ts"),"@cline/llms":o($,"packages/llms/src/index.ts"),"@cline/shared":o($,"packages/shared/src/index.ts"),"@cline/shared/storage":o($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":o($,"packages/shared/src/db/index.ts")};for(let[Q,J]of Object.entries(Z))if(N0(J))W[Q]=J;for(let Q of["agents","core","llms","shared"]){let J=o($,"packages",Q),j=o(J,"package.json");if(!N0(j))continue;try{let X=JSON.parse(i8(j,"utf8"));if(typeof X.name!=="string"||!X.exports)continue;if(typeof X.exports==="string"){let Y=o(J,X.exports);if(N0(Y))W[X.name]=Y;continue}if(typeof X.exports!=="object")continue;for(let[Y,V]of Object.entries(X.exports)){let B=HM(J,V);if(!B)continue;let H=Y==="."?X.name:`${X.name}/${Y.replace(/^\.\//,"")}`;W[H]=B}}catch{}}return W}function HM($,W){let Z=i3(W);if(!Z)return null;let Q=qG($,Z);for(let J of Q)if(N0(J))return J;return null}function i3($,W=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(W.has($))return null;W.add($);let Z=$;for(let Q of VM){let J=i3(Z[Q],W);if(J)return J}return null}function qG($,W){let Z=W.replace(/^\.\//,""),Q=[o($,W)];if(Z.startsWith("dist/")){let J=Z.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[o($,`${J}.ts`),o($,`${J}.tsx`),o($,`${J}.mts`),o($,`${J}.cts`),...Q]}return Q}function GM($){return Object.fromEntries(Object.entries($).sort(([W],[Z])=>Z.length-W.length))}function WZ($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function r8($){if($.startsWith("@")){let[W,Z]=$.split("/",3);return Z?`${W}/${Z}`:$}return $.split("/",1)[0]??$}function KM($){let W=r8($);if($===W)return".";return`.${$.slice(W.length)}`}function MG($){return r8($).startsWith("@cline/")}function d3($,W){let Z=r8(W),Q=b$($);while(!0){let J=o(Q,"node_modules",Z);if(N0(J)||N0(o(J,"package.json")))return!0;let j=o(Q,"..");if(j===Q)return!1;Q=j}}function OG($){return l3($)!==null}function l3($){try{return jM.resolve($)}catch{}return FM($)}function FM($){let W=r8($),Z=RG(W);if(!Z)return null;let Q=o(Z,"package.json");try{let J=JSON.parse(i8(Q,"utf8")),j=KM($),X=j==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,j)?J.exports[j]:void 0,Y=i3(X)??(j==="."&&typeof J.main==="string"?J.main:null);if(!Y)return null;let V=o(Z,Y),B=[V,...qG(Z,Y).filter((H)=>H!==V)];for(let H of B)if(N0(H))return H;return null}catch{return null}}function AM(){let $=[zG],W=process.env.CLINE_WRAPPER_PATH?.trim();if(W)$.push(b$(b$(W)));let Z=process.execPath?.trim();if(Z)$.push(b$(Z));return[...new Set($.map((Q)=>o(Q)))]}function UM($,W){let Z=$;while(!0){let Q=o(Z,"package.json");if(N0(Q))try{if(JSON.parse(i8(Q,"utf8")).name===W)return Z}catch{}let J=o(Z,"node_modules",W,"package.json");if(N0(J))return b$(J);let j=o(Z,"..");if(j===Z)return null;Z=j}}function RG($){for(let W of AM()){let Z=UM(W,$);if(Z)return Z}return null}function DM($){let Z=b$($);for(let Q=0;Q<4;Q++){let J=o(Z,"package.json");if(N0(J))try{let X=JSON.parse(i8(J,"utf8"));return X!=null&&typeof X==="object"&&"cline"in X}catch{return!1}let j=o(Z,"..");if(j===Z)return!1;Z=j}return!1}function NG($,W){let Z=W.startsWith("file:")?TG(W):QM(W)?W:o(b$($),W);if(N0(Z)&&$5.has(W5(Z)))return Z;for(let Q of $5){let J=`${Z}${Q}`;if(N0(J))return J}for(let Q of $5){let J=o(Z,`index${Q}`);if(N0(J))return J}return null}function EG($){let W=new Set,Z=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of Z)for(let J of $.matchAll(Q)){let j=J[1];if(j)W.add(j)}return[...W]}function _M($){return W5($)!==".ts"}function wG($,W,Z=new Set){if(Z.has($)||!N0($))return;if(Z.add($),!$5.has(W5($)))return;let Q=i8($,"utf8"),J=_M($);for(let j of EG(Q)){if(j.startsWith("node:")||r3.has(j))continue;if(WZ(j)){if(!J)continue;if(Object.hasOwn(u3,j)||Object.hasOwn(u3,r8(j))||d3($,j)||MG(j)&&OG(j)||W&&OG(j))continue;throw Error(`Cannot find module '${r8(j)}'`)}let X=NG($,j);if(X)wG(X,W,Z)}}function CG($,W=new Set,Z=new Set){if(W.has($)||!N0($))return Z;if(W.add($),!$5.has(W5($)))return Z;let Q=i8($,"utf8");for(let J of EG(Q)){if(Z.add(J),WZ(J))continue;let j=NG($,J);if(j)CG(j,W,Z)}return Z}function fM($,W){let Z=p3($),Q={},J=CG($),j=new Set(YM);for(let[X,Y]of Object.entries(u3)){try{Z.resolve(X);continue}catch{}Q[X]=Y}for(let X of J)if(WZ(X)&&(MG(X)||W))j.add(X);for(let X of j){if(Object.hasOwn(Q,X)||d3($,X))continue;let Y=l3(X);if(Y)Q[X]=Y}if(!W)return Q;for(let X of J){if(!WZ(X)||Object.hasOwn(Q,X)||d3($,X)||X.startsWith("node:")||r3.has(X))continue;let Y=l3(X);if(Y)Q[X]=Y}return Q}function LM($){let W=W5($);return W===".ts"||W===".tsx"||W===".mts"||W===".cts"}var C2;function OM(){if(C2!==void 0)return C2;let $=RG("jiti");if(!$)return C2=null,null;let W=o($,"dist","babel.cjs");if(!N0(W))return C2=null,null;try{let Q=p3(W)(W);C2=typeof Q==="function"?Q:null}catch{C2=null}return C2}async function PG($,W={}){let Z=!DM($);wG($,Z);let Q=fM($,Z),J=GM(Q),j=await import("jiti"),X=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!X)throw Error("Unable to load jiti");let Y=Object.entries(J).filter(([,G])=>LM(G)).map(([G])=>G),V=OM(),B=V?(G)=>V({...G,interopDefault:!0}):void 0;return await X($,{alias:J,cache:W.useCache,requireCache:W.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...r3],transformModules:Y,tryNative:!1,...B?{transform:B}:{}}).import($,{})}function SG($,W){if(!$)return!0;if($.providerIds?.length){if(!W?.providerId||!$.providerIds.includes(W.providerId))return!1}if($.modelIds?.length){if(!W?.modelId||!$.modelIds.includes(W.modelId))return!1}return!0}function bG($){return typeof $==="object"&&$!==null}function n3($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function qM($,W){if(!bG($.manifest))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);if(!n3($.manifest.capabilities))throw Error(`Invalid plugin module at ${W}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${W}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!n3($.manifest.providerIds))throw Error(`Invalid plugin module at ${W}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!n3($.manifest.modelIds))throw Error(`Invalid plugin module at ${W}: manifest.modelIds must be a string array when provided`)}function MM($,W){if(!bG($))throw Error(`Invalid plugin module at ${W}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${W}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${W}: missing required "manifest"`);qM($,W)}async function Z5($,W={}){let Z=TM(W.cwd??process.cwd(),$),Q=await PG(Z,{useCache:W.useCache}),J=W.exportName??"plugin",j=Q.default??Q[J];MM(j,Z);let X=j,Y=X.setup,V=Y?(B,H)=>{let G={...W.session,...H.session},K={...H,session:Object.keys(G).length>0?G:void 0,client:W.client??H.client,user:W.user??H.user,workspaceInfo:W.workspaceInfo??H.workspaceInfo,automation:W.automation??H.automation,logger:W.logger??H.logger,telemetry:W.telemetry??H.telemetry};return Y(B,K)}:void 0;return{...X,manifest:zM(X.manifest),setup:V}}async function ZZ($,W={}){return(await P2($,W)).plugins}async function P2($,W={}){let Z=[],Q=[],J=new Map,j=0;for(let Y of $)try{let V=await Z5(Y,W);if(!SG(V.manifest,W))continue;let B=J.get(V.name);if(B)Q.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:Y,overriddenPluginPath:B.pluginPath,message:`Plugin "${V.name}" from ${Y} overrides ${B.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:Y,order:j++})}catch(V){let B=V instanceof Error?V.message:String(V);Z.push({pluginPath:Y,phase:"load",message:B,stack:V instanceof Error?V.stack:void 0})}let X=[...J.values()].sort((Y,V)=>Y.order-V.order);return{plugins:X.map((Y)=>Y.plugin),pluginPaths:X.map((Y)=>Y.pluginPath),failures:Z,warnings:Q}}import{existsSync as t3}from"node:fs";import{createRequire as mG}from"node:module";import{dirname as QZ,join as a8}from"node:path";import{fileURLToPath as CM}from"node:url";var xG={};w(xG,{resolveSubprocessRuntimeExecutable:()=>a3,buildSubprocessSandboxCommand:()=>IG,SubprocessSandbox:()=>n8,CLINE_JS_RUNTIME_PATH_ENV:()=>kG});import{spawn as RM}from"node:child_process";import{basename as NM}from"node:path";import{augmentNodeCommandForDebug as EM,withResolvedClineBuildEnv as wM}from"@cline/shared";function yG($){if($ instanceof Error)return $;return Error(String($))}var kG="CLINE_JS_RUNTIME_PATH";function hG($){let W=$?.trim();if(!W)return!1;let Z=NM(W).toLowerCase();return Z==="node"||Z==="node.exe"||Z==="bun"||Z==="bun.exe"}function a3($={}){let W=$.env??process.env,Z=$.runtimeExecutable?.trim()||W[kG]?.trim();if(Z)return Z;let Q=$.execPath?.trim()||process.execPath;if(hG(Q))return Q;for(let J of[W.BUN_EXEC_PATH,W.npm_node_execpath,W.NODE]){let j=J?.trim();if(j&&hG(j))return j}return"node"}function IG($,W={}){let Z=a3({env:W.env,execPath:W.execPath,runtimeExecutable:W.runtimeExecutable});return EM([Z,...$],{env:W.env,execArgv:W.execArgv,debugRole:W.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class n8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let W=this.pending.get($);if(!W)return;if(this.pending.delete($),W.timeout)clearTimeout(W.timeout);return W}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],W=IG($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Z=RM(W[0]??a3(this.options),W.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:wM(process.env),windowsHide:!0});this.process=Z;let Q="",J=(j)=>{let X=Q+j;Q=X.length>4000?X.slice(-4000):X};Z.stderr?.setEncoding("utf8"),Z.stderr?.on("data",(j)=>{J(j)}),Z.on("message",(j)=>{this.onMessage(j)}),Z.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${yG(j).message}`))}),Z.on("exit",(j,X)=>{this.process=null;let Y=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(X)})${Y?`: ${Y}`:""}`))})}async call($,W,Z={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,j={type:"call",id:J,method:$,args:W};return await new Promise((X,Y)=>{let V={resolve:(B)=>X(B),reject:Y};if((Z.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),Y(Error(`${this.processLabel} call timed out after ${Z.timeoutMs}ms: ${$}`))},Z.timeoutMs);this.pending.set(J,V),Q.send(j,(B)=>{if(!B)return;let H=this.clearPendingRequest(J);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${yG(B).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((W)=>{let Z=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}W()},300);$.once("exit",()=>{clearTimeout(Z),W()});try{$.kill("SIGTERM")}catch{clearTimeout(Z),W()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let W=this.clearPendingRequest($.id);if(!W)return;if($.ok){W.resolve($.result);return}W.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[W,Z]of this.pending.entries()){if(this.pending.delete(W),Z.timeout)clearTimeout(Z.timeout);Z.reject($)}}}function PM($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function Q5($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function SM(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function bM(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Z=mG($).resolve(`${SM()}/package.json`),Q=a8(QZ(Z),"extensions","plugin-sandbox-bootstrap.js");return t3(Q)?Q:void 0}catch{return}}function yM(){let $=process.execPath?.trim();if(!$)return;let W=a8(QZ(QZ($)),"extensions","plugin-sandbox-bootstrap.js");return t3(W)?W:void 0}function hM(){let $=QZ(CM(import.meta.url)),W=mG(import.meta.url),Z=[a8($,"plugin-sandbox-bootstrap.js"),a8($,"extensions","plugin-sandbox-bootstrap.js"),a8($,"agents","plugin-sandbox-bootstrap.js"),bM(),yM()];for(let j of Z.filter((X)=>typeof X==="string"))if(t3(j))return{file:j};let Q=a8($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=W.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
205
+ `)}}var o3=hM();function s3($,W,Z){if(typeof $==="number"&&$>0)return $;if(Z){let Q=process.env[Z];if(Q){let J=Number(Q);if(Number.isInteger(J)&&J>0)return J}}return W}async function o8($){let W=new n8({name:"plugin-sandbox",..."file"in o3?{bootstrapFile:o3.file}:{bootstrapScript:o3.script},onEvent:$.onEvent}),Z=s3($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Q=s3($.hookTimeoutMs,3000),J=s3($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},X,Y=()=>{return X??=W.call("initialize",j,{timeoutMs:Z}).finally(()=>{X=void 0}),X},V;try{V=await W.call("initialize",j,{timeoutMs:Z})}catch(G){throw await W.shutdown().catch(()=>{}),G}let B=V.plugins.map(PM);return{extensions:B.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{kM(F,W,G,J,Y),IM(F,W,G,J,Y),xM(F,W,G,J,Y),mM(F,W,G,J,Y),gM(F,G)}};return K.hooks=cM(W,G,Q,Y),K}),failures:V.failures,pluginPaths:B.map((G)=>G.pluginPath),shutdown:async()=>{await W.shutdown()},warnings:V.warnings}}function kM($,W,Z,Q,J){for(let j of Z.contributions?.tools??[]){let X={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(Y,V)=>{try{return await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}catch(B){if(!Q5(B))throw B;return await J(),await W.call("executeTool",{pluginId:Z.pluginId,contributionId:j.id,input:Y,context:V},{timeoutMs:Q})}}};$.registerTool(X)}}function IM($,W,Z,Q,J){for(let j of Z.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(X)=>{try{return await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}catch(Y){if(!Q5(Y))throw Y;return await J(),await W.call("executeCommand",{pluginId:Z.pluginId,contributionId:j.id,input:X},{timeoutMs:Q})}}})}function xM($,W,Z,Q,J){for(let j of Z.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}catch(X){if(!Q5(X))throw X;return await J(),await W.call("resolveRuleContent",{pluginId:Z.pluginId,contributionId:j.id},{timeoutMs:Q})}}:j.content??""})}function gM($,W){for(let Z of W.contributions?.providers??[])$.registerProvider({name:Z.name,description:Z.description,metadata:Z.metadata});for(let Z of W.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Z.eventType,source:Z.source,description:Z.description,attributesSchema:Z.attributesSchema,payloadSchema:Z.payloadSchema,examples:Z.examples,metadata:Z.metadata});for(let Z of W.contributions?.mcpServers??[])$.registerMcpServer(Z)}function mM($,W,Z,Q,J){for(let j of Z.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(X){try{let Y=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return gG(Y)?Y:X}catch(Y){if(!Q5(Y))throw Y;await J();let V=await W.call("buildMessages",{pluginId:Z.pluginId,contributionId:j.id,messages:X},{timeoutMs:Q});return gG(V)?V:X}}})}function gG($){return Array.isArray($)&&$.every((W)=>typeof W==="object"&&W!==null&&("role"in W)&&("content"in W))}function vM($,W,Z,Q,J){return async(j)=>{try{return await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}catch(X){if(!Q5(X))throw X;return await J(),await $.call("invokeHook",{pluginId:W,hookName:Z,payload:j},{timeoutMs:Q})}}}function cM($,W,Z,Q){let J={};for(let j of W.hooks??[])J[j]=vM($,W.pluginId,j,Z,Q);return Object.keys(J).length>0?J:void 0}var $J="package.json",nM="package";function J5($){return rM($)}function j5($){return pM($)}function aM($){try{return XZ($)&&dM($).isDirectory()}catch{return!1}}function WJ($){let W=[],Z=new Set;for(let Q of $){let J=jZ(Q);if(Z.has(J))continue;Z.add(J),W.push(J)}return W}function cG($){let W=WJ($);return c9(W)}function uG($){return J5($).flatMap((W)=>j5(W)).filter((W)=>XZ(W))}function oM($,W){let Z=[];for(let Q of $)try{Z.push(...vG([Q],W))}catch{}return Z}function e3($){return typeof $==="object"&&$!==null}function sM($){try{let W=JSON.parse(uM(YZ($,$J),"utf8"));if(!e3(W)||!e3(W.cline))return[];let Z=W.cline.plugins;if(!Array.isArray(Z))return[];let Q=[];for(let J of Z){if(typeof J==="string"){Q.push(J);continue}if(!e3(J)||!Array.isArray(J.paths))continue;for(let j of J.paths)if(typeof j==="string")Q.push(j)}return Q}catch{return[]}}function dG($,W){let Z=jZ(W);return sM($).some((Q)=>jZ($,Q)===Z)}function tM($,W){return lM($)===nM&&XZ(YZ(JZ($),$J))&&dG(JZ($),W)}function eM($){let W=jZ($),Z=[],Q=JZ(W);while(!0){if(tM(Q,W)){Z.push(Q);break}if(XZ(YZ(Q,$J))){if(dG(Q,W))Z.push(Q);break}let J=JZ(Q);if(J===Q)break;Q=J}return WJ(Z)}function e1($={}){let W=$.cwd??process.cwd(),Z=uG($.workspacePath),Q=vG($.pluginPaths??[],W);return cG([...Q,...Z])}function $R($={}){let W=$.cwd??process.cwd(),Z=uG($.workspacePath),Q=oM($.pluginPaths??[],W);return cG([...Q,...Z])}function $$($){let W=[];for(let Z of $)for(let Q of eM(Z)){let J=YZ(Q,iM);if(aM(J))W.push(J)}return WJ(W)}function lG($={}){return $$($R($))}async function s8($={}){let W=e1($);if(W.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Q=await P2(W,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}let Z=await o8({pluginPaths:W,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Z.extensions??[],shutdown:Z.shutdown,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}import{execFile as WR}from"node:child_process";import{promisify as ZR}from"node:util";var QR=ZR(WR);function ZJ($,W){$?.log(W,{severity:"warn"})}function JR($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))return;let Z=W;if(!Z.latest||!Array.isArray(Z.history))return;let Q=Z.latest,J=Z.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:J}}async function S2($,W){let Z=await QR("git",["-C",$,...W],{windowsHide:!0});return{stdout:Z.stdout.trim(),stderr:Z.stderr.trim()}}async function QJ($,W){if(!$)return;let Z=`refs/cline/checkpoints/${W}/`;try{let{stdout:Q}=await S2($,["for-each-ref","--format=%(refname)",Z]),J=Q.trim().split(`
206
+ `).filter(Boolean);await Promise.allSettled(J.map((j)=>S2($,["update-ref","-d",j])))}catch{}}async function pG($,W,Z){if(!$||Z.length===0)return;await Promise.allSettled(Z.map((Q)=>S2($,["update-ref",`refs/cline/checkpoints/${W}/${Q.runCount}`,Q.ref])))}function jR($,W){let Z=$.findIndex((Q)=>Q.runCount===W.runCount);if(Z<0)return[...$,W];return $.map((Q,J)=>J===Z?W:Q)}function rG($){let W=$.initialRunCount??0,Z,Q=async()=>{if(Z!==void 0)return Z;try{Z=(await S2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Z=!1}return Z},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:W});if(!await Q())return;let j=async(B)=>{try{let G=(await S2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:W,kind:"commit"}}catch(H){ZJ($.logger,`${B}: ${H instanceof Error?H.message:String(H)}`);return}},X=`cline checkpoint session=${$.sessionId} run=${W}`,Y="";try{Y=(await S2($.cwd,["stash","create",X])).stdout.trim()}catch(B){return ZJ($.logger,`Checkpoint snapshot failed: ${B instanceof Error?B.message:String(B)}`),j("Checkpoint HEAD fallback failed")}if(!Y)return j("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${W}`;try{await S2($.cwd,["update-ref",V,Y])}catch(B){ZJ($.logger,`Checkpoint store failed: ${B instanceof Error?B.message:String(B)}`);return}return{ref:Y,createdAt:Date.now(),runCount:W,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;W+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||W<1)return;let X=await J();if(!X)return;let Y=await $.readSessionMetadata(),V=JR(Y);if(V?.latest.ref===X.ref)return;let B=jR(V?.history??[],X);await $.writeSessionMetadata({...Y??{},checkpoint:{latest:X,history:B}});return}}}import{spawn as AR}from"node:child_process";import{appendFileSync as UR,readFileSync as DR}from"node:fs";import{join as _R}from"node:path";import{augmentNodeCommandForDebug as aG,withResolvedClineBuildEnv as XJ}from"@cline/shared";import{ensureHookLogDir as iG}from"@cline/shared/storage";function t8($,W){if(!W)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:W}}import{existsSync as XR,readdirSync as YR}from"node:fs";import{basename as VR,extname as BR,join as HR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as VZ,resolveHooksConfigSearchPaths as GR}from"@cline/shared/storage";function X5($){return GR($)}var e8;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(e8||={});var Y5={["TaskStart"]:"agent_start",["TaskResume"]:"agent_resume",["TaskCancel"]:"agent_abort",["TaskComplete"]:"agent_end",["TaskError"]:"agent_error",["PreToolUse"]:"tool_call",["PostToolUse"]:"tool_result",["UserPromptSubmit"]:"prompt_submit",["PreCompact"]:void 0,["SessionShutdown"]:"session_shutdown"},KR=new Map(Object.values(e8).map(($)=>[$.toLowerCase(),$])),FR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function V5($){let W=BR($).toLowerCase();if(!FR.has(W))return;let Z=VR($,W).trim().toLowerCase();return KR.get(Z)}function y$($){let W=[],Z=new Set,Q=X5($).filter((J)=>XR(J));for(let J of Q)try{for(let j of YR(J,{withFileTypes:!0})){if(!j.isFile())continue;let X=V5(j.name);if(!X)continue;let Y=HR(J,j.name);if(Z.has(Y))continue;Z.add(Y),W.push({fileName:X,hookEventName:Y5[X],path:Y})}}catch{}return W.sort((J,j)=>J.path.localeCompare(j.path))}function HZ($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))W[Z]=typeof Q==="string"?Q:JSON.stringify(Q);return W}function BZ($,W,Z){let Q=Z instanceof Error?`: ${Z.message}`:"",J=`${W}${Q}`;if($){try{$.log(J,{severity:"warn",...Z!==void 0?{error:Z}:{}})}catch{}return}console.warn(J)}function fR($,W){if(!W)return $;if(!$)return{...W};let Z=[$.context,W.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
207
+ `),Q=[...$.appendMessages??[],...W.appendMessages??[]];return{cancel:$.cancel===!0||W.cancel===!0?!0:void 0,review:$.review===!0||W.review===!0?!0:void 0,context:Z||void 0,overrideInput:W.overrideInput!==void 0?W.overrideInput:$.overrideInput,systemPrompt:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function LR($){if(!$||typeof $!=="object")return;let W=$,Z=typeof W.context==="string"?W.context:typeof W.contextModification==="string"?W.contextModification:typeof W.errorMessage==="string"?W.errorMessage:void 0;return{cancel:typeof W.cancel==="boolean"?W.cancel:void 0,review:typeof W.review==="boolean"?W.review:void 0,context:Z,overrideInput:Object.hasOwn(W,"overrideInput")?W.overrideInput:void 0}}function JJ($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function E0($,W){let Z=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:W.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:W.workspacePath?[W.workspacePath]:[],workspaceInfo:W.workspaceInfo,userId:Z,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function OR($){let W=$.trim();if(!W)return{};let Q=W.split(`
208
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function TR($,W){let Z=$.stdin;if(!Z)throw Error("hook command failed to create stdin");await new Promise((Q,J)=>{let j=!1,X=()=>{Z.off("error",V),Z.off("finish",B),$.off("close",H)},Y=(G)=>{if(j)return;if(j=!0,X(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){Q();return}J(G);return}Q()},V=(G)=>Y(G),B=()=>Y(),H=()=>Y();Z.on("error",V),Z.once("finish",B),$.once("close",H);try{Z.end(W)}catch(G){Y(G)}})}async function oG($,W){if(W.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await nG($,W)}catch(Z){let Q=MR(W.command,process.platform,Z);if(!Q)throw Z;return await nG($,{...W,command:Q})}}async function nG($,W){let Z=aG(W.command,{env:W.env,debugRole:"hook"}),Q=AR(Z[0],Z.slice(1),{cwd:W.cwd,env:XJ(W.env),stdio:W.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W.detached,windowsHide:!0}),J=new Promise((K)=>{Q.once("spawn",()=>K())}),j=new Promise((K,F)=>{Q.once("error",(A)=>F(A))}),X=JSON.stringify($);if(await Promise.race([J,j]),await TR(Q,X),W.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let Y="",V="",B=!1,H;Q.stdout.on("data",(K)=>{Y+=K.toString()}),Q.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,Q.kill("SIGKILL")},W.timeoutMs);Q.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=OR(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,j])}function zR($){try{let Z=DR($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Z?.startsWith("#!"))return;let Q=Z.slice(2).trim();if(!Q)return;let J=Q.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function qR($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function MR($,W=process.platform,Z){if(W!=="win32"||!qR(Z))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function sG($){if($.length===0)return;let[W,...Z]=$,Q=W.replace(/\\/g,"/").toLowerCase(),J=Q.split("/").at(-1)??Q;if(J==="env")return sG(Z);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Z];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Z]:[J,...Z];return $}function RR($){let W=zR($);if(W&&W.length>0)return[...sG(W)??W,$];let Z=$.toLowerCase();if(Z.endsWith(".sh")||Z.endsWith(".bash")||Z.endsWith(".zsh"))return["bash",$];if(Z.endsWith(".js")||Z.endsWith(".mjs")||Z.endsWith(".cjs"))return aG(["node",$],{debugRole:"hook"});if(Z.endsWith(".ts")||Z.endsWith(".mts")||Z.endsWith(".cts"))return["bun","run",$];if(Z.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Z.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function NR($){let W={};for(let Z of y$($)){if(!Z.hookEventName)continue;let Q=Z.hookEventName,J=W[Q]??[];J.push(RR(Z.path)),W[Q]=J}return W}async function ER($){let W;for(let Z of $.commands){let Q=Z.join(" ");try{let J=await oG($.payload,{command:Z,cwd:$.cwd,env:XJ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){BZ($.logger,`hook command timed out: ${Q}`);continue}if(J?.parseError){BZ($.logger,`hook command returned invalid JSON control output: ${Q} (${J.parseError})`);continue}W=fR(W,LR(J?.parsedJson))}catch(J){BZ($.logger,`hook command failed: ${Q}`,J)}}return W}function b2($){for(let W of $.commands){let Z=W.join(" ");oG($.payload,{command:W,cwd:$.cwd,env:XJ(process.env),detached:!0}).catch((Q)=>{BZ($.logger,`hook command failed: ${Z}`,Q)})}}function h$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function jJ($,W){return{...h$($.snapshot),userMessage:W}}function tG($){return{...h$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function eG($){return{...h$($.snapshot),iteration:$.snapshot.iteration,record:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}}function $K($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function wR($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}function $6($){let W={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Z=(Q)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
209
+ `,X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??_R(iG(),"hooks.jsonl");iG(X),UR(X,J,"utf8")};return{beforeRun:async(Q)=>{let J=jJ(Q,"");Z({...E0(J,W),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let J=tG(Q);Z({...E0(J,W),hookName:"tool_call",iteration:J.iteration,tool_call:{id:J.call.id,name:J.call.name,input:J.call.input},preToolUse:{toolName:J.call.name,parameters:HZ(J.call.input)}});return},afterTool:async(Q)=>{let J=eG(Q);Z({...E0(J,W),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:HZ(J.record.input),result:typeof J.record.output==="string"?J.record.output:JSON.stringify(J.record.output),success:!J.record.error,executionTimeMs:J.record.durationMs}});return},afterRun:async({snapshot:Q,result:J})=>{let j=h$(Q);if(J.status==="completed"){Z({...E0(j,W),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||JJ(J.error?.message)){Z({...E0(j,W),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Z({...E0(j,W),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let J=jJ({snapshot:Q.snapshot},$K(Q.message.content));Z({...E0(J,W),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function B5($){let W=NR($.workspacePath);if(!Object.values(W).some((G)=>G.length>0))return;let Q=async(G,K)=>{let F=W[K]??[];if(F.length===0)return;b2({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...E0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...E0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=W.prompt_submit??[];if(K.length>0)b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},j=async(G)=>{let K=W.tool_call??[];if(K.length===0)return;return ER({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...E0(G,$),hookName:"tool_call",iteration:G.iteration,tool_call:{id:G.call.id,name:G.call.name,input:G.call.input},preToolUse:{toolName:G.call.name,parameters:HZ(G.call.input)}}})},X=async(G)=>{let K=W.tool_result??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:HZ(G.record.input),result:typeof G.record.output==="string"?G.record.output:JSON.stringify(G.record.output),success:!G.record.error,executionTimeMs:G.record.durationMs}}})},Y=async(G)=>{let K=W.agent_end??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=W.agent_error??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},B=async(G)=>{if(JJ(G.reason)){let F=W.agent_abort??[];if(F.length>0)b2({commands:F,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=W.session_shutdown??[];if(K.length===0)return;b2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...E0(G,$),hookName:"session_shutdown",reason:G.reason}})},H={};if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0||(W.prompt_submit?.length??0)>0){if((W.agent_start?.length??0)>0||(W.agent_resume?.length??0)>0)H.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(h$(G.snapshot),K);return};if((W.prompt_submit?.length??0)>0)H.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(jJ({snapshot:G.snapshot},$K(G.message.content)))}}if((W.tool_call?.length??0)>0)H.beforeTool=async(G)=>{let K=await j(tG(G));return wR(K)};if((W.tool_result?.length??0)>0)H.afterTool=async(G)=>{await X(eG(G));return};if((W.agent_end?.length??0)>0)H.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await Y({...h$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((W.agent_error?.length??0)>0||(W.agent_abort?.length??0)>0||(W.session_shutdown?.length??0)>0){let G=H.afterRun;H.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||JJ(A.error?.message)){await B({...h$(F),reason:A.error?.message});return}if(A.error)await V({...h$(F),iteration:A.iterations,error:A.error})}}return H}function W6($){return t8("core.hook_config_files",B5($))}function y2($,W){let Z=$.map((Q)=>Q[W]).filter((Q)=>typeof Q==="function");if(Z.length===0)return;return async(Q)=>{let J;for(let j of Z){let X=await j(Q);if(!X||typeof X!=="object")continue;let Y=X;J={...J??{},...Y,stop:J?.stop===!0||Y.stop===!0?!0:Y.stop,options:J?.options||Y.options?{...J?.options??{},...Y.options??{}}:void 0}}return J}}function h2($){let W=$.filter((Z)=>Z!==void 0);if(W.length===0)return;return{beforeRun:y2(W,"beforeRun"),afterRun:y2(W,"afterRun"),beforeModel:y2(W,"beforeModel"),afterModel:y2(W,"afterModel"),beforeTool:y2(W,"beforeTool"),afterTool:y2(W,"afterTool"),onEvent:y2(W,"onEvent")}}var WK={};w(WK,{normalizeRuntimeCapabilities:()=>w0});function w0(...$){let W,Z;for(let J of $){if(!J)continue;if(J.toolExecutors)W={...W??{},...J.toolExecutors};if(J.requestToolApproval)Z=J.requestToolApproval}let Q=W&&Object.keys(W).length>0;if(!Q&&!Z)return;return{...Q?{toolExecutors:W}:{},...Z?{requestToolApproval:Z}:{}}}var HK={};w(HK,{toProviderConfig:()=>$1,emptyStoredProviderSettings:()=>x$,StoredProviderSettingsSchema:()=>j6,StoredProviderSettingsEntrySchema:()=>yZ,ProviderSettingsSchemaTyped:()=>J6});import{z as I$}from"zod";var BK={};w(BK,{toProviderConfig:()=>$1,safeParseSettings:()=>bZ,safeCreateProviderConfig:()=>DJ,parseSettings:()=>SZ,normalizeProviderId:()=>Q6,isBuiltInProviderId:()=>AJ,createProviderConfig:()=>UJ,SapSettingsSchema:()=>wZ,ReasoningSettingsSchema:()=>MZ,ProviderSettingsSchema:()=>k$,ProviderProtocolSchema:()=>TZ,ProviderIdSchema:()=>A5,ProviderClientSchema:()=>zZ,OcaSettingsSchema:()=>CZ,ModelCatalogSettingsSchema:()=>PZ,GcpSettingsSchema:()=>NZ,BUILT_IN_PROVIDER_IDS:()=>FJ,BUILT_IN_PROVIDER:()=>F5,AzureSettingsSchema:()=>EZ,AwsSettingsSchema:()=>RZ,AuthSettingsSchema:()=>qZ});import*as e0 from"@cline/llms";import{z as E}from"zod";var VK={};w(VK,{resolveProviderConfig:()=>K5,getProviderConfig:()=>OZ,getLiveModelsCatalog:()=>Z6,clearPublicModelsCatalogCache:()=>sR,clearPrivateModelsCatalogCache:()=>KJ,clearLiveModelsCatalogCache:()=>GJ,OPENAI_COMPATIBLE_PROVIDERS:()=>G5,DEFAULT_MODELS_CATALOG_URL:()=>DZ});import*as W0 from"@cline/llms";function YJ($){if(!Array.isArray($))return[];return $.map((W)=>{if(typeof W==="string")return W.trim();if(W&&typeof W==="object"){let Z=W;for(let Q of[Z.id,Z.name,Z.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((W)=>W.length>0)}function CR($,W){let Z=YJ($);if(Z.length>0)return Z;if(!$||typeof $!=="object")return[];let Q=$,J=YJ(Q.data??Q.models);if(J.length>0)return J;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let X=Object.keys(Q.models).filter((Y)=>Y.trim().length>0);if(X.length>0)return X}let j=Q.providers?.[W];if(j&&typeof j==="object"){let Y=YJ(j.models??j);if(Y.length>0)return Y}return[]}async function GZ($,W){let Z=await fetch($,{method:"GET"});if(!Z.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Z.status}`);return CR(await Z.json(),W)}function ZK($){return $.replace(/\/+$/,"")}function KZ($,W,Z){let Q=Z?.trim();if(!Q)return;let J=$?.trim();if(!J||!W?.trim())return Q;try{let j=new URL(Q),X=new URL(W),Y=new URL(J);if(j.origin!==X.origin)return Q;let V=ZK(X.pathname),B=ZK(Y.pathname);if(V&&j.pathname.startsWith(`${V}/`)){let H=j.pathname.slice(V.length);Y.pathname=`${B}${H}`}else Y.pathname=j.pathname;return Y.search=j.search,Y.hash=j.hash,Y.toString()}catch{return Q}}function PR($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{...Z}]))}function SR($){if($.baseUrl.length===0)return!1;switch($.client){case"openai-compatible":case"openai":case"openai-r1":case"fetch":return!0;default:return $.protocol==="openai-chat"}}var bR=Object.values(W0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:PR($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),JK=Object.fromEntries(bR.map(($)=>[$.id,$]));function yR($){return JK[$]}function hR(){return Object.fromEntries(Object.entries(JK).filter(([,$])=>SR($)))}function jK($=[]){let W=$.flatMap((Z)=>{switch(Z){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Z];default:return[]}});return W.length>0?W:void 0}var DZ="https://models.dev/api.json",kR=600000,XK=300000,IR=5000,UZ=new Map,H5=new Map,VJ=new Map,FZ=new Map;async function xR(){return W0.getGeneratedProviderModels()}async function gR($,W={},Z={},Q={},J={},j={}){if($==="litellm")return W0.sortModelsByReleaseDate(Q);let X=await xR(),Y=W0.resolveProviderModelCatalogKeys($),V=Object.assign({},...Y.map((G)=>X[G]??{}));if(Boolean(W0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl))return W0.sortModelsByReleaseDate({...J,...j});if($==="openai-codex")return W0.sortModelsByReleaseDate({...W,...W0.filterOpenAICodexModels(Z),...J,...j});if($==="cline-pass"&&Object.keys(Z).length>0)return{...Z,...j};let H=W0.sortModelsByReleaseDate({...V,...W,...Z,...Q,...J});if($==="cline")return W0.sortModelsByReleaseDate({...W0.preferCanonicalModelIds(H,W0.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...j});return W0.sortModelsByReleaseDate({...H,...j})}function mR($,W){let Z=W0.resolveProviderModelCatalogKeys($);return Object.assign({},...Z.map((Q)=>W[Q]??{}))}function _Z($){let W=$?.trim();return W&&W.length>0?W:""}function HJ($){let W=$.apiKey?.trim()||$.accessToken?.trim();return W&&W.length>0?W:void 0}function vR($){let W=2166136261;for(let Z=0;Z<$.length;Z+=1)W^=$.charCodeAt(Z),W+=(W<<1)+(W<<4)+(W<<7)+(W<<8)+(W<<24);return(W>>>0).toString(16)}function cR($,W){return`${$}:${_Z(W.baseUrl)}:${vR(HJ(W)??"")}`}async function fZ($,W,Z=IR){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await fetch($,{...W,signal:Q.signal})}finally{clearTimeout(J)}}function k2($,W,Z){if(Z&&!$.includes(W))$.push(W)}function LZ($,W){let Z=["streaming","tools"];return k2(Z,"images",Boolean(W.supportsImages)),k2(Z,"prompt-cache",Boolean(W.supportsPromptCache)),k2(Z,"reasoning",Boolean(W.supportsReasoning)),{id:$,name:W.name??$,contextWindow:W.contextWindow,maxInputTokens:W.maxInputTokens,maxTokens:W.maxTokens,capabilities:Z,releaseDate:W.releaseDate,status:"active"}}async function uR($,W){let Z=await fZ("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${W}`,"Content-Type":"application/json"}});if(!Z.ok)throw Error(`Baseten model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;if(Y.includes("whisper")||Y.includes("tts")||Y.includes("embedding"))continue;let V=X.supported_features??[];j[Y]=LZ(Y,{name:Y,contextWindow:X.context_length,maxInputTokens:X.context_length,maxTokens:X.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return j}function QK($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let W=Number($);return Number.isFinite(W)?W:void 0}return}async function dR($,W){let Z=await fZ("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":W}});if(!Z.ok)throw Error(`Hicap model refresh failed: HTTP ${Z.status}`);let J=(await Z.json())?.data??[],j={};for(let X of J){let Y=X.id?.trim();if(!Y)continue;j[Y]=LZ(Y,{name:Y,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function lR($,W){let Q=`${(_Z($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await fZ(Q,{method:"GET",headers:{Authorization:`Bearer ${W}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let X=(await J.json())?.data??[],Y={};for(let V of X){let B=V.id?.trim();if(!B)continue;let H=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];k2(F,"tools",H.includes("tools")),k2(F,"reasoning",H.includes("reasoning")),k2(F,"temperature",G.includes("temperature")),k2(F,"images",K.includes("image"));let A={input:QK(V.pricing?.prompt),output:QK(V.pricing?.completion)};Y[B]={id:B,name:V.name??B,description:V.description,contextWindow:V.context_length,maxInputTokens:V.context_length,maxTokens:V.max_completion_tokens,capabilities:F,pricing:A.input!==void 0||A.output!==void 0?A:void 0,status:"active"}}return Y}function pR($){let W=_Z($).replace(/\/+$/,"");if(!W)return"http://localhost:4000";return W.endsWith("/v1")?W.slice(0,-3):W}function rR($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function iR($){let W=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Z=500,Q=W?`: ${W.slice(0,500)}${W.length>500?"...":""}`:"";return`HTTP ${$.status}${Q}`}async function nR($,W){let Z=pR($.baseUrl),Q=[],J=[["x-litellm-api-key",{"x-litellm-api-key":W}],["Authorization",{Authorization:`Bearer ${W}`}]];for(let j of rR(Z))for(let[X,Y]of J)try{let V=await fZ(j,{method:"GET",headers:{accept:"application/json",...Y}});if(V.ok){let H=(await V.json())?.data??[],G={};for(let K of H){let F=K.model_name?.trim(),D=K.litellm_params?.model?.trim()||F;if(!D)continue;let U=K.model_info,f=LZ(D,{name:F??D,maxTokens:U?.max_output_tokens??U?.max_tokens,maxInputTokens:U?.max_input_tokens??U?.max_tokens,supportsImages:U?.supports_vision,supportsPromptCache:U?.supports_prompt_caching,supportsReasoning:U?.supports_reasoning});if(G[D]=f,F)G[F]={...f,id:F,name:F}}return G}Q.push(`${new URL(j).pathname} (${X}): ${await iR(V)}`)}catch(V){let B=V instanceof Error?V.message:String(V);Q.push(`${new URL(j).pathname} (${X}): ${B}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${Q.join("; ")}`)}var YK={baseten:uR,hicap:dR,litellm:nR,poolside:lR},BJ=new Map,AZ=new Map;function aR($,W){return`${$}:${_Z(W.baseUrl)}`}async function oR($,W,Z){let Q=W0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=KZ(Z.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!J)return{};let j=W?.cacheTtlMs??XK,X=aR($,Z),Y=Date.now(),V=BJ.get(X);if(V&&V.expiresAt>Y)return V.data;let B=AZ.get(X);if(B)return B;let H=GZ(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,LZ(F,{name:F})]));return BJ.set(X,{data:K,expiresAt:Y+j}),K}).finally(()=>{AZ.delete(X)});return AZ.set(X,H),H}function sR(){BJ.clear(),AZ.clear()}async function tR($,W){let Z=HJ(W);if(!Z)return{};let Q=YK[$];if(!Q)return{};return Q(W,Z)}function eR($,W,Z){if(!Z)return!1;if(!YK[$])return!1;if(W?.loadPrivateOnAuth===!1)return!1;return Boolean(HJ(Z))}async function $N($,W,Z){let Q=W?.cacheTtlMs??XK,J=cR($,Z),j=Date.now(),X=VJ.get(J);if(X&&X.expiresAt>j)return X.data;let Y=FZ.get(J);if(Y)return Y;let V=tR($,Z).then((B)=>{return VJ.set(J,{data:B,expiresAt:j+Q}),B}).finally(()=>{FZ.delete(J)});return FZ.set(J,V),V}async function WN($){return W0.fetchLiveProviderModels($,globalThis.fetch)}async function Z6($={}){let W=$.url??DZ,Z=$.cacheTtlMs??kR,Q=Date.now(),J=UZ.get(W);if(J&&J.expiresAt>Q)return J.data;let j=H5.get(W);if(j)return j;let X=WN(W).then((Y)=>{return UZ.set(W,{data:Y,expiresAt:Q+Z}),Y}).finally(()=>{H5.delete(W)});return H5.set(W,X),X}function GJ($){if($){UZ.delete($),H5.delete($);return}UZ.clear(),H5.clear()}function KJ(){VJ.clear(),FZ.clear()}function ZN($){return Object.fromEntries(Object.entries($).map(([W,Z])=>[W,{baseUrl:Z.baseUrl,modelId:Z.modelId,capabilities:jK(Z.capabilities)}]))}var G5=ZN(hR());function OZ($){let W=yR($);if(!W)return;return{baseUrl:W.baseUrl||void 0,modelId:W.modelId,knownModels:W.knownModels,capabilities:jK(W.capabilities)}}async function K5($,W,Z){let Q=OZ($);if(!Q)return;try{let J=W?.loadLatestOnInit?await Z6(W):void 0,j=J?mR($,J):{},X=Z&&eR($,W,Z)?await $N($,W,Z):{},V=Boolean(W0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Z??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:Z,B=V?await oR($,W,V).catch(()=>({})):{},H=await gR($,Q.knownModels,j,X,B,Z?.knownModels);return{...Q,knownModels:H}}catch(J){if(W?.failOnError)throw J;if($==="litellm")return{...Q,knownModels:{}};return Q}}var F5=e0.BUILT_IN_PROVIDER,FJ=e0.BUILT_IN_PROVIDER_IDS,AJ=e0.isBuiltInProviderId,Q6=e0.normalizeProviderId,A5=E.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),TZ=E.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),zZ=E.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),qZ=E.object({apiKey:E.string().optional(),accessToken:E.string().optional(),refreshToken:E.string().optional(),expiresAt:E.number().int().positive().optional(),accountId:E.string().optional(),organizationId:E.string().optional(),organizationName:E.string().optional(),memberId:E.string().optional(),metadata:E.record(E.string(),E.unknown()).optional()}),QN=E.enum(["none","low","medium","high","xhigh"]),MZ=E.object({enabled:E.boolean().optional(),effort:QN.optional(),budgetTokens:E.number().int().positive().optional()}),RZ=E.object({accessKey:E.string().optional(),secretKey:E.string().optional(),sessionToken:E.string().optional(),region:E.string().optional(),profile:E.string().optional(),authentication:E.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:E.boolean().optional(),useCrossRegionInference:E.boolean().optional(),useGlobalInference:E.boolean().optional(),endpoint:E.string().url().optional(),customModelBaseId:E.string().optional()}),NZ=E.object({projectId:E.string().optional(),region:E.string().optional()}),EZ=E.object({apiVersion:E.string().optional(),useIdentity:E.boolean().optional()}),wZ=E.object({clientId:E.string().optional(),clientSecret:E.string().optional(),tokenUrl:E.string().url().optional(),resourceGroup:E.string().optional(),deploymentId:E.string().optional(),useOrchestrationMode:E.boolean().optional(),api:E.enum(["orchestration","foundation-models"]).optional(),defaultSettings:E.record(E.string(),E.unknown()).optional()}),CZ=E.object({mode:E.enum(["internal","external"]).optional(),usePromptCache:E.boolean().optional()}),PZ=E.object({loadLatestOnInit:E.boolean().optional(),loadPrivateOnAuth:E.boolean().optional(),url:E.string().url().optional(),cacheTtlMs:E.number().int().positive().optional(),failOnError:E.boolean().optional()}),k$=E.object({provider:A5,apiKey:E.string().optional(),auth:qZ.optional(),model:E.string().optional(),protocol:TZ.optional(),client:zZ.optional(),routingProviderId:A5.optional(),maxTokens:E.number().int().positive().optional(),contextWindow:E.number().int().positive().optional(),baseUrl:E.string().url().optional(),headers:E.record(E.string(),E.string()).optional(),timeout:E.number().int().positive().optional(),reasoning:MZ.optional(),aws:RZ.optional(),gcp:NZ.optional(),azure:EZ.optional(),sap:wZ.optional(),oca:CZ.optional(),region:E.string().optional(),apiLine:E.enum(["china","international"]).optional(),capabilities:E.array(E.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:PZ.optional()});function SZ($){return k$.parse($)}function bZ($){return k$.safeParse($)}function JN($){return $.protocol==="openai-responses"||$.client==="openai"}function $1($,W={}){let Z=$.provider,Q=Q6(Z),J=W.includeKnownModels!==!1,j=$.reasoning?.effort||"none",X=j==="none"?void 0:j,Y=G5[Q],V=Object.assign({},...e0.resolveProviderModelCatalogKeys(Q).map((D)=>e0.getGeneratedModelsForProvider(D))),B=Object.keys(V)[0],H=M8(Q,$),G=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?U9:D9:Y?.baseUrl),K=$.routingProviderId??(JN($)&&Q!==F5.OPENAI_NATIVE?F5.OPENAI_NATIVE:void 0),F=J?Y?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Z,clientType:$.client,routingProviderId:K,modelId:$.model??Y?.modelId??B??"default",...J?{knownModels:F}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:X,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??Y?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(A).filter(([D,U])=>U!==void 0))}function UJ($){let W=SZ($);return $1(W)}function DJ($){let W=bZ($);if(W.success)return{success:!0,config:$1(W.data)};return{success:!1,error:W.error}}var J6=k$;var yZ=I$.object({settings:k$,updatedAt:I$.string().datetime(),tokenSource:I$.enum(["manual","oauth","migration"]).default("manual")}),j6=I$.object({version:I$.literal(1),lastUsedProvider:I$.string().min(1).optional(),providers:I$.record(I$.string(),yZ)});function x$(){return{version:1,providers:{}}}_1();var fK={};w(fK,{InMemoryWorkspaceManager:()=>Y6});import{upsertWorkspaceInfo as YN,WorkspaceManifestSchema as OJ}from"@cline/shared";var _K={};w(_K,{withSessionGitMetadata:()=>kZ,readSessionGitMetadata:()=>UK,readGitWorkspaceState:()=>fJ,normalizeWorkspacePath:()=>E1,hasCurrentSessionGitMetadata:()=>_J,generateWorkspaceInfoWithDiagnostics:()=>U5,generateWorkspaceInfo:()=>X6,buildWorkspaceMetadataWithInfo:()=>LJ,buildWorkspaceMetadata:()=>D5});import{basename as jN,resolve as XN}from"node:path";import{performance as GK}from"node:perf_hooks";import{processWorkspaceInfo as FK}from"@cline/shared";import AK from"simple-git";function UK($){let W=$?.git;if(!W||typeof W!=="object"||Array.isArray(W))return{};let Z=W;return{...typeof Z.url==="string"&&Z.url.trim()?{url:Z.url.trim()}:{},...typeof Z.branch==="string"&&Z.branch.trim()?{branch:Z.branch.trim()}:{}}}function kZ($,W){let Z={...$??{}};if(!W.url&&!W.branch)return delete Z.git,Object.keys(Z).length>0?Z:void 0;let J={...Z.git&&typeof Z.git==="object"&&!Array.isArray(Z.git)?Z.git:{}};if(W.url)J.url=W.url;else delete J.url;if(W.branch)J.branch=W.branch;else delete J.branch;return Z.git=J,Z}function _J($,W){let Z=UK($);return Z.url===W.url&&Z.branch===W.branch}function DK($){let W=$.find(({name:Z})=>Z==="origin")??$[0];return(W?.refs.fetch||W?.refs.push)?.trim()||void 0}function E1($){return XN($)}async function X6($){return(await U5($)).info}function KK($){let W=$ instanceof Error?$.message:String($);return/unknown revision|ambiguous argument|does not have any commits yet/i.test(W)}function hZ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function U5($){let W=E1($),Z={rootPath:W,hint:jN(W)},Q={},J;try{let j=AK({baseDir:W});if(!await j.checkIsRepo())return{info:Z,vcsType:"none",gitState:Q};try{let Y=await j.getRemotes(!0);if(Y.length>0){let V=Y.map((H)=>{let G=H.refs.fetch||H.refs.push;return`${H.name}: ${G}`});Z.associatedRemoteUrls=V;let B=DK(Y);if(B)Q.url=B}}catch(Y){J??=hZ(Y)}try{let Y=(await j.revparse(["HEAD"])).trim();if(Y.length>0)Z.latestGitCommitHash=Y}catch(Y){if(!KK(Y))J??=hZ(Y)}try{let Y=(await j.branch()).current.trim();if(Y.length>0)Z.latestGitBranchName=Y,Q.branch=Y}catch(Y){if(!KK(Y))J??=hZ(Y)}return{info:Z,vcsType:"git",gitState:Q,error:J}}catch(j){return{info:Z,vcsType:"none",gitState:Q,error:hZ(j)}}}async function fJ($){try{let W=AK({baseDir:E1($)});if(!await W.checkIsRepo())return{};let[Z,Q]=await Promise.all([W.getRemotes(!0),W.branch()]),J=DK(Z),j=Q.current.trim();return{...J?{url:J}:{},...j?{branch:j}:{}}}catch{return}}async function D5($){let W=await X6($);return FK(W)}async function LJ($){let W=GK.now(),Z=await U5($),Q=GK.now()-W,J=Z.info;return{workspaceInfo:J,workspaceMetadata:FK(J),durationMs:Q,vcsType:Z.vcsType,gitState:Z.gitState,initError:Z.error}}class Y6{manifest;listeners=new Set;constructor($){this.manifest=OJ.parse($??{workspaces:{}})}async addWorkspacePath($){let W=await X6($);return this.manifest=YN(this.manifest,W),this.emit({type:"workspace_added",workspace:W}),W}async switchWorkspace($){let W=E1($),Z=this.manifest.workspaces[W];if(Z)return this.manifest=OJ.parse({...this.manifest,currentWorkspacePath:W}),this.emit({type:"workspace_switched",workspace:Z}),Z;let Q=await this.addWorkspacePath(W);return this.manifest=OJ.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let W=E1($);return this.manifest.workspaces[W]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let W of this.listeners)W($)}}U0();import{createHash as VN}from"node:crypto";var LK=new Set,OK=new Set;function BN($){return VN("sha256").update($).digest("hex")}function HN($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function TK($){if(!$.telemetry)return;let W=BN($.rootPath),Z=$.rootCount??1;if(!LK.has(W))LK.add(W),iW($.telemetry,{root_count:Z,vcs_types:HN($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!OK.has(W)){OK.add(W);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",nW($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:Z})}}function FN($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function AN($,W,Z){if(W.length>0)for(let j of W)Z?.log(j.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(FN).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Z?.log(`Some plugins failed to initialize. ${Q}${J}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Z?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function UN($,W){let Z=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!Z&&!Q)return W;return{...W??{},...Z?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function zK($,W){return KN($,W)}function DN($){let W=0;for(let Z of $??[]){if(Z.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0)?.kind==="recovery_notice")continue;W+=1}return W}function _N($,W,Z,Q,J,j){let X=Q.getProviderSettings($.providerId),Y=J||X?.modelCatalog?{...J??{},...X?.modelCatalog??{}}:void 0,V=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,B=GN({providerId:$.providerId,sessionId:W,source:Z,defaultSource:K0.CLI,client:{name:$.extensionContext?.client?.name,version:$.extensionContext?.client?.version,versionHeaderFallback:$.headers?.["X-CLIENT-VERSION"],platform:$.extensionContext?.client?.platform,platformVersion:$.extensionContext?.client?.platformVersion,isMultiRoot:$.extensionContext?.client?.isMultiRoot},coreVersion:p8,openAiCodex:{accountId:V?.accountId??X?.auth?.accountId,accessToken:V?.accessToken??$.apiKey??X?.auth?.accessToken??X?.apiKey,userAgentVersion:process.env.npm_package_version},headers:{stored:X?.headers,config:$.headers,session:V?.headers}}),H={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:void 0,reasoning:UN($,X?.reasoning),modelCatalog:Y},G={...$1(H),...V??{}};if(B)G.headers=B;if($.knownModels)G.knownModels=$.knownModels;if($.extensionContext)G.extensionContext=$.extensionContext;let F=$.fetch??G.fetch??j;if(F)G.fetch=F;return G}async function qK($){let{input:W,sessionId:Z,providerSettingsManager:Q,defaultTelemetry:J,defaultCapabilities:j,defaultToolPolicies:X,defaultFetch:Y,onPluginEvent:V,onTeamEvent:B,createSubAgentLifecycleCallbacks:H,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,D=t1(W.config),{modelCatalogDefaults:U,userInstructionService:f,configExtensions:_,onTeamRestored:R,...T}=K??{},O=Object.keys(T).length>0?T:void 0,{workspaceInfo:L,workspaceMetadata:C,gitState:N,durationMs:p,vcsType:k,initError:P}=await LJ(D),r=O?.extensionContext,c={...r??{},workspace:{...L,...r?.workspace??{}},session:{...r?.session??{},sessionId:Z},logger:r?.logger??O?.logger,telemetry:r?.telemetry??O?.telemetry??J};TK({telemetry:c.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:k,durationMs:p,initError:P,featureFlagEnabled:!0});let g1=W6({cwd:W.config.cwd,workspacePath:D,rootSessionId:Z,logger:O?.logger,workspaceInfo:L}),Z2=FG(O?.hooks)?void 0:$6({rootSessionId:Z,workspacePath:D,workspaceInfo:L}),A8=h2([O?.hooks,Z2]),g0;if(zK(_,"plugins"))try{g0=await s8({pluginPaths:O?.pluginPaths,workspacePath:D,cwd:W.config.cwd,onEvent:V,providerId:W.config.providerId,modelId:W.config.modelId,workspaceInfo:L,session:c.session,client:c.client,user:c.user,logger:c.logger,telemetry:c.telemetry,automation:c.automation}),AN(g0.failures,g0.warnings,O?.logger)}catch($4){let D8=$4 instanceof Error?$4.message:String($4);O?.logger?.log?.(`plugin loading failed; continuing without plugins (${D8})`)}let r0=k3(g1?[g1]:void 0,k3(O?.extensions,u9(g0?.extensions))),U8=zK(_,"plugins")?$$(g0?.pluginPaths??[]):void 0,S0={...W.config,...O??{},sessionId:Z,hooks:A8,extensions:r0,extensionContext:c,telemetry:c.telemetry},G1=_N(S0,Z,W.source,Q,U,Y),y0=h2([S0.hooks,S0.checkpoint?.enabled===!0?rG({cwd:S0.cwd,sessionId:Z,logger:S0.logger,createCheckpoint:S0.checkpoint?.createCheckpoint,initialRunCount:DN(W.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),O0={...S0,providerConfig:G1,workspaceMetadata:C,hooks:y0},v=W.toolPolicies??S0.toolPolicies??X,i0=w0(j,W.capabilities),b=i0?.requestToolApproval,$0=i0?.toolExecutors,q0=H?.(O0),h0=new Y6({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:W,config:O0,providerConfig:G1,workspaceMetadata:C,workspaceInfo:L,gitState:N,extensions:r0,hooks:y0,toolPolicies:v,requestToolApproval:b,pluginSandboxShutdown:g0?.shutdown,runtimeBuilderInput:{config:O0,hooks:y0,extensions:r0,onTeamEvent:B,createSpawnTool:G,onTeamRestored:R,onSubAgentEvent:q0?.onSubAgentEvent,onSubAgentStart:q0?.onSubAgentStart,onSubAgentEnd:q0?.onSubAgentEnd,userInstructionService:f,pluginSkillDirectories:U8,configExtensions:_,toolExecutors:$0,toolPolicies:v,workspaceManager:h0,logger:O0.logger,telemetry:O0.telemetry,requestToolApproval:b}}}import{existsSync as IZ,mkdirSync as fN,readdirSync as LN,rmdirSync as ON,rmSync as TN,unlinkSync as zN}from"node:fs";import{dirname as MK,join as _5}from"node:path";function X0(){return new Date().toISOString()}function f5($){if(!$||!IZ($))return;try{zN($)}catch{}}function qN($){let W=u8($);if(W)return{rootSessionId:W.rootSessionId,fileStem:`${W.agentId}__${W.teamTaskId}`};let Z=i4($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:Z.agentId};return{rootSessionId:$,fileStem:$}}class TJ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return _5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let W=this.sessionArtifactsDir($);if(!IZ(W))fN(W,{recursive:!0});return W}sessionMessagesPath($){return _5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionCompactionPath($){return _5(this.sessionArtifactsDir($),`${$}.compaction.json`)}sessionManifestPath($,W=!1){let Z=W?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return _5(Z,`${$}.json`)}removeSessionDirIfEmpty($){let W=this.sessionArtifactsDir($),Z=this.ensureSessionsDir();while(W.startsWith(Z)&&W!==Z){if(!IZ(W)){W=MK(W);continue}try{if(LN(W).length>0)break;ON(W)}catch{break}W=MK(W)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!IZ($))return;try{TN($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,W,Z){let{rootSessionId:Q,fileStem:J}=qN($),j=this.sessionArtifactsDir(Q);return{messagesPath:_5(j,`${J}.messages.json`)}}}import{resolveDocumentsExtensionPath as MN}from"@cline/shared/storage";U0();function RK($,W,Z,Q,J){if(Z)oW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});else aW($.telemetry,{ulid:W,apiProvider:$.providerId,...J});RN($.telemetry,{workspacePath:Q})}function RN($,W){let Z=MN("Hooks"),Q=y$(W.workspacePath),J=new Map;for(let j of Q){let X=j.hookEventName??"unknown",Y=J.get(X)??{global:0,workspace:0};if(j.path===Z||j.path.startsWith(`${Z}/`))Y.global+=1;else Y.workspace+=1;J.set(X,Y)}for(let[j,X]of J.entries())X9($,j,X.global,X.workspace)}function NK($,W){for(let Z of W.mentions)J9($,Z,W.matchedFiles.includes(Z)?1:0,"file",!W.matchedFiles.includes(Z));for(let Z of W.matchedFiles)Z9($,"file",Z.length);for(let Z of W.ignoredMentions)Q9($,"file","not_found",Z)}var Mf={};w(Mf,{ProviderSettingsManager:()=>B1});import{chmodSync as Nf,existsSync as IY,mkdirSync as Dv,readFileSync as _v,renameSync as fv,rmSync as Lv,writeFileSync as Ov}from"node:fs";import{basename as Ef,dirname as xY}from"node:path";import{resolveProviderSettingsPath as Tv}from"@cline/shared/storage";var q={};w(q,{writeModelsFileSync:()=>xW,writeHubDiscovery:()=>GQ,writeGlobalSettings:()=>R1,withHubStartupLock:()=>KQ,verifyHubConnection:()=>C1,updateMcpSettingsFileSync:()=>f1,updateMcpSettingsFile:()=>A6,updateMcpServerOAuthStateAsync:()=>I5,updateMcpServerOAuthState:()=>v2,updateLocalProvider:()=>_7,uninstallPlugin:()=>CW,uninstallMarketplaceSkill:()=>Z7,uninstallMarketplacePlugin:()=>Q7,uninstallMarketplaceMcpServerFromSettings:()=>$7,uninstallMarketplaceEntry:()=>oX,truncateNotificationBody:()=>LW,truncateCommandOutput:()=>G2,toggleDisabledTool:()=>v9,toTeamProgressLifecycleEvent:()=>C6,toProviderConfig:()=>$1,toHubStatusUrl:()=>Kj,toHubHealthUrl:()=>FQ,toHookConfigFileName:()=>V5,syncStoredProviderRegistration:()=>BY,syncPluginMcpServersToSettings:()=>EW,summarizeUsageFromMessages:()=>l8,stripUtf8Bom:()=>Fv,stopLocalHubServerGracefully:()=>Mj,startLocalOAuthServer:()=>F1,startHubWebSocketServer:()=>V8,startHubServer:()=>W_,startClineDeviceAuth:()=>v7,splitCoreSessionConfig:()=>d5,spawnDetachedHubServerWithRetry:()=>T6,spawnDetachedHubServer:()=>fj,setTelemetryOptOutGlobally:()=>QH,setSdkLogger:()=>y7,setMcpServerDisabled:()=>g2,setDisabledTools:()=>_3,setDisabledPlugin:()=>GH,setCompactionStrategyGlobally:()=>YH,setAutoUpdateEnabledGlobally:()=>jH,sendHubCommand:()=>nU,sdkDebug:()=>s,saveProviderOAuthCredentials:()=>j2,saveLocalProviderSettings:()=>DY,saveLocalProviderOAuthCredentials:()=>OY,sanitizeSessionToken:()=>E2,safeParseSettings:()=>bZ,safeCreateProviderConfig:()=>DJ,runSubprocessEvent:()=>I6,runHook:()=>g6,reviveTeamStateDates:()=>a9,restartLocalHubIfIdleAfterStartupTimeout:()=>fQ,resolveWorkspaceHubOwnerContext:()=>zA,resolveWorkflowsConfigSearchPaths:()=>C5,resolveSkillsConfigSearchPaths:()=>E5,resolveSharedHubOwnerContext:()=>u0,resolveSessionBackend:()=>pj,resolveRulesConfigSearchPaths:()=>w5,resolveProviderConfig:()=>K5,resolveProviderApiKeyFromSettings:()=>i7,resolveProductionHubOwnerContext:()=>X1,resolvePluginSkillDirectoriesFromPaths:()=>$$,resolvePluginConfigSearchPaths:()=>J5,resolveModelsRegistryPath:()=>x1,resolveMcpServerRegistrations:()=>W1,resolveMarketplaceMcpServerName:()=>SW,resolveLocalClineAuthToken:()=>zY,resolveHubUrl:()=>WX,resolveHubOwnerContext:()=>j$,resolveHubEndpointOptions:()=>j1,resolveHubBuildId:()=>HQ,resolveHooksConfigSearchPaths:()=>X5,resolveDisabledToolNames:()=>N1,resolveDisabledPluginPaths:()=>m4,resolveDefaultMcpSettingsPath:()=>Q0,resolveDefaultHubPort:()=>O6,resolveDefaultHubPathname:()=>_j,resolveDefaultHubHost:()=>Dj,resolveCoreSelectedToolIds:()=>s9,resolveCoreDistinctId:()=>d0,resolveCompatibleLocalHubUrl:()=>ZW,resolveClineDir:()=>fA,resolveClineDataDir:()=>n2,resolveAndLoadAgentPlugins:()=>s8,resolveAgentPluginPaths:()=>e1,requestHubShutdown:()=>WW,requestDesktopToolApproval:()=>hX,removePluginMcpServersFromSettings:()=>wW,rememberRecoverableLocalHubUrl:()=>p$,registerRemoteConfigSessionBlobUpload:()=>pQ,registerMcpServersFromSettingsFile:()=>c2,registerDisposable:()=>Gv,refreshProviderModelsFromSource:()=>_Y,refreshOpenAICodexToken:()=>A9,refreshOcaToken:()=>f9,refreshClineToken:()=>K9,readSessionCheckpointHistory:()=>Q8,readRemoteConfigSessionBlobUploadMetadata:()=>RX,readModelsFileSync:()=>t6,readHubDiscovery:()=>L0,readGlobalSettings:()=>R0,readCompactionStrategyGlobally:()=>XH,readBearerToken:()=>gQ,projectSessionCompactionState:()=>X2,probeHubServer:()=>X$,probeHubConnection:()=>iU,prewarmFileIndex:()=>y9,prewarmDetachedHubServer:()=>UQ,prepareRemoteConfigCoreIntegration:()=>EX,parseWorkflowConfigFromMarkdown:()=>N5,parseUserCommandEnvelope:()=>Hv,parseSkillConfigFromMarkdown:()=>M5,parseSettings:()=>SZ,parseSessionCompactionState:()=>A1,parseRuleConfigFromMarkdown:()=>R5,parsePluginSource:()=>K7,parseMcpInstallArgs:()=>NW,parseHookEventPayload:()=>x6,parseConfiguredAgentConfig:()=>XW,normalizeWorkspacePath:()=>E1,normalizeUserInput:()=>Bv,normalizeSdkError:()=>Vv,normalizeRuntimeCapabilities:()=>w0,normalizeProviderId:()=>Q6,normalizeOAuthProvider:()=>fY,normalizeHubWebSocketUrl:()=>r$,noopBasicLogger:()=>Yv,migrateLegacyProviderSettings:()=>uW,mergeRulesForSystemPrompt:()=>K6,mergeAgentHooks:()=>h2,marketplaceEntryKey:()=>aX,markLocalProviderEnabled:()=>FY,makeTeamTaskSubSessionId:()=>r4,makeSubSessionId:()=>c8,loginOpenAICodex:()=>X4,loginOcaOAuth:()=>H4,loginLocalProvider:()=>LY,loginClineOAuth:()=>J4,loginAndSaveProviderOAuthCredentials:()=>K4,loginAndSaveLocalProviderOAuthCredentials:()=>TY,loadOpenTelemetryAdapter:()=>hm,loadMcpSettingsFile:()=>x2,loadLlmsConfigFromFile:()=>yY,loadConfiguredAgentConfigs:()=>N6,loadAgentPluginsFromPathsWithDiagnostics:()=>P2,loadAgentPluginsFromPaths:()=>ZZ,loadAgentPluginFromPath:()=>Z5,listSessionHistoryFromBackend:()=>Vj,listPluginToolsWithDiagnostics:()=>QQ,listPluginTools:()=>m5,listMcpServerOAuthStatuses:()=>x5,listLocalProviders:()=>AY,listHookConfigFiles:()=>y$,isToolDisabledGlobally:()=>VH,isTelemetryOptedOutGlobally:()=>m9,isSessionNotFoundError:()=>J$,isRuleEnabled:()=>rZ,isPluginDisabledGlobally:()=>HH,isOfficialPluginSlug:()=>G7,isOAuthProvider:()=>L$,isMarketplaceSkillInstalled:()=>W7,isLocalHubOrigin:()=>MX,isLocalHubHostName:()=>mQ,isHubReconnectableTransportError:()=>zj,isHubCommandTimeoutError:()=>_Q,isDiscoveryFilePresent:()=>OA,isClinePassLimitMessage:()=>nm,isClinePassLimitError:()=>im,isClineOrgIndividualInferenceSubscriptionMessage:()=>rm,isClineOrgIndividualInferenceSubscriptionError:()=>pm,isClineNotSubscribedMessage:()=>lm,isClineNotSubscribedError:()=>dm,isClineAccountActionRequest:()=>xZ,isBuiltInProviderId:()=>AJ,isAutoUpdateEnabledGlobally:()=>JH,installPlugin:()=>ZY,installMcpServer:()=>kX,identifyAccount:()=>K1,hashSecret:()=>M0,hasMcpSettingsFile:()=>Z$,getValidOpenAICodexCredentials:()=>Y4,getValidOcaCredentials:()=>G4,getValidClineCredentials:()=>j4,getProviderOAuthCredentialsFromSettings:()=>F4,getProviderConfigFields:()=>qY,getProviderConfig:()=>OZ,getProviderAuthStorageId:()=>r7,getProviderAuthHandler:()=>B0,getPersistedProviderApiKey:()=>M8,getMcpServerOAuthState:()=>m2,getMarketplaceSkillCandidates:()=>bW,getLocalProviderModels:()=>UY,getLiveModelsCatalog:()=>Z6,getGlobalMarketplaceSkillPaths:()=>yW,getFileIndex:()=>i1,getCurrentContextSize:()=>m3,getCoreHeadlessToolNames:()=>p4,getCoreDefaultEnabledToolIds:()=>o9,getCoreBuiltinToolCatalog:()=>R2,getCoreAcpToolNames:()=>t9,getClinePassSubscriptionUrl:()=>um,getClineOrgIndividualInferenceSubscriptionMessage:()=>cm,getClineNotSubscribedMessage:()=>vm,getClineDefaultSystemPrompt:()=>am,generateWorkspaceInfoWithDiagnostics:()=>U5,generateWorkspaceInfo:()=>X6,formatRulesForSystemPrompt:()=>G6,formatProviderOAuthApiKey:()=>n7,formatDisplayUserInput:()=>Xv,findInstalledGlobalMarketplaceSkillName:()=>hW,findCheckpointForRun:()=>h6,filterExtensionToolRegistrations:()=>u9,filterDisabledTools:()=>a1,filterDisabledPluginPaths:()=>c9,fetchClineRecommendedModels:()=>SY,extractClinePassLimitMessage:()=>mm,executeClineAccountAction:()=>gZ,ensureHubWebSocketServer:()=>vQ,ensureHubServer:()=>Z_,ensureDetachedHubServer:()=>wA,ensureCustomProvidersLoadedSync:()=>vW,ensureCustomProvidersLoaded:()=>cW,ensureCompatibleLocalHubUrl:()=>s2,enrichPromptWithMentions:()=>y8,emptyWorkspaceManifest:()=>Qv,emptyStoredProviderSettings:()=>x$,discoverPluginModulePaths:()=>j5,disablePluginMcpServersInSettings:()=>mX,deriveSubsessionStatus:()=>n4,deleteLocalProvider:()=>f7,defineLlmsConfig:()=>bY,createWorkflowsConfigDefinition:()=>b5,createUserInstructionConfigService:()=>g$,createToolPoliciesWithPreset:()=>k9,createTool:()=>Zv,createTeamName:()=>nQ,createSubprocessHooks:()=>CQ,createSpawnAgentTool:()=>P$,createSkillsConfigDefinition:()=>P5,createShellTool:()=>y4,createShellExecutor:()=>K2,createSessionHost:()=>b6,createSessionCompactionState:()=>R8,createRuntimeHost:()=>b6,createRulesConfigDefinition:()=>S5,createRemoteConfigSessionMessagesArtifactUploader:()=>NX,createProviderConfig:()=>UJ,createOpenTelemetryTelemetryService:()=>_W,createOAuthClientCallbacks:()=>V6,createMcpTools:()=>f6,createLocalHubScheduleRuntimeHandlers:()=>cQ,createLlmsSdk:()=>kY,createInitialAccumulatedUsage:()=>z0,createInMemoryHubOwnerContext:()=>LA,createHubServerUrl:()=>L1,createHubAuthToken:()=>BQ,createHookConfigFileHooks:()=>B5,createHookConfigFileExtension:()=>W6,createHookAuditHooks:()=>$6,createEditorExecutor:()=>D2,createDisabledMcpToolPolicy:()=>g5,createDisabledMcpToolPolicies:()=>ZQ,createDelegatedAgentConfigProvider:()=>w$,createDelegatedAgent:()=>C$,createDefaultToolsWithPreset:()=>I9,createDefaultTools:()=>M$,createDefaultShellExecutor:()=>x4,createDefaultMcpServerClientFactory:()=>D6,createDefaultExecutors:()=>h8,createCoreSettingsService:()=>d2,createCoreSessionSnapshot:()=>P1,createContributionRegistry:()=>Wv,createContextCompactionPrepareTurn:()=>z4,createConfiguredTelemetryService:()=>G$,createConfiguredTelemetryHandle:()=>a$,createConfiguredAgentTools:()=>E6,createCompactionStateAwarePrepareTurn:()=>q4,createClineTelemetryServiceMetadata:()=>$v,createClineTelemetryServiceConfig:()=>em,createCheckpointComparePlan:()=>RQ,createBuiltinTools:()=>N2,createApplyPatchExecutor:()=>U2,createAgentTeamsTools:()=>M2,createAgentRuntime:()=>Uv,createAgentHooksExtension:()=>t8,connectToHub:()=>bQ,computePatchChanges:()=>S8,completeClineDeviceAuth:()=>c7,compareCheckpointToWorkspace:()=>FW,collectPluginMcpOAuthCandidates:()=>F7,clearPrivateModelsCatalogCache:()=>KJ,clearLiveModelsCatalogCache:()=>GJ,clearHubDiscovery:()=>c0,captureWorkspacePathResolved:()=>QV,captureWorkspaceInitialized:()=>iW,captureWorkspaceInitError:()=>nW,captureToolUsage:()=>f8,captureTokenUsage:()=>sW,captureTaskRestarted:()=>oW,captureTaskCreated:()=>aW,captureTaskCompleted:()=>W4,captureSubagentExecution:()=>Q4,captureSkillUsed:()=>eW,captureSdkError:()=>tm,captureProviderConfigured:()=>jV,captureProviderApiError:()=>Z4,captureModeSwitch:()=>tW,captureMistakeLimitReached:()=>W9,captureMentionUsed:()=>Z9,captureMentionSearchResults:()=>J9,captureMentionFailed:()=>Q9,captureHookDiscovery:()=>X9,captureExtensionActivated:()=>ZV,captureDiffEditFailure:()=>$9,captureConversationTurnEvent:()=>_8,captureCompactionSkipped:()=>V9,captureCompactionExecuted:()=>Y9,captureAuthSucceeded:()=>c1,captureAuthStarted:()=>v1,captureAuthLoggedOut:()=>D$,captureAuthFailed:()=>u1,captureAgentUnexpectedReasoningTokens:()=>WV,captureAgentTeamCreated:()=>j9,captureAgentCreated:()=>_$,buildWorkspaceMetadata:()=>D5,buildTeamProgressSummary:()=>w6,buildSdkErrorProperties:()=>om,buildRemoteConfigSessionBlobUploadMetadata:()=>dQ,buildMcpInstallTransport:()=>aQ,buildDelegatedAgentConfig:()=>z2,buildConnectionUpdate:()=>R3,buildConfiguredAgentToolName:()=>YW,buildConfiguredAgentToolDescriptors:()=>VW,buildCheckpointWorkspaceDiff:()=>NQ,bootstrapAgentTeams:()=>v8,authorizeMcpServerOAuth:()=>tZ,addLocalProvider:()=>KY,accumulateUsageTotals:()=>f0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q5,UnifiedConfigFileWatcher:()=>I2,ToolPresets:()=>t0,TelemetryService:()=>c6,TelemetryLoggerSink:()=>DW,TEAM_TOOL_NAMES:()=>m8,SubprocessSandbox:()=>n8,StructuredCommandInputSchema:()=>B2,StoredProviderSettingsSchema:()=>j6,StoredProviderSettingsEntrySchema:()=>yZ,SqliteTeamStore:()=>B8,SqliteSessionStore:()=>b1,SessionVersioningService:()=>t$,SessionVersioningError:()=>p0,SessionSource:()=>K0,SessionNotFoundError:()=>Q$,SapSettingsSchema:()=>wZ,SKILLS_CONFIG_DIRECTORY_NAME:()=>z5,SESSION_STATUSES:()=>a4,SESSION_NOT_FOUND_ERROR_CODE:()=>l2,SDK_ERROR_TELEMETRY_EVENT:()=>Kv,RpcClineAccountService:()=>O5,RemoteRuntimeHost:()=>M6,ReasoningSettingsSchema:()=>MZ,RULES_CONFIG_DIRECTORY_NAME:()=>pZ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>lQ,ProviderSettingsSchema:()=>k$,ProviderSettingsManager:()=>B1,ProviderProtocolSchema:()=>TZ,ProviderIdSchema:()=>A5,ProviderClientSchema:()=>zZ,PatchActionType:()=>A2,OpenTelemetryProvider:()=>u6,OcaSettingsSchema:()=>CZ,OPENAI_COMPATIBLE_PROVIDERS:()=>G5,NodeHubClient:()=>O1,NoOpFeatureFlagsProvider:()=>Z8,NativeHubTransportAdapter:()=>MW,ModelCatalogSettingsSchema:()=>PZ,McpSettingsUpdateSkippedError:()=>F6,McpSettingsMutatorPurityError:()=>m$,McpSettingsLockTimeoutError:()=>v$,MAX_COMMAND_OUTPUT_CHARS:()=>l1,LocalRuntimeHost:()=>k1,Llms:()=>km,InMemoryWorkspaceManager:()=>Y6,InMemoryMcpManager:()=>u2,HubUIClient:()=>JX,HubTransportError:()=>k0,HubSessionClient:()=>QX,HubServerTransport:()=>l6,HubScheduleService:()=>v6,HubScheduleCommandService:()=>m6,HubRuntimeHost:()=>Y$,HubCommandError:()=>z6,HookEventPayloadSchema:()=>wQ,HookEventNameSchema:()=>EQ,HookConfigFileName:()=>e8,HOOK_CONFIG_FILE_EVENT_MAP:()=>Y5,HOOKS_CONFIG_DIRECTORY_NAME:()=>VZ,GlobalSettingsSchema:()=>g4,GcpSettingsSchema:()=>NZ,FileTeamPersistenceStore:()=>T7,FeatureFlagsService:()=>W8,FeatureFlagDefaultValue:()=>jv,FEATURE_FLAGS:()=>Jv,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>E7,DefaultToolNames:()=>T0,DefaultRuntimeBuilder:()=>i6,DefaultLlmsSdk:()=>lW,DEFAULT_MODELS_CATALOG_URL:()=>DZ,DEFAULT_HUB_PORT:()=>Aj,DEFAULT_HUB_PATHNAME:()=>Uj,DEFAULT_HUB_HOST:()=>Fj,CoreSettingsService:()=>c$,CoreSessionService:()=>h1,ContributionRegistry:()=>sm,CommandExitError:()=>p1,ClinePassLimitError:()=>gm,ClineOrgIndividualInferenceSubscriptionError:()=>xm,ClineNotSubscribedError:()=>Im,ClineCore:()=>AW,ClineAccountService:()=>L5,ChatViewStateSchema:()=>CY,ChatSummarySchema:()=>N7,ChatSessionStatusSchema:()=>q7,ChatSessionConfigSchema:()=>z7,ChatMessageSchema:()=>R7,ChatMessageRoleSchema:()=>M7,CORE_TELEMETRY_EVENTS:()=>m,CORE_BUILD_VERSION:()=>dW,BrowserWebSocketHubAdapter:()=>qW,BUILT_IN_PROVIDER_IDS:()=>FJ,BUILT_IN_PROVIDER:()=>F5,AzureSettingsSchema:()=>EZ,AwsSettingsSchema:()=>RZ,AuthSettingsSchema:()=>qZ,AgentTeamsRuntime:()=>$8,AgentTeam:()=>S6,Agent:()=>Av,ALL_DEFAULT_TOOL_NAMES:()=>O$});M(q,A20);import*as km from"@cline/llms";import{ClineNotSubscribedError as Im,ClineOrgIndividualInferenceSubscriptionError as xm,ClinePassLimitError as gm,extractClinePassLimitMessage as mm,getClineNotSubscribedMessage as vm,getClineOrgIndividualInferenceSubscriptionMessage as cm,getClinePassSubscriptionUrl as um,isClineNotSubscribedError as dm,isClineNotSubscribedMessage as lm,isClineOrgIndividualInferenceSubscriptionError as pm,isClineOrgIndividualInferenceSubscriptionMessage as rm,isClinePassLimitError as im,isClinePassLimitMessage as nm}from"@cline/llms";import{buildClineSystemPrompt as am,buildSdkErrorProperties as om,ContributionRegistry as sm,captureSdkError as tm,createClineTelemetryServiceConfig as em,createClineTelemetryServiceMetadata as $v,createContributionRegistry as Wv,createTool as Zv,emptyWorkspaceManifest as Qv,FEATURE_FLAGS as Jv,FeatureFlagDefaultValue as jv,formatDisplayUserInput as Xv,noopBasicLogger as Yv,normalizeSdkError as Vv,normalizeUserInput as Bv,parseUserCommandEnvelope as Hv,registerDisposable as Gv,SDK_ERROR_TELEMETRY_EVENT as Kv,stripUtf8Bom as Fv}from"@cline/shared";import"@cline/shared/storage";var wK={};w(wK,{isClineAccountActionRequest:()=>xZ,executeClineAccountAction:()=>gZ,RpcClineAccountService:()=>O5,ClineAccountService:()=>L5});function NN($){if(typeof $!=="object"||$===null||!("error"in $))return;let W=$.error;return typeof W==="string"&&W.trim()?W:void 0}function EK($,W,Z){let Q=NN(Z);if(Q)return Q;let J=W.trim();if(J){let j=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class L5{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let W=$.apiBaseUrl.trim();if(!W)throw Error("apiBaseUrl is required");this.apiBaseUrl=W,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let W=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(W)}/balance`)}async fetchUsageTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/usages`)).items??[]}async fetchPaymentTransactions($){let W=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(W)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let W=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)W.searchParams.set("type",$.type);return this.request(`${W.pathname}${W.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}`)}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(W)}/balance`)}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");let Z=await this.resolveOrganizationMemberId(W,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(W)}/members/${encodeURIComponent(Z)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let W=$?.trim();if(W)return W;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,W){let Z=W?.trim();if(Z)return Z;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let X=(await this.fetchUserOrganizations()).find((Y)=>Y.organizationId===$)?.memberId;if(!X?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return X}async request($,W){let Z=(await this.getAuthTokenFn())?.trim();if(!Z)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,j=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let X=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:W?.method??"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json",...Q??{}},body:W?.body!==void 0?JSON.stringify(W.body):void 0,signal:J.signal});if(X.status===204||W?.expectNoContent){if(!X.ok)throw Error(`Cline account request failed with status ${X.status}`);return}let Y=await X.text(),V;if(Y.trim())try{V=JSON.parse(Y)}catch{if(!X.ok)throw Error(EK(X.status,Y,void 0));throw Error("Cline account response was not valid JSON")}if(!X.ok)throw Error(EK(X.status,Y,V));if(typeof V==="object"&&V!==null){let B=V;if(typeof B.success==="boolean"){if(!B.success)throw Error(B.error||"Cline account request failed");return B.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(j)}}}function xZ($){return $.action==="clineAccount"}async function gZ($,W){switch($.operation){case"fetchMe":return W.fetchMe();case"fetchBalance":return W.fetchBalance($.userId);case"fetchUsageTransactions":return W.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return W.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return W.fetchUserOrganizations();case"fetchOrganizationBalance":return W.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return W.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await W.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return W.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class O5{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let W=$.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:W})}async fetchOrganizationUsageTransactions($){let W=$.organizationId.trim();if(!W)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:W,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var CK={};w(CK,{createOAuthClientCallbacks:()=>V6});function V6($){return{onAuth:({url:W,instructions:Z})=>{if($.onOutput?.(Z??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(W)).catch((Q)=>{$.onOpenUrlError?.({url:W,error:Q})})}catch(Q){$.onOpenUrlError?.({url:W,error:Q})}$.onOutput?.(W)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var gU={};w(gU,{ClineCore:()=>AW});function PK($){if($===!0)return{};if(!$)return;return $}function SK($){if($==="user")return"global";return $}class zJ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let W=this.getService().ingestEvent($);return{event:W.event,duplicate:W.duplicate,matchedSpecIds:W.matchedSpecs.map((Z)=>Z.specId),queuedRuns:W.queuedRuns,suppressions:W.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function bK($){let{host:W}=$;return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||K0.CLI,interactive:!1,config:{providerId:Q6(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:CN(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content),delivery:Q.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:wN(J)}},async abortSession(Z){return await W.abort(Z,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}function mZ($){let W=EN($.automationService,$.automation),Z=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!W&&!Z&&!Q&&!J&&!j)return $.context;return{...$.context??{},...Z?{client:Z}:{},...Q?{user:Q}:{},...J?{logger:J}:{},...j?{telemetry:j}:{},...W?{automation:W}:{}}}function EN($,W){if(!$)return;return{ingestEvent:(Z)=>{W.ingestEvent(Z)}}}function wN($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function CN($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var IF={};w(IF,{createCoreSettingsService:()=>d2,CoreSettingsService:()=>c$});import{existsSync as c5,readFileSync as Dw}from"node:fs";import{basename as mJ,dirname as CF,extname as _w,isAbsolute as bF,join as fw,relative as yF,resolve as PF}from"node:path";var iK={};w(iK,{resolveWorkflowsConfigSearchPaths:()=>C5,resolveSkillsConfigSearchPaths:()=>E5,resolveRulesConfigSearchPaths:()=>w5,parseWorkflowConfigFromMarkdown:()=>N5,parseSkillConfigFromMarkdown:()=>M5,parseRuleConfigFromMarkdown:()=>R5,createWorkflowsConfigDefinition:()=>b5,createUserInstructionConfigService:()=>g$,createSkillsConfigDefinition:()=>P5,createRulesConfigDefinition:()=>S5,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q5,UnifiedConfigFileWatcher:()=>I2,SKILLS_CONFIG_DIRECTORY_NAME:()=>z5,RULES_CONFIG_DIRECTORY_NAME:()=>pZ});import{createHash as PN}from"node:crypto";import{watch as SN}from"node:fs";import{readdir as bN,readFile as yN}from"node:fs/promises";import{join as hN}from"node:path";function kN($){return PN("sha1").update($).digest("hex")}function kK($){return Boolean($&&typeof $==="object"&&"code"in $)}function yK($){return kK($)&&$.code==="ENOENT"}function hK($){return kK($)&&($.code==="EACCES"||$.code==="EPERM")}class I2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,W){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=W?.debounceMs??75,this.emitParseErrors=W?.emitParseErrors??!1;for(let Z of $){if(this.definitionsByType.has(Z.type))throw Error(`Duplicate unified config definition type '${Z.type}'.`);this.definitionsByType.set(Z.type,Z),this.recordsByType.set(Z.type,new Map),this.discoveredDirectoriesByType.set(Z.type,new Set);for(let Q of Z.directories){let J=this.baseTypesByDirectory.get(Q);if(J)J.add(Z.type);else this.baseTypesByDirectory.set(Q,new Set([Z.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let W=this.definitionsByType.get($);if(!W)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(W)})}getSnapshot($){let W=this.recordsByType.get($);return new Map([...W?.entries()??[]].map(([Z,Q])=>[Z,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[W,Z]of this.recordsByType.entries())$.set(W,new Map([...Z.entries()].map(([Q,J])=>[Q,{...J}])));return $}emit($){for(let W of this.listeners)W($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[W,Z]of this.watchersByDirectory.entries()){if($.has(W))continue;Z.close(),this.watchersByDirectory.delete(W)}this.watchedTypesByDirectory=$;for(let W of $.keys()){if(this.watchersByDirectory.has(W))continue;try{let Z=SN(W,()=>{let Q=this.watchedTypesByDirectory.get(W);if(!Q)return;for(let J of Q)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(W,Z),Z.on("error",(Q)=>{let J=this.watchedTypesByDirectory.get(W);if(!J)return;for(let j of J)this.emit({kind:"error",type:j,error:Q,filePath:W})})}catch(Z){if(!yK(Z)&&!hK(Z)){let Q=$.get(W);if(!Q)continue;for(let J of Q)this.emit({kind:"error",type:J,error:Z,filePath:W})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let W of $){let Z=this.definitionsByType.get(W);if(!Z)continue;await this.refreshTypeInternal(Z)}})},this.debounceMs)}async refreshTypeInternal($){let{records:W,discoveredDirectories:Z}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[J,j]of Q.entries()){if(W.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:j.filePath})}for(let[J,j]of W.entries()){let X=Q.get(J);if(X&&X.filePath===j.filePath&&X.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:J,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,W),this.discoveredDirectoriesByType.set($.type,Z),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let W=new Map,Z=new Set;for(let Q of $.directories){Z.add(Q);let J=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let j of J){let{fileName:X,filePath:Y}=j;if(Z.add(j.directoryPath),$.includeFile&&!$.includeFile(X,Y))continue;try{let V=await yN(Y,"utf8"),B={type:$.type,directoryPath:j.directoryPath,fileName:X,filePath:Y,content:V},H=$.parseFile(B),G=$.resolveId(H,B).trim();if(!G)continue;W.set(G,{type:$.type,id:G,item:H,filePath:Y,fingerprint:kN(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:Y})}}}return{records:W,discoveredDirectories:Z}}buildDesiredTypesByDirectory(){let $=new Map;for(let[W,Z]of this.baseTypesByDirectory.entries())$.set(W,new Set(Z));for(let[W,Z]of this.discoveredDirectoriesByType.entries())for(let Q of Z){let J=$.get(Q);if(J)J.add(W);else $.set(Q,new Set([W]))}return $}async readDirectoryFileCandidates($){try{return(await bN($,{withFileTypes:!0})).filter((Z)=>Z.isFile()).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:hN($,Z.name)})).sort((Z,Q)=>Z.fileName.localeCompare(Q.fileName))}catch(W){if(yK(W)||hK(W))return[];throw W}}}import{readdir as MJ,readFile as IN,stat as qJ}from"node:fs/promises";import{basename as W$,dirname as xN,extname as cZ,join as v0,resolve as T5}from"node:path";import{stripUtf8Bom as gN}from"@cline/shared";import{AGENTS_RULES_FILE_NAME as IK,RULES_CONFIG_DIRECTORY_NAME as pZ,resolveGlobalAgentsRulesPath as mN,resolveRulesConfigSearchPaths as vN,resolveSkillsConfigSearchPaths as cN,resolveWorkflowsConfigSearchPaths as uN,SKILLS_CONFIG_DIRECTORY_NAME as z5,WORKFLOWS_CONFIG_DIRECTORY_NAME as q5}from"@cline/shared/storage";import dN from"yaml";var vZ="SKILL.md",lN="managed.json",pN=new Set([".md",".markdown",".txt"]);function RJ($){return $.trim().toLowerCase()}function B6($){let W=$;return W?.code==="ENOENT"||W?.code==="EACCES"||W?.code==="EPERM"||W?.code==="ELOOP"}function uZ($){return pN.has(cZ($).toLowerCase())}function xK($){let W=[],Z=new Set;for(let Q of $){let J=T5(Q);if(Z.has(J))continue;Z.add(J),W.push(Q)}return W}function rN($){let W=[...$?.directories??E5($?.workspacePath)];if($?.pluginSkillDirectories)W.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)W.push(...lG({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return xK(W)}async function NJ($){try{let W=await MJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(!Q.isDirectory())continue;let J=v0($,Q.name),j=v0(J,lN);try{let X=await IN(j,"utf8"),Y=JSON.parse(X);if(Y&&typeof Y==="object")Z.push(J)}catch(X){if(B6(X))continue;if(X?.name==="SyntaxError")continue;throw X}}return Z.sort((Q,J)=>Q.localeCompare(J))}catch(W){if(B6(W))return[];throw W}}function EJ($){let W=gN($),Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=W.match(Z);if(!Q)return{data:{},body:W,hadFrontmatter:!1};let[,J,j]=Q;try{let X=dN.parse(J);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:j,hadFrontmatter:!0}}catch(X){let Y=X instanceof Error?X.message:String(X);return{data:{},body:W,hadFrontmatter:!0,parseError:Y}}}function dZ($,W,Z){if($===void 0||$===null){if(Z)throw Error(`Missing required frontmatter field '${W}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${W}' must be a string.`);let Q=$.trim();if(!Q&&Z)throw Error(`Frontmatter field '${W}' cannot be empty.`);return Q||void 0}function H6($,W){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${W}' must be a boolean.`);return $}function iN($,W){if(W$($.filePath).toLowerCase()!==IK.toLowerCase())return W$($.filePath,cZ($.filePath));if(W&&T5($.filePath)===T5(W,IK))return"Workspace AGENTS.md";if(T5($.filePath)===T5(mN()))return"Global AGENTS.md";return W$($.filePath,cZ($.filePath))}function M5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in skill file.");let Y=dZ(Z.name,"name",!1)??W.trim();if(!Y)throw Error("Missing skill name.");return{name:Y,description:dZ(Z.description,"description",!1),disabled:H6(Z.disabled,"disabled")??(H6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function R5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in rule file.");let X=dZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing rule name.");return{name:X,disabled:H6(Z.disabled,"disabled")??(H6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function N5($,W){let{data:Z,body:Q,parseError:J}=EJ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let j=Q.trim();if(!j)throw Error("Missing instructions body in workflow file.");let X=dZ(Z.name,"name",!1)??W.trim();if(!X)throw Error("Missing workflow name.");return{name:X,disabled:H6(Z.disabled,"disabled")??(H6(Z.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Z}}function E5($){return cN($)}function w5($){return vN($)}function C5($){return uN($)}async function gK($){if(W$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>gK(v0(Q,z5))))).flat()}try{let W=await MJ($,{withFileTypes:!0}),Z=[];for(let Q of W){if(Q.isFile()&&Q.name===vZ){Z.push({directoryPath:$,fileName:Q.name,filePath:v0($,Q.name)});continue}let J=v0($,Q.name);if(Q.isDirectory()||Q.isSymbolicLink()&&await qJ(J).then((X)=>X.isDirectory()).catch((X)=>{if(B6(X))return!1;throw X}))Z.push({directoryPath:J,fileName:vZ,filePath:v0(J,vZ)})}return Z}catch(W){if(B6(W))return[];throw W}}async function lZ($){if(W$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>lZ(v0(Q,"rules.md"))))).flat()}try{if((await qJ($)).isFile())return[{directoryPath:xN($),fileName:W$($),filePath:$}]}catch(W){if(!B6(W))throw W}try{let Z=(await MJ($,{withFileTypes:!0})).filter((J)=>J.isFile()&&uZ(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:v0($,J.name)})),Q=v0($,"AGENTS.md");try{if((await qJ(Q)).isFile()){if(!Z.some((X)=>X.fileName==="AGENTS.md"))Z.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return Z}catch(W){if(B6(W))return[];throw W}}async function nN($){if(W$($)===".cline"){let W=await NJ($);return(await Promise.all(W.map((Q)=>lZ(v0(Q,q5))))).flat()}return lZ($)}function P5($){let W=rN($),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Z?xK([...W,Z]):W,discoverFiles:gK,includeFile:(Q)=>Q===vZ,parseFile:(Q)=>M5(Q.content,W$(Q.directoryPath)),resolveId:(Q)=>RJ(Q.name)}}function S5($){let W=$?.directories??w5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Z?[...W,Z]:W,discoverFiles:lZ,includeFile:(Q,J)=>Q===".clinerules"||uZ(Q)||uZ(J),parseFile:(Q)=>R5(Q.content,iN(Q,$?.workspacePath)),resolveId:(Q)=>RJ(Q.name)}}function b5($){let W=$?.directories??C5($?.workspacePath),Z=$?.workspacePath?v0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Z?[...W,Z]:W,discoverFiles:nN,includeFile:(Q)=>uZ(Q),parseFile:(Q)=>N5(Q.content,W$(Q.filePath,cZ(Q.filePath))),resolveId:(Q)=>RJ(Q.name)}}function mK($){let W=[P5($?.skills),S5($?.rules),b5($?.workflows)];return new I2(W,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as vK}from"@cline/shared";function aN($,W){if($.description?.trim())return vK($.description,".");if(W==="workflow")return;return vK($.instructions,".")}function oN($){return $.disabled!==!0}function cK($,W){return[...$.getSnapshot(W).entries()].map(([Z,Q])=>({id:Z,record:Q})).filter(({record:Z})=>oN(Z.item)).map(({id:Z,record:Q})=>({id:Z,name:Q.item.name,instructions:Q.item.instructions,description:aN(Q.item,W),kind:W})).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function y5($){let W=new Map;for(let Z of[...cK($,"workflow"),...cK($,"skill")])if(!W.has(Z.name))W.set(Z.name,Z);return[...W.values()].sort((Z,Q)=>Z.name.localeCompare(Q.name))}function uK($,W){if(!$.startsWith("/")||$.length<2)return $;let Z=$.match(/^\/(\S+)/);if(!Z)return $;let Q=Z[1];if(!Q)return $;let J=Q.length+1,j=$.slice(J),X=y5(W).find((Y)=>Y.name===Q);return X?`${X.instructions}${j}`:$}var lK={};w(lK,{mergeRulesForSystemPrompt:()=>K6,loadRulesForSystemPromptFromWatcher:()=>wJ,listEnabledRulesFromWatcher:()=>dK,isRuleEnabled:()=>rZ,formatRulesForSystemPrompt:()=>G6});function rZ($){return $.disabled!==!0}function G6($){if($.length===0)return"";return`
210
210
 
211
211
  # Rules
212
212
  ${$.map((Z)=>`## ${Z.name}
213
213
  ${Z.instructions}`).join(`
214
214
 
215
- `)}`}function G6($,W){let Z=$?.trim(),Q=W?.trim();if(Z&&Q)return`${Z}
215
+ `)}`}function K6($,W){let Z=$?.trim(),Q=W?.trim();if(Z&&Q)return`${Z}
216
216
 
217
- ${Q}`;return Z||Q||void 0}function uK($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(rZ).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function wJ($){return H6(uK($))}function iZ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function pN($){if(!$||$.length===0)return;let W=$.map(iZ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function rN($,W,Z){if(!Z)return!0;let Q=iZ($),J=iZ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function y5($,W){let Z=pN(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>rN(J.id,J.name,Z))}function iN($,W){return y5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function nN($,W,Z){let Q=iZ(W);if(!Q)return{error:"Missing skill name."};let J=y5($,Z),j=J.find((H)=>H.id===Q);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=iN($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function CJ($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=nN($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
217
+ ${Q}`;return Z||Q||void 0}function dK($){return[...$.getSnapshot("rule").values()].map((Z)=>Z.item).filter(rZ).sort((Z,Q)=>Z.name.localeCompare(Q.name))}function wJ($){return G6(dK($))}function iZ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function sN($){if(!$||$.length===0)return;let W=$.map(iZ).filter((Z)=>Z.length>0);return W.length>0?new Set(W):void 0}function tN($,W,Z){if(!Z)return!0;let Q=iZ($),J=iZ(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function h5($,W){let Z=sN(W);return[...$.getSnapshot("skill").entries()].map(([J,j])=>{let X=j.item;return{id:J,name:X.name.trim(),description:X.description?.trim(),disabled:X.disabled===!0,skill:X}}).filter((J)=>tN(J.id,J.name,Z))}function eN($,W){return h5($,W).filter((Z)=>!Z.disabled).map((Z)=>Z.name.trim()).filter((Z)=>Z.length>0).sort((Z,Q)=>Z.localeCompare(Q))}function $E($,W,Z){let Q=iZ(W);if(!Q)return{error:"Missing skill name."};let J=h5($,Z),j=J.find((H)=>H.id===Q);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let X=Q.includes(":")?Q.split(":").at(-1)??Q:Q,Y=J.filter(({id:H})=>{if(H===X)return!0;return H.endsWith(`:${X}`)}),V=Y.filter(({skill:H})=>H.disabled!==!0);if(V.length===1){let{id:H,skill:G}=V[0];return{id:H,skill:G}}if(V.length>1)return{error:`Skill "${W}" is ambiguous. Use one of: ${V.map(({id:H})=>H).join(", ")}`};if(Y.length===1){let{skill:H}=Y[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(Y.length>1)return{error:`Skill "${W}" is ambiguous, and all matches are disabled: ${Y.map(({id:H})=>H).join(", ")}`};let B=eN($,Z);return{error:B.length>0?`Skill "${W}" not found. Available skills: ${B.join(", ")}`:"No skills are currently available."}}function CJ($,W=Promise.resolve(),Z){let Q=new Set,J=async(j,X)=>{await W;let Y=$E($,j,Z);if("error"in Y)return Y.error;let{id:V,skill:B}=Y;if(Q.has(V))return`Skill "${B.name}" is already running.`;Q.add(V);try{let H=X?.trim(),G=H?`
218
218
  <command-args>${H}</command-args>`:"",K=B.description?.trim()?`Description: ${B.description.trim()}
219
219
 
220
220
  `:"";return`<command-name>${B.name}</command-name>${G}
221
221
  <command-instructions>
222
222
  ${K}${B.instructions}
223
- </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>y5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function lK($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>wJ($.watcher)});if($.registerSkillsTool)Q.registerTool(F2(CJ($.watcher,W,$.allowedSkillNames)));for(let J of b5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
223
+ </command-instructions>`}finally{Q.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>h5($,Z).map(({skill:j,...X})=>X),enumerable:!0,configurable:!1}),J}function pK($){let W=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await W,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>wJ($.watcher)});if($.registerSkillsTool)Q.registerTool(F2(CJ($.watcher,W,$.allowedSkillNames)));for(let J of y5($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:J.name,description:J.description,handler:(j)=>{let X=j.trim();return X?`${J.instructions}
224
224
 
225
- ${X}`:J.instructions}})}}}class pK{watcher;ready;stopped=!1;constructor($){this.watcher=gK($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return b5(this.watcher)}resolveRuntimeSlashCommand($){return cK($,this.watcher)}hasConfiguredSkills($){return y5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return CJ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return lK({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function x$($){return new pK($)}import{readFile as aN,writeFile as oN}from"node:fs/promises";import{stripUtf8Bom as sN}from"@cline/shared";import nK from"yaml";function tN($){let W=sN($),Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=W.match(Z);if(!Q)return{data:{},body:W,hadFrontmatter:!1};let[,J,j]=Q,X=nK.parse(J);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:j,hadFrontmatter:!0}}function iK($,W){return`---
226
- ${nK.stringify($).trimEnd()}
225
+ ${X}`:J.instructions}})}}}class rK{watcher;ready;stopped=!1;constructor($){this.watcher=mK($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([W,Z])=>({type:$,id:W,filePath:Z.filePath,item:Z.item}))}listRuntimeCommands(){return y5(this.watcher)}resolveRuntimeSlashCommand($){return uK($,this.watcher)}hasConfiguredSkills($){return h5(this.watcher,$).some((W)=>!W.disabled)}createSkillsExecutor($){return CJ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return pK({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function g$($){return new rK($)}import{readFile as WE,writeFile as ZE}from"node:fs/promises";import{stripUtf8Bom as QE}from"@cline/shared";import aK from"yaml";function JE($){let W=QE($),Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=W.match(Z);if(!Q)return{data:{},body:W,hadFrontmatter:!1};let[,J,j]=Q,X=aK.parse(J);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:j,hadFrontmatter:!0}}function nK($,W){return`---
226
+ ${aK.stringify($).trimEnd()}
227
227
  ---
228
- ${W}`}function eN($,W){let{data:Z,body:Q,hadFrontmatter:J}=tN($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return iK(Z,Q)}return Z.disabled=!0,iK(Z,Q)}async function aK({filePath:$,enabled:W}){let Z=await aN($,"utf8"),Q=eN(Z,W);return await oN($,Q),{filePath:$,enabled:W,disabled:!W}}var MF={};w(MF,{updateMcpSettingsFileSync:()=>D1,updateMcpSettingsFile:()=>F6,updateMcpServerOAuthStateAsync:()=>k5,updateMcpServerOAuthState:()=>v2,setMcpServerDisabled:()=>g2,resolvePluginMcpServerRegistrations:()=>$Q,resolveMcpServerRegistrations:()=>t0,resolveDefaultMcpSettingsPath:()=>Q0,registerMcpServersFromSettingsFile:()=>c2,normalizePluginMcpServerRegistration:()=>gJ,loadMcpSettingsFile:()=>x2,listMcpServerOAuthStatuses:()=>I5,hasMcpSettingsFile:()=>W$,getMcpServerOAuthState:()=>m2,createMcpTools:()=>_6,createDisabledMcpToolPolicy:()=>x5,createDisabledMcpToolPolicies:()=>ZQ,createDefaultMcpServerClientFactory:()=>U6,authorizeMcpServerOAuth:()=>tZ,McpSettingsUpdateSkippedError:()=>K6,McpSettingsMutatorPurityError:()=>g$,McpSettingsLockTimeoutError:()=>m$,InMemoryMcpManager:()=>u2});import{spawn as gE}from"node:child_process";import{StringDecoder as fF}from"node:string_decoder";import{UnauthorizedError as AF}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as mE}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as wE}from"node:crypto";import{UnauthorizedError as CE}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as PE}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as SE}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as bE}from"@modelcontextprotocol/sdk/client/streamableHttp.js";aZ();var yE="/mcp/oauth/callback",hE=[1456,1457,1458],kE=300000;function IE($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function xE($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function sZ($){let W={};try{W=m2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=A6(X(W))??{};try{W=v2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return xE(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=wE(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function oZ($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new SE(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new bE(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function FF($){return new PE({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function tZ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (aZ(),KF)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await G1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:hE,callbackPath:$.callbackPath??yE,timeoutMs:$.timeoutMs??kE,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=sZ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=FF($),Y;try{let V=oZ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof CE))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=FF($);let F=oZ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=IE(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var vE="2024-11-05",cE=5000,uE=1500,UF="http://127.0.0.1:1456/mcp/oauth/callback";function eZ($){return $ instanceof Error?$.message:String($)}function DF($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
228
+ ${W}`}function jE($,W){let{data:Z,body:Q,hadFrontmatter:J}=JE($);if(!J&&W)return $;if(W){if(delete Z.disabled,Z.enabled===!1)delete Z.enabled;if(Object.keys(Z).length===0)return Q;return nK(Z,Q)}return Z.disabled=!0,nK(Z,Q)}async function oK({filePath:$,enabled:W}){let Z=await WE($,"utf8"),Q=jE(Z,W);return await ZE($,Q),{filePath:$,enabled:W,disabled:!W}}var RF={};w(RF,{updateMcpSettingsFileSync:()=>f1,updateMcpSettingsFile:()=>A6,updateMcpServerOAuthStateAsync:()=>I5,updateMcpServerOAuthState:()=>v2,setMcpServerDisabled:()=>g2,resolvePluginMcpServerRegistrations:()=>$Q,resolveMcpServerRegistrations:()=>W1,resolveDefaultMcpSettingsPath:()=>Q0,registerMcpServersFromSettingsFile:()=>c2,normalizePluginMcpServerRegistration:()=>gJ,loadMcpSettingsFile:()=>x2,listMcpServerOAuthStatuses:()=>x5,hasMcpSettingsFile:()=>Z$,getMcpServerOAuthState:()=>m2,createMcpTools:()=>f6,createDisabledMcpToolPolicy:()=>g5,createDisabledMcpToolPolicies:()=>ZQ,createDefaultMcpServerClientFactory:()=>D6,authorizeMcpServerOAuth:()=>tZ,McpSettingsUpdateSkippedError:()=>F6,McpSettingsMutatorPurityError:()=>m$,McpSettingsLockTimeoutError:()=>v$,InMemoryMcpManager:()=>u2});import{spawn as lE}from"node:child_process";import{StringDecoder as LF}from"node:string_decoder";import{UnauthorizedError as UF}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as pE}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as hE}from"node:crypto";import{UnauthorizedError as kE}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as IE}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as xE}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as gE}from"@modelcontextprotocol/sdk/client/streamableHttp.js";aZ();var mE="/mcp/oauth/callback",vE=[1456,1457,1458],cE=300000;function uE($){if($ instanceof Error){let W=$.message.trim();if(W.length>0)return W}return String($)}function dE($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function sZ($){let W={};try{W=m2($.serverName,{filePath:$.settingsPath})??{}}catch{W={}}let Z,Q,J=async(X)=>{let Y=U6(X(W))??{};try{W=v2($.serverName,()=>Y,{filePath:$.settingsPath})}catch{W=Y}};return{provider:{get redirectUrl(){return W.redirectUrl??$.redirectUrl},get clientMetadata(){return dE(W.redirectUrl??$.redirectUrl)},state:()=>{return Q=hE(),Q},clientInformation:()=>W.clientInformation,saveClientInformation:async(X)=>{await J((Y)=>({...Y,clientInformation:X,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>W.tokens,saveTokens:async(X)=>{let Y=Date.now();await J((V)=>({...V,tokens:X,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Y}))},redirectToAuthorization:async(X)=>{Z=X.toString(),await $.onAuthorizationUrl?.(Z)},saveCodeVerifier:async(X)=>{await J((Y)=>({...Y,codeVerifier:X,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!W.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return W.codeVerifier},invalidateCredentials:async(X)=>{await J((Y)=>{if(X==="all")return{lastError:Y.lastError,redirectUrl:Y.redirectUrl};return{...Y,...X==="client"?{clientInformation:void 0}:{},...X==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...X==="verifier"?{codeVerifier:void 0}:{},...X==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(X)=>{await J((Y)=>({...Y,discoveryState:X}))},discoveryState:()=>W.discoveryState},getLastAuthorizationUrl:()=>Z,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await J((X)=>({...X,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(X)=>{await J((Y)=>({...Y,lastError:X}))},clearError:async()=>{await J((X)=>({...X,lastError:void 0}))}}}function oZ($){let W=$.registration.transport;if(W.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Z=W.headers?{headers:W.headers}:void 0;if(W.type==="sse")return new xE(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch});return new gE(new URL(W.url),{authProvider:$.oauthProvider,requestInit:Z,fetch:$.fetch})}function AF($){return new IE({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function tZ($){let W=$.serverName.trim();if(!W)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Z}=await Promise.resolve().then(() => (aZ(),FF)),Q=Z({filePath:$.filePath}).find((V)=>V.name===W);if(!Q)throw Error(`MCP server "${W}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${W}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${W}" uses stdio transport and does not support OAuth browser flow.`);let J=await F1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:vE,callbackPath:$.callbackPath??mE,timeoutMs:$.timeoutMs??cE,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=sZ({settingsPath:$.filePath,serverName:W,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await j.resetInteractiveState();let X=AF($),Y;try{let V=oZ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});try{return await X.connect(V),await X.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" is already authorized.`}}catch(B){if(!(B instanceof kE))throw B;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${W}" did not provide an authorization URL.`);let G=await J.waitForCallback();if(!G)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(G.error)throw Error(`OAuth authorization failed: ${G.error}`);if(!G.code)throw Error("OAuth callback did not include an authorization code.");let K=j.getLastOAuthState();if(!K)throw Error(`MCP server "${W}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),Y=AF($);let F=oZ({registration:Q,oauthProvider:j.provider,fetch:$.fetch});return await Y.connect(F),await Y.listTools(),await j.clearError(),{serverName:W,authorized:!0,message:`MCP server "${W}" OAuth authorization completed.`}}}catch(V){let B=uE(V);throw await j.markError(B),Error(B)}finally{await X.close().catch(()=>{return}),await Y?.close().catch(()=>{return}),J.close()}}var rE="2024-11-05",iE=5000,nE=1500,DF="http://127.0.0.1:1456/mcp/oauth/callback";function eZ($){return $ instanceof Error?$.message:String($)}function _F($){let W=Buffer.from(JSON.stringify($),"utf8"),Z=Buffer.from(`Content-Length: ${W.byteLength}\r
229
229
  \r
230
- `,"utf8");return Buffer.concat([Z,W])}function _F($){return Buffer.from(`${JSON.stringify($)}
231
- `,"utf8")}class IJ{buffer="";decoder=new fF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
230
+ `,"utf8");return Buffer.concat([Z,W])}function fF($){return Buffer.from(`${JSON.stringify($)}
231
+ `,"utf8")}class IJ{buffer="";decoder=new LF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`\r
232
232
  \r
233
- `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class xJ{buffer="";decoder=new fF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
234
- `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class LF{registration;process;nextRequestId=1;pending=new Map;framedParser=new IJ;newlineParser=new xJ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:vE,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},uE),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new IJ,this.newlineParser=new xJ,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=gE(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${eZ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${eZ($)}.${Z}`)),W.kill()}async request($,W,Z=cE){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?DF(j):_F(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?DF(Q):_F(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class OF{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=sZ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??UF});this.authContext=$;try{let W=new mE({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=oZ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof AF?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):eZ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??sZ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??UF}),Z=$ instanceof AF?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):eZ($);throw await W.markError(Z),Error(Z)}}function U6($={}){return(W)=>W.transport.type==="stdio"?new LF(W):new OF(W,$)}aZ();function e0(){return Date.now()}function dE($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class u2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:e0()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=e0(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=e0(),W)await this.disconnectState(Z)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&e0()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=dE(Q);return W.toolCache=J,W.toolCacheUpdatedAt=e0(),W.updatedAt=e0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=e0(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=e0();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=e0()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=e0(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=e0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=e0()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function D6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function TF($){return D6($)&&Object.values($).every((W)=>typeof W==="string")}function lE($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function pE($){if(!D6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function rE($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function gJ($){if(!D6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!D6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!pE(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!D6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=D6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!lE(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!TF(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=rE({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!TF(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function $Q($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=gJ(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as iE}from"node:crypto";var zF=64,nE=/[^a-zA-Z0-9_-]+/g,qF=8,aE=1,oE="mcp_tool";function sE($){return iE("sha1").update($).digest("hex").slice(0,qF)}function tE($){return $.replace(nE,"_")}var WQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=tE(Z);if(Q===Z&&Z.length<=zF)return Z;let J=sE(Z),j=zF-aE-qF;return`${Q.slice(0,j)||oE}_${J}`};function x5($){return{[($.nameTransform??WQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function ZQ($){let W={};for(let Z of $.toolNames)Object.assign(W,x5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as eE}from"@cline/shared";function $w($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function _6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??WQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return eE({name:J,description:$w($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}U1();var EF={};w(EF,{listPluginToolsWithDiagnostics:()=>QQ,listPluginTools:()=>g5});import{stat as Ww}from"node:fs/promises";import{isAbsolute as Zw,relative as Qw,resolve as RF}from"node:path";U1();function Jw($,W){let Z=Qw(RF($),RF(W));return Z===""||!Z.startsWith("..")&&!Zw(Z)}var jw=32,f6=new Map;function Xw($,W){if(!f6.has($)&&f6.size>=jw){let Z=f6.keys().next().value;if(Z)f6.delete(Z)}f6.set($,W)}async function Yw($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await Ww(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function NF($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function Vw($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function Bw($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function QQ($){let W=t1({workspacePath:$.workspacePath,cwd:$.cwd}),Z=R1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await Yw({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=f6.get(Q);if(J)return{tools:NF(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await a8({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=Jw($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await Bw(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=Vw(j);return Xw(Q,{tools:B,failures:X,warnings:Y}),{tools:NF(B,Z),failures:X,warnings:Y}}async function g5($){return(await QQ($)).tools}function c5($,W){if(!W)return"global";let Z=bF(W,$);return!Z.startsWith("..")&&!SF(Z)?"workspace":"global"}function Fw($,W){return c5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function Aw($,W){let Z=bF(CF($),CF(W));return Z===""||!Z.startsWith("..")&&!SF(Z)}function Uw($){try{let W=JSON.parse(Hw($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function Dw($){let W=wF($);while(!0){let Z=Kw(W,"package.json");if(v5(Z)){let J=Uw(Z);if(J)return J;break}let Q=wF(W);if(Q===W)break;W=Q}return mJ($,Gw($))}function _w($){let W=[];for(let Z of t1({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of e1([Z]))W.push({directory:Q,pluginName:Dw(Z),pluginPath:Z,source:$.workspaceRoot?Fw(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function fw($,W){return W.find((Z)=>Aw(Z.directory,$))}function m5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function yF($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function hF($,W){return $.cwd?.trim()||W||process.cwd()}async function PF($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=yF($),Q=hF($,Z),J=x$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function Lw($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class v${async list($={}){return await PF($,async(W)=>{let Z=yF($),Q=_w({workspaceRoot:Z,cwd:hF($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:c5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:c5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=fw(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??c5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await g5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=Q0();if(W$({filePath:B}))try{for(let H of t0({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:c5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:m5(J.filter((H)=>v5(H.path))),rules:m5(j.filter((H)=>v5(H.path))),skills:m5(X.filter((H)=>v5(H.path))),tools:m5(Y),mcp:m5(V.filter((H)=>v5(H.path)))}})}async toggle($){if($.type==="skills")return await PF($,async(W)=>{let Z=Lw(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??mJ($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??mJ($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await aK({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)v9($.name);else VH($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||Q0(),Q=$.enabled;if(Q===void 0){let J=t0({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return g2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function d2(){return new v$}function IF($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await d2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await d2().toggle(W)}}}function xF($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}var gF={};w(gF,{splitCoreSessionConfig:()=>u5,isSessionNotFoundError:()=>Q$,SessionNotFoundError:()=>Z$,SESSION_NOT_FOUND_ERROR_CODE:()=>l2});var l2="session_not_found";class Z$ extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function Q$($){return $ instanceof Z$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function u5($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}function mF($){let W=$.config;return"providerId"in W?{...$,config:{...W,...Ow($.localRuntime)},localRuntime:$.localRuntime}:$}function vJ($,W={}){let Z=u5($.config),Q=C0(W.defaultCapabilities,$.capabilities),J=Tw(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function Ow($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function Tw(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}D0();function vF($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:v.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function d5($){return!!$&&typeof $==="object"&&!Array.isArray($)}function cJ($){let W=$?.trim();return W?W:void 0}function zw($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function cF($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function uF($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function qw($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function Mw($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=cJ($.subject),X=cJ($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:zw($.occurredAt,W),workspaceRoot:cJ($.workspaceRoot),payload:d5($.payload)?$.payload:void 0,attributes:d5($.attributes)?$.attributes:void 0,dedupeKey:X}}function uJ($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!d5(Q))return;Q=Q[J]}return Q}function Rw($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=uJ(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=uJ($.attributes,W);if(J!==void 0)return J}if($.payload)return uJ($.payload,W);return}function JQ($,W){if(Array.isArray(W))return W.some((Z)=>JQ($,Z));if(Array.isArray($))return $.some((Z)=>JQ(Z,W));if(d5(W)){if(!d5($))return!1;return Object.entries(W).every(([Z,Q])=>JQ($[Z],Q))}return Object.is($,W)}function Nw($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>JQ(Rw($,Z),Q))}class dJ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=Mw($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!Nw(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=qw(V.scheduledFor,cF(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:uF(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:uF(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?cF(Z,J):Z}),reason:"dedupe_window"}}}class l5{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as yw}from"node:path";import{buildClineSystemPrompt as hw}from"@cline/shared";import{nowIso as dF}from"@cline/shared/db";import{mkdirSync as Ew,writeFileSync as ww}from"node:fs";import{join as Cw}from"node:path";import{resolveCronReportsDir as Pw}from"@cline/shared/storage";function c$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function p2($,W){if(W===void 0||W===null)return;return`${$}: ${c$(W)}`}function Sw($,W,Z){let Q=[`runId: ${c$($.runId)}`,`specId: ${c$(W.specId)}`,`externalId: ${c$(W.externalId)}`,`title: ${c$(W.title)}`,`triggerKind: ${c$($.triggerKind)}`,`status: ${c$($.status)}`,`sourcePath: ${c$(W.sourcePath)}`],J=[p2("sessionId",$.sessionId),p2("startedAt",$.startedAt),p2("completedAt",$.completedAt),p2("triggerEventId",$.triggerEventId),p2("triggerEventType",Z?.eventType),p2("triggerEventSource",Z?.source),p2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
233
+ `);if(Z<0)break;let J=this.buffer.slice(0,Z).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(J[1],10),X=Z+4,Y=X+j;if(this.buffer.length<Y)break;W.push(this.buffer.slice(X,Y)),this.buffer=this.buffer.slice(Y)}return W}}class xJ{buffer="";decoder=new LF("utf8");push($){this.buffer+=this.decoder.write($);let W=[];while(!0){let Z=this.buffer.indexOf(`
234
+ `);if(Z<0)break;let Q=this.buffer.slice(0,Z).trim();if(this.buffer=this.buffer.slice(Z+1),Q.length>0)W.push(Q)}return W}}class OF{registration;process;nextRequestId=1;pending=new Map;framedParser=new IJ;newlineParser=new xJ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],W;for(let Z of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Z);try{await this.request("initialize",{protocolVersion:rE,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},nE),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Z;return}catch(Q){W=Q instanceof Error?Q:Error(String(Q))}}throw W??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((W)=>typeof W?.name==="string"&&typeof W.inputSchema==="object"&&W.inputSchema!==null).map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let W=this.registration.transport;if(W.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${W.type}`);this.framedParser=new IJ,this.newlineParser=new xJ,this.stderrBuffer="",this.protocolMode=$;let Z=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=lE(W.command,W.args??[],{cwd:W.cwd,env:{...process.env,...W.env??{}},stdio:["pipe","pipe","pipe"],...Z});this.process=Q,Q.stdout.on("data",(J)=>this.handleStdout(J)),Q.stderr.on("data",(J)=>{if(this.process!==Q)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(J)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${eZ(J)}`))}),Q.once("exit",(J,j)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let X=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${j??"null"}).${X}`))})}handleStdout($){try{let W=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Z of W){let Q=JSON.parse(Z);if(typeof Q.id!=="number")continue;let J=this.pending.get(Q.id);if(!J)continue;if(this.pending.delete(Q.id),clearTimeout(J.timeout),Q.error){let j=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;J.reject(Error(j));continue}J.resolve(Q.result)}}catch(W){this.handleProtocolFailure(W)}}handleProtocolFailure($){let W=this.process;if(!W)return;this.connected=!1,this.process=void 0;let Z=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${eZ($)}.${Z}`)),W.kill()}async request($,W,Z=iE){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,j={jsonrpc:"2.0",id:J,method:$,...W?{params:W}:{}},X=new Promise((Y,V)=>{let B=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Z);this.pending.set(J,{resolve:Y,reject:V,timeout:B})});try{Q.stdin.write(this.protocolMode==="framed"?_F(j):fF(j))}catch(Y){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw Y}return X}notify($,W){let Z=this.process;if(!Z?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...W?{params:W}:{}};Z.stdin.write(this.protocolMode==="framed"?_F(Q):fF(Q))}failAllPending($){for(let[W,Z]of this.pending)clearTimeout(Z.timeout),this.pending.delete(W),Z.reject($)}}class TF{registration;options;client;authContext;constructor($,W){this.registration=$;this.options=W}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=sZ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??DF});this.authContext=$;try{let W=new pE({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Z=oZ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await W.connect(Z),await $.clearError(),this.client=W}catch(W){let Z=W instanceof UF?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):eZ(W);throw await $.markError(Z),Error(Z)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema&&typeof Z.inputSchema==="object"&&!Array.isArray(Z.inputSchema)?Z.inputSchema:{}}))}catch(W){return await this.handleOperationError(W)}}async callTool($){let W=await this.ensureConnectedClient();try{return await W.callTool({name:$.name,arguments:$.arguments??{}})}catch(Z){return await this.handleOperationError(Z)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let W=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${W} Run authorizeMcpServerOAuth for this server.`;return`${W} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let W=this.authContext??sZ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??DF}),Z=$ instanceof UF?this.formatUnauthorizedMessage(W.getLastAuthorizationUrl()):eZ($);throw await W.markError(Z),Error(Z)}}function D6($={}){return(W)=>W.transport.type==="stdio"?new OF(W):new TF(W,$)}aZ();function Z1(){return Date.now()}function aE($){return $.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema}))}class u2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let W=this.servers.get($.name);if(!W){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:Z1()});return}let Z=JSON.stringify(W.registration.transport)!==JSON.stringify($.transport);if(W.registration={...$},W.updatedAt=Z1(),Z)await this.disconnectState(W),W.client=void 0,W.toolCache=void 0,W.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.connectState(W)})}async disconnectServer($){await this.runExclusive($,async()=>{let W=this.requireServer($);await this.disconnectState(W)})}async setServerDisabled($,W){await this.runExclusive($,async()=>{let Z=this.requireServer($);if(Z.registration={...Z.registration,disabled:W},Z.updatedAt=Z1(),W)await this.disconnectState(Z)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,W)=>$.name.localeCompare(W.name))}async listTools($){let W=this.requireServer($),Z=W.toolCacheUpdatedAt??0;if(W.toolCache&&Z1()-Z<=this.toolsCacheTtlMs)return W.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let W=this.requireServer($),Q=await(await this.ensureConnectedClient(W)).listTools(),J=aE(Q);return W.toolCache=J,W.toolCacheUpdatedAt=Z1(),W.updatedAt=Z1(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let W=this.requireServer($.serverName),Z=await this.ensureConnectedClient(W);return W.updatedAt=Z1(),Z.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let W of $)await this.unregisterServer(W)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=Z1();try{let W=$.client??await this.clientFactory($.registration);await W.connect(),$.client=W,$.status="connected",$.lastError=void 0,$.updatedAt=Z1()}catch(W){throw $.status="disconnected",$.lastError=W instanceof Error?W.message:String(W),$.updatedAt=Z1(),W}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=Z1();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=Z1()}}requireServer($){let W=this.servers.get($);if(!W)throw Error(`Unknown MCP server: ${$}`);return W}async runExclusive($,W){let Z=this.operationLocks.get($)??Promise.resolve(),Q,J=new Promise((X)=>{Q=X}),j=Z.catch(()=>{return}).then(()=>J);this.operationLocks.set($,j),await Z.catch(()=>{return});try{return await W()}finally{if(Q?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function _6($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function zF($){return _6($)&&Object.values($).every((W)=>typeof W==="string")}function oE($){return Array.isArray($)&&$.every((W)=>typeof W==="string")}function sE($){if(!_6($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function tE($){let W=$.env?Object.entries($.env):[];if(W.length===0)return{ok:!0};let Z={};for(let[Q,J]of W){if(typeof J==="string"){Z[Q]=J;continue}let j=J.fromEnv?.trim()||Q,X=process.env[j];if(typeof X==="string"&&X.length>0){Z[Q]=X;continue}if(typeof J.value==="string"){Z[Q]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Z).length>0?Z:void 0}}function gJ($){if(!_6($))return{name:"",loadError:"invalid MCP server registration"};let W=typeof $.name==="string"?$.name.trim():"";if(!W)return{name:W,loadError:"empty MCP server name"};let Z=$.env,Q=Z===void 0?void 0:Z;if(Q!==void 0){if(!_6(Q))return{name:W,loadError:"invalid env"};for(let[V,B]of Object.entries(Q))if(typeof B!=="string"&&!sE(B))return{name:W,loadError:`invalid env "${V}"`}}let J=$.transport;if(!_6(J))return{name:W,loadError:"invalid MCP transport"};let j=J.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:W,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Q!==void 0)return{name:W,loadError:"top-level env is only supported for stdio MCP transports"};let X=_6($.metadata)?$.metadata:void 0;if(j==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:W,loadError:"stdio MCP transport requires command"};let B=J.args;if(B!==void 0&&!oE(B))return{name:W,loadError:"stdio MCP transport args must be strings"};let H=J.cwd;if(H!==void 0&&typeof H!=="string")return{name:W,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!zF(G))return{name:W,loadError:"stdio MCP transport env must be strings"};let K=tE({name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:G},env:Q,metadata:X});if(!K.ok)return{name:W,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:W,registration:{name:W,transport:{type:"stdio",command:V,args:B,cwd:H,env:F},metadata:X}}}if(typeof J.url!=="string"||!J.url.trim())return{name:W,loadError:`${j} MCP transport requires url`};let Y=J.headers;if(Y!==void 0&&!zF(Y))return{name:W,loadError:`${j} MCP transport headers must be strings`};return{name:W,registration:{name:W,transport:j==="sse"?{type:"sse",url:J.url,headers:Y}:{type:"streamableHttp",url:J.url,headers:Y},metadata:X}}}function $Q($){let W=new Map;return $.map(({server:Z,owner:Q,ownerLabel:J})=>{let j=gJ(Z);if(!j.registration)return{owner:Q,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let X=W.get(j.registration.name);if(W.has(j.registration.name)){let Y=X?` already registered by ${X}`:"";return{owner:Q,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${Y}`}}return W.set(j.registration.name,J),{owner:Q,name:j.registration.name,registration:j.registration}})}import{createHash as eE}from"node:crypto";var qF=64,$w=/[^a-zA-Z0-9_-]+/g,MF=8,Ww=1,Zw="mcp_tool";function Qw($){return eE("sha1").update($).digest("hex").slice(0,MF)}function Jw($){return $.replace($w,"_")}var WQ=({serverName:$,toolName:W})=>{let Z=`${$}__${W}`,Q=Jw(Z);if(Q===Z&&Z.length<=qF)return Z;let J=Qw(Z),j=qF-Ww-MF;return`${Q.slice(0,j)||Zw}_${J}`};function g5($){return{[($.nameTransform??WQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function ZQ($){let W={};for(let Z of $.toolNames)Object.assign(W,g5({serverName:$.serverName,toolName:Z,nameTransform:$.nameTransform}));return W}import{createTool as jw}from"@cline/shared";function Xw($,W){let Z=W.description?.trim();if(Z)return Z;return`Execute MCP tool "${W.name}" from server "${$}".`}async function f6($){let W=await $.provider.listTools($.serverName),Z=$.nameTransform??WQ;return W.map((Q)=>{let J=Z({serverName:$.serverName,toolName:Q.name});return jw({name:J,description:Xw($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,X)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:X})})})}_1();var wF={};w(wF,{listPluginToolsWithDiagnostics:()=>QQ,listPluginTools:()=>m5});import{stat as Yw}from"node:fs/promises";import{isAbsolute as Vw,relative as Bw,resolve as NF}from"node:path";_1();function Hw($,W){let Z=Bw(NF($),NF(W));return Z===""||!Z.startsWith("..")&&!Vw(Z)}var Gw=32,L6=new Map;function Kw($,W){if(!L6.has($)&&L6.size>=Gw){let Z=L6.keys().next().value;if(Z)L6.delete(Z)}L6.set($,W)}async function Fw($){let W=await Promise.all($.pluginPaths.map(async(Z)=>{try{let Q=await Yw(Z);return`${Z}:${Q.mtimeMs}:${Q.size}`}catch{return`${Z}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:W})}function EF($,W){return $.map((Z)=>({...Z,enabled:!W.has(Z.name)}))}function Aw($){return $.sort((W,Z)=>{let Q=W.name.localeCompare(Z.name);if(Q!==0)return Q;return W.path.localeCompare(Z.path)})}async function Uw($,W){if(!$.setup)return{tools:[]};let Z=[],Q={registerTool:(J)=>Z.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Q,{workspaceInfo:W}),{tools:Z}}async function QQ($){let W=e1({workspacePath:$.workspacePath,cwd:$.cwd}),Z=N1($.disabledToolNames);if(W.length===0)return{tools:[],failures:[],warnings:[]};let Q=await Fw({pluginPaths:W,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=L6.get(Q);if(J)return{tools:EF(J.tools,Z),failures:J.failures,warnings:J.warnings};let j=[],X=[],Y=[],V;try{V=await o8({pluginPaths:W,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),X=[...V.failures],Y=[...V.warnings];for(let H of V.extensions??[]){let G=H.__clinePluginPath;if(!G)continue;let K=Hw($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await Uw(H,{rootPath:$.workspacePath})}catch(A){X.push({pluginPath:G,pluginName:H.name,phase:"setup",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0});continue}for(let A of F.tools)j.push({name:A.name,pluginName:H.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(H){X=W.map((G)=>({pluginPath:G,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let B=Aw(j);return Kw(Q,{tools:B,failures:X,warnings:Y}),{tools:EF(B,Z),failures:X,warnings:Y}}async function m5($){return(await QQ($)).tools}function u5($,W){if(!W)return"global";let Z=yF(W,$);return!Z.startsWith("..")&&!bF(Z)?"workspace":"global"}function Lw($,W){return u5($,W)==="workspace"?"workspace-plugin":"global-plugin"}function Ow($,W){let Z=yF(PF($),PF(W));return Z===""||!Z.startsWith("..")&&!bF(Z)}function Tw($){try{let W=JSON.parse(Dw($,"utf8"));return typeof W.name==="string"&&W.name.trim()?W.name.trim():void 0}catch{return}}function zw($){let W=CF($);while(!0){let Z=fw(W,"package.json");if(c5(Z)){let J=Tw(Z);if(J)return J;break}let Q=CF(W);if(Q===W)break;W=Q}return mJ($,_w($))}function qw($){let W=[];for(let Z of e1({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let Q of $$([Z]))W.push({directory:Q,pluginName:zw(Z),pluginPath:Z,source:$.workspaceRoot?Lw(Z,$.workspaceRoot):"global-plugin"});return W.sort((Z,Q)=>Q.directory.length-Z.directory.length)}function Mw($,W){return W.find((Z)=>Ow(Z.directory,$))}function v5($){return[...$].sort((W,Z)=>{let Q=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(W.source!==Z.source)return Q(W.source)-Q(Z.source);return W.name.localeCompare(Z.name)})}function hF($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function kF($,W){return $.cwd?.trim()||W||process.cwd()}async function SF($,W){if($.userInstructionService)return await W($.userInstructionService);let Z=hF($),Q=kF($,Z),J=g$({skills:{workspacePath:Z||void 0,includePluginSkills:!0,cwd:Q},rules:{workspacePath:Z||void 0},workflows:{workspacePath:Z||void 0}});try{return await J.start(),await W(J)}finally{J.stop()}}function Rw($,W){if(!$)return;let Z=$.listRecords("skill");if(W.id){let Q=Z.find((J)=>J.id===W.id);if(Q)return Q}for(let Q of Z)if(Q.filePath===W.path||Q.item.name===W.name||Q.id===W.name)return Q;return}class c${async list($={}){return await SF($,async(W)=>{let Z=hF($),Q=qw({workspaceRoot:Z,cwd:kF($,Z)}),J=[],j=[],X=[],Y=[],V=[];if(W){for(let H of W.listRecords("workflow")){let G=H.item;J.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"workflow",source:u5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("rule")){let G=H.item;j.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"rule",source:u5(H.filePath,Z),description:G.instructions,toggleable:!1})}for(let H of W.listRecords("skill")){let G=H.item,K=Mw(H.filePath,Q);X.push({id:H.id,name:G.name,path:H.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??u5(H.filePath,Z),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Z)try{for(let H of await m5({workspacePath:Z,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))Y.push({id:`${H.pluginName}:${H.name}:${H.path}`,name:H.name,path:H.path,enabled:H.enabled,kind:"tool",source:H.source,description:H.description,toggleable:!0})}catch{}let B=Q0();if(Z$({filePath:B}))try{for(let H of W1({filePath:B}))V.push({id:H.name,name:H.name,path:B,enabled:H.disabled!==!0,kind:"mcp",source:u5(B,Z),description:H.transport.type,toggleable:!0})}catch{}return{workflows:v5(J.filter((H)=>c5(H.path))),rules:v5(j.filter((H)=>c5(H.path))),skills:v5(X.filter((H)=>c5(H.path))),tools:v5(Y),mcp:v5(V.filter((H)=>c5(H.path)))}})}async toggle($){if($.type==="skills")return await SF($,async(W)=>{let Z=Rw(W,$),Q=Z?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??mJ($.path??"")}'.`);let J=Z?.item&&"disabled"in Z.item?Z.item.disabled!==!0:void 0,j=$.enabled??(J!==void 0?!J:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??mJ($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await oK({filePath:Q,enabled:j}),await W?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:W}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)v9($.name);else BH($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let W=$.name?.trim()||$.id?.trim();if(!W)throw Error("MCP server settings toggle requires a server name.");let Z=$.path?.trim()||Q0(),Q=$.enabled;if(Q===void 0){let J=W1({filePath:Z}).find((j)=>j.name===W);if(!J)throw Error(`Unknown MCP server: ${W}`);Q=J.disabled===!0}return g2({filePath:Z,name:W,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function d2(){return new c$}function xF($){return{async list(W){let Z=$;if(Z.listSettings)return await Z.listSettings(W);return await d2().list(W)},async toggle(W){let Z=$;if(Z.toggleSetting)return await Z.toggleSetting(W);return await d2().toggle(W)}}}function gF($){function W(){let Z=$.pendingPrompts;if(!Z)throw Error("Pending prompt service is not available.");return Z}return{list(Z){return W().list(Z)},update(Z){return W().update(Z)},delete(Z){return W().delete(Z)}}}var mF={};w(mF,{splitCoreSessionConfig:()=>d5,isSessionNotFoundError:()=>J$,SessionNotFoundError:()=>Q$,SESSION_NOT_FOUND_ERROR_CODE:()=>l2});var l2="session_not_found";class Q$ extends Error{sessionId;code="session_not_found";constructor($,W){super(W??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function J$($){return $ instanceof Q$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function d5($){let{hooks:W,logger:Z,telemetry:Q,extensionContext:J,extraTools:j,extensions:X,onTeamEvent:Y,onConsecutiveMistakeLimitReached:V,checkpoint:B,compaction:H,...G}=$,K={};if(W)K.hooks=W;if(Z)K.logger=Z;if(Q)K.telemetry=Q;if(J)K.extensionContext=J;if(j)K.extraTools=j;if(X)K.extensions=X;if(Y)K.onTeamEvent=Y;if(V)K.onConsecutiveMistakeLimitReached=V;if(B?.createCheckpoint)K.checkpoint=B;if(H?.compact)K.compaction=H;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...B?{checkpoint:{enabled:B.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,preserveRecentTokens:H.preserveRecentTokens,summarizer:H.summarizer}}:{}},...F?{localRuntime:F}:{}}}function vF($){let W=$.config;return"providerId"in W?{...$,config:{...W,...Nw($.localRuntime)},localRuntime:$.localRuntime}:$}function vJ($,W={}){let Z=d5($.config),Q=w0(W.defaultCapabilities,$.capabilities),J=Ew(Z.localRuntime,$.localRuntime),j=W.withExtensionContext?.(J?.extensionContext);if(j)J={...J??{},extensionContext:j};return{...$,...Z,...J?{localRuntime:J}:{},...Q?{capabilities:Q}:{}}}function Nw($){if(!$)return{};let{modelCatalogDefaults:W,userInstructionService:Z,configExtensions:Q,onTeamRestored:J,...j}=$;return j}function Ew(...$){let W={};for(let Z of $)if(Z)Object.assign(W,Z);return Object.keys(W).length>0?W:void 0}U0();function cF($){let W=$.input.config.telemetry??$.telemetry;if(!W)return;W.capture({event:m.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??K0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function l5($){return!!$&&typeof $==="object"&&!Array.isArray($)}function cJ($){let W=$?.trim();return W?W:void 0}function ww($,W){let Z=$?.trim();if(!Z)return W;let Q=Date.parse(Z);if(!Number.isFinite(Q))return W;return new Date(Q).toISOString()}function uF($,W){return new Date(new Date($).getTime()+Math.max(0,Math.floor(W))*1000).toISOString()}function dF($,W){return new Date(new Date($).getTime()-Math.max(0,Math.floor(W))*1000).toISOString()}function Cw($,W){if(!$)return W;return new Date($).getTime()>=new Date(W).getTime()?$:W}function Pw($,W){let Z=$.eventId.trim(),Q=$.eventType.trim(),J=$.source.trim(),j=cJ($.subject),X=cJ($.dedupeKey)??`${Q}:${J}:${j??Z}`;return{eventId:Z,eventType:Q,source:J,subject:j,occurredAt:ww($.occurredAt,W),workspaceRoot:cJ($.workspaceRoot),payload:l5($.payload)?$.payload:void 0,attributes:l5($.attributes)?$.attributes:void 0,dedupeKey:X}}function uJ($,W){if(!W)return;let Z=W.split("."),Q=$;for(let J of Z){if(!l5(Q))return;Q=Q[J]}return Q}function Sw($,W){if($.attributes&&Object.hasOwn($.attributes,W))return $.attributes[W];if($.payload&&Object.hasOwn($.payload,W))return $.payload[W];let Z={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=uJ(Z,W);if(Q!==void 0)return Q;if($.attributes){let J=uJ($.attributes,W);if(J!==void 0)return J}if($.payload)return uJ($.payload,W);return}function JQ($,W){if(Array.isArray(W))return W.some((Z)=>JQ($,Z));if(Array.isArray($))return $.some((Z)=>JQ(Z,W));if(l5(W)){if(!l5($))return!1;return Object.entries(W).every(([Z,Q])=>JQ($[Z],Q))}return Object.is($,W)}function bw($,W){if(!W||Object.keys(W).length===0)return!0;return Object.entries(W).every(([Z,Q])=>JQ(Sw($,Z),Q))}class dJ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let W=new Date(this.nowFn()).toISOString(),Z=Pw($,W),Q=this.store.insertEventLog(Z,{receivedAtIso:W});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Z.eventType),j=[],X=[],Y=[];for(let H of J){if(!bw(Z,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Z.dedupeKey});continue}X.push(H);let G=this.materializeForSpec(H,Z,Q.record.receivedAt);if(G.run)Y.push(G.run);else j.push({specId:H.specId,externalId:H.externalId,reason:G.reason,dedupeKey:Z.dedupeKey})}let V=X.length===0?"unmatched":Y.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:V,matchedSpecCount:X.length,queuedRunCount:Y.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let B=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:V,matchedSpecCount:X.length,queuedRunCount:Y.length}),{event:B??Q.record,duplicate:!1,matchedSpecs:X,queuedRuns:Y,suppressions:j}}catch(J){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:J});throw J}}materializeForSpec($,W,Z){let Q=W.dedupeKey??W.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(V){let B=Cw(V.scheduledFor,uF(Z,J)),H=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:W.eventId,scheduledFor:B});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:dF(Z,j)}))return{reason:"dedupe_window"};let X=$.cooldownSeconds??0;if(X>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:dF(Z,X)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:W.eventId,scheduledFor:J>0?uF(Z,J):Z}),reason:"dedupe_window"}}}class p5{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},W=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of W)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let Z=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of Z)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as mw}from"node:path";import{buildClineSystemPrompt as vw}from"@cline/shared";import{nowIso as lF}from"@cline/shared/db";import{mkdirSync as yw,writeFileSync as hw}from"node:fs";import{join as kw}from"node:path";import{resolveCronReportsDir as Iw}from"@cline/shared/storage";function u$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function p2($,W){if(W===void 0||W===null)return;return`${$}: ${u$(W)}`}function xw($,W,Z){let Q=[`runId: ${u$($.runId)}`,`specId: ${u$(W.specId)}`,`externalId: ${u$(W.externalId)}`,`title: ${u$(W.title)}`,`triggerKind: ${u$($.triggerKind)}`,`status: ${u$($.status)}`,`sourcePath: ${u$(W.sourcePath)}`],J=[p2("sessionId",$.sessionId),p2("startedAt",$.startedAt),p2("completedAt",$.completedAt),p2("triggerEventId",$.triggerEventId),p2("triggerEventType",Z?.eventType),p2("triggerEventSource",Z?.source),p2("triggerEventSubject",Z?.subject)];for(let j of J)if(j)Q.push(j);return`---
235
235
  ${Q.join(`
236
236
  `)}
237
237
  ---
238
- `}function bw($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
238
+ `}function gw($){let W=[];if($.triggerEvent){let Z=$.triggerEvent,Q=[`- eventId: ${Z.eventId}`,`- eventType: ${Z.eventType}`,`- source: ${Z.source}`,Z.subject?`- subject: ${Z.subject}`:"",`- occurredAt: ${Z.occurredAt}`,Z.dedupeKey?`- dedupeKey: ${Z.dedupeKey}`:"",Z.attributes?`- attributes: ${JSON.stringify(Z.attributes)}`:""].filter((J)=>J.length>0);W.push(`## Trigger Event
239
239
 
240
240
  ${Q.join(`
241
241
  `)}
@@ -254,17 +254,17 @@ ${Q.join(`
254
254
  ${Z.join(`
255
255
  `)}
256
256
  `)}return W.join(`
257
- `)}function lJ($){let W=Pw($.specs);Ew(W,{recursive:!0});let Z=Cw(W,`${$.run.runId}.md`),Q=`${Sw($.run,$.spec,$.data.triggerEvent)}
258
- ${bw($.data)}`;return ww(Z,Q,"utf8"),Z}class pJ{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var kw=15000,Iw=90,lF=["rules","skills","plugins"];function xw($,W){return new Set($.extensions??lF).has(W)}function gw($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[z0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function mw($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
259
- `)}class rJ extends Error{constructor($){super($);this.name="TimeoutError"}}async function vw($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new rJ("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class p5{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new pJ($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??Iw)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let $=Math.max(2000,this.options.pollIntervalMs??kw);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:dF(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await vw(F,A)).result,f=Date.now(),_=lJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:f-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:_,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,dF())}catch(H){let G=H instanceof rJ;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=lJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
257
+ `)}function lJ($){let W=Iw($.specs);yw(W,{recursive:!0});let Z=kw(W,`${$.run.runId}.md`),Q=`${xw($.run,$.spec,$.data.triggerEvent)}
258
+ ${gw($.data)}`;return hw(Z,Q,"utf8"),Z}class pJ{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,W,Z){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(Z)),J=this.activeExecutions.get($)??new Set;if(J.size>=Q)return!1;return J.add(W),this.activeExecutions.set($,J),!0}release($,W){let Z=this.activeExecutions.get($);if(!Z)return;if(Z.delete(W),Z.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let W of this.activeExecutions.values())$+=W.size;return $}}var cw=15000,uw=90,pF=["rules","skills","plugins"];function dw($,W){return new Set($.extensions??pF).has(W)}function lw($,W){if($.tools===void 0)return{"*":{autoApprove:!0}};let Z={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)Z[Q]={enabled:!0,autoApprove:!0};if(W==="yolo")Z[T0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Z}function pw($){let W=$?.trim();if(!W)return;return["# Notes Directory",`Use ${W} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
259
+ `)}class rJ extends Error{constructor($){super($);this.name="TimeoutError"}}async function rw($,W){if(W<=0)return $;let Z,Q=new Promise((J,j)=>{Z=setTimeout(()=>{j(new rJ("cron run timed out"))},W)});try{return await Promise.race([$,Q])}finally{if(Z)clearTimeout(Z)}}class r5{store;materializer;options;limiter;claimLeaseMs;timer;started=!1;ticking=!1;disposed=!1;stopping=!1;activeRuns=new Map;constructor($){this.store=$.store,this.materializer=$.materializer,this.options=$,this.limiter=new pJ($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??uw)*1000)}async start(){if(this.disposed)throw Error("CronRunner disposed");if(this.started)return;this.stopping=!1,this.started=!0;let $=Math.max(2000,this.options.pollIntervalMs??cw);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let W=[...this.activeRuns.entries()];await Promise.all(W.map(async([Z,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:Z,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:lF(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((W)=>this.executeClaim(W)))}catch($){let W=this.options.logger;if(W)if(W.error)W.error("cron.runner.tick.failed",{error:$});else W.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,W])=>{let Z=this.store.getRun($);return Z?[{...Z,...W}]:[]})}async executeClaim($){let W=$.run,Z=this.store.getSpec(W.specId);if(!Z){this.store.completeRun(W.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Z.enabled||Z.removed){this.store.completeRun(W.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=Z.maxParallel&&Z.maxParallel>0?Z.maxParallel:1;if(!this.limiter.acquire(Z.specId,W.runId,Q)){this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Z.specId,W.runId),this.store.requeueRun({runId:W.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(W.runId,{claimToken:$.claimToken});let j=W.triggerEventId?this.store.getEventLog(W.triggerEventId):void 0,X,Y,V=Date.now(),B;if(Z.timeoutSeconds&&Z.timeoutSeconds>0)B=V+Z.timeoutSeconds*1000;try{Y=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Z);if(X=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!X)throw Error("runtime returned empty sessionId");this.activeRuns.set(W.runId,{claimToken:$.claimToken,sessionId:X}),this.store.attachSessionIdToRun(W.runId,X);let K={config:H,prompt:this.buildPrompt(Z,j)},F=this.options.runtimeHandlers.sendSession(X,K),A=B?Math.max(1,B-Date.now()):0,U=(await rw(F,A)).result,f=Date.now(),_=lJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"done"},spec:Z,data:{finalText:U.text,usage:U.usage,toolCalls:U.toolCalls,durationMs:f-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"done",sessionId:X,reportPath:_,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Z,W.runId),this.store.updateSpecLastRunAt(Z.specId,lF())}catch(H){let G=H instanceof rJ;if(X&&G)try{await this.options.runtimeHandlers.abortSession(X)}catch{}let K=H instanceof Error?H.message:String(H),F=Date.now(),A=lJ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...W,sessionId:X,status:"failed"},spec:Z,data:{error:K,durationMs:F-V,triggerEvent:j}});this.store.completeRun(W.runId,{status:"failed",sessionId:X,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Z,W.runId)}finally{if(Y?.(),X)try{await this.options.runtimeHandlers.stopSession(X)}catch{}this.activeRuns.delete(W.runId),this.limiter.release(Z.specId,W.runId)}}publishScheduleExecutionEvent($,W,Z){if(W.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(Z);if(!Q)return;let J=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:W.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:J,errorMessage:Q.error})}buildPrompt($,W){let Z=$.prompt??"";if(!W)return Z;let Q={eventId:W.eventId,eventType:W.eventType,source:W.source,subject:W.subject,occurredAt:W.occurredAt,workspaceRoot:W.workspaceRoot,dedupeKey:W.dedupeKey,attributes:W.attributes,payload:W.payload};return`${Z}
260
260
 
261
261
  Trigger event:
262
- ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=mw($.notesDirectory),j=G6(void 0,J),X=await U5(W),Y=hw({ide:"Cline Cron",workspaceRoot:W,workspaceName:yw(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?G6(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:gw($,X),configExtensions:lF.filter((Y)=>xw($,Y))}}}import{existsSync as BC,readdirSync as HC,readFileSync as GC,statSync as KC}from"node:fs";import{relative as FC}from"node:path";import{resolveCronSpecsDir as AC}from"@cline/shared/storage";function r5($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var cw=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],rF=["sun","mon","tue","wed","thu","fri","sat"];function i5($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function iJ($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function nJ($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:r5(i5(W,0,$),0,59),hours:r5(i5(W,1,$),0,23),daysOfMonth:r5(i5(W,2,$),1,31),months:r5(i5(W,3,$),1,12,cw),daysOfWeek:r5(i5(W,4,$),0,6,rF)}}function aJ($){nJ($)}function iF($,W,Z=Date.now()){r2($,Z,W)}var pF=new Map,uw=new Map(rF.map(($,W)=>[$,W]));function nF($){let W=$?.trim();return W?W:void 0}function aF($){let W=pF.get($);if(W)return W;let Z=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return pF.set($,Z),Z}function dw($){let W=nF($);if(!W)return;aF(W).format(new Date)}function lw($,W){let Z=aF(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=uw.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function pw($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function rw($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function iw($,W,Z){let Q=nJ($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(rw(Q,lw(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function r2($,W,Z){let Q=nF(Z);if(Q)return dw(Q),iw($,W,Q);let J=nJ($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=pw(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??iJ(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??iJ(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??iJ(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as nw}from"node:crypto";import aw from"yaml";function ow($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function sw($){let W=$.replace(/\r\n/g,`
262
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Z=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(Z)},W);return()=>clearInterval(Z)}async buildSystemPrompt($,W,Z,Q){let J=pw($.notesDirectory),j=K6(void 0,J),X=await D5(W),Y=vw({ide:"Cline Cron",workspaceRoot:W,workspaceName:mw(W),metadata:X,rules:$.systemPrompt?void 0:j,mode:Z,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?K6(Y,j)??Y:Y}async buildStartRequest($){let W=($.workspaceRoot??"").trim(),Z=($.providerId??"").trim(),Q=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():W;if(!W)throw Error("cron spec requires workspaceRoot");let X=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:W,cwd:j,provider:Z,model:Q,mode:X,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,W,X,Z),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:lw($,X),configExtensions:pF.filter((Y)=>dw($,Y))}}}import{existsSync as UC,readdirSync as DC,readFileSync as _C,statSync as fC}from"node:fs";import{relative as LC}from"node:path";import{resolveCronSpecsDir as OC}from"@cline/shared/storage";function i5($,W,Z,Q){let J=new Set;function j(X){let Y=X.toLowerCase();if(Q){let B=Q.indexOf(Y);if(B!==-1)return B+W}let V=Number(X);if(!Number.isInteger(V)||V<W||V>Z)throw Error(`Invalid cron value "${X}" for range [${W}-${Z}]`);return V}for(let X of $.split(",")){if(X==="*"){for(let B=W;B<=Z;B+=1)J.add(B);continue}let Y=X.indexOf("/");if(Y!==-1){let B=X.slice(0,Y),H=Number(X.slice(Y+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${X.slice(Y+1)}"`);let G=W,K=Z;if(B!=="*"){let F=B.indexOf("-");if(F!==-1)G=j(B.slice(0,F)),K=j(B.slice(F+1));else G=j(B)}if(G>K)throw Error(`Invalid cron range "${B}"`);for(let F=G;F<=K;F+=H)J.add(F);continue}let V=X.indexOf("-");if(V!==-1){let B=j(X.slice(0,V)),H=j(X.slice(V+1));if(B>H)throw Error(`Invalid cron range "${X}"`);for(let G=B;G<=H;G+=1)J.add(G);continue}J.add(j(X))}return[...J].sort((X,Y)=>X-Y)}var iw=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],iF=["sun","mon","tue","wed","thu","fri","sat"];function n5($,W,Z){let Q=$[W];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${Z}": missing field ${W+1}`);return Q}function iJ($,W){let Z=$[0];if(typeof Z!=="number")throw Error(`Invalid cron pattern: no values parsed for ${W}`);return Z}function nJ($){let W=$.trim().split(/\s+/);if(W.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${W.length}`);return{minutes:i5(n5(W,0,$),0,59),hours:i5(n5(W,1,$),0,23),daysOfMonth:i5(n5(W,2,$),1,31),months:i5(n5(W,3,$),1,12,iw),daysOfWeek:i5(n5(W,4,$),0,6,iF)}}function aJ($){nJ($)}function nF($,W,Z=Date.now()){r2($,Z,W)}var rF=new Map,nw=new Map(iF.map(($,W)=>[$,W]));function aF($){let W=$?.trim();return W?W:void 0}function oF($){let W=rF.get($);if(W)return W;let Z=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return rF.set($,Z),Z}function aw($){let W=aF($);if(!W)return;oF(W).format(new Date)}function ow($,W){let Z=oF(W).formatToParts(new Date($)),Q=new Map(Z.map((X)=>[X.type,X.value])),J=Q.get("weekday")?.toLowerCase().slice(0,3)??"",j=nw.get(J);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${W}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:j,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function sw($){let W=new Date($);return{month:W.getMonth()+1,dayOfMonth:W.getDate(),dayOfWeek:W.getDay(),hour:W.getHours(),minute:W.getMinutes()}}function tw($,W){return $.months.includes(W.month)&&$.daysOfMonth.includes(W.dayOfMonth)&&$.daysOfWeek.includes(W.dayOfWeek)&&$.hours.includes(W.hour)&&$.minutes.includes(W.minute)}function ew($,W,Z){let Q=nJ($),J=new Date(W);J.setSeconds(0,0);let j=J.getTime()+60000,X=new Date(W);X.setFullYear(X.getFullYear()+4);let Y=X.getTime();while(j<=Y){if(tw(Q,ow(j,Z)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Z}"`)}function r2($,W,Z){let Q=aF(Z);if(Q)return aw(Q),ew($,W,Q);let J=nJ($),j=new Date(W);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let X=new Date(W);X.setFullYear(X.getFullYear()+4);while(j<=X){let{month:Y,dayOfMonth:V,dayOfWeek:B,hour:H,minute:G}=sw(j.getTime());if(!J.months.includes(Y)){let K=J.months.find((A)=>A>Y)??iJ(J.months,"months"),F=K<=Y?1:0;j=new Date(j.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(B)){j=new Date(j.getFullYear(),j.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(H)){let K=J.hours.find((A)=>A>H)??iJ(J.hours,"hours"),F=K<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??iJ(J.minutes,"minutes"),F=K<=G?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+F,K,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as $C}from"node:crypto";import WC from"yaml";function ZC($){let W=$.replace(/\\/g,"/");if(W.startsWith("events/")&&W.endsWith(".event.md"))return"event";if(W.endsWith(".cron.md"))return"schedule";return"one_off"}function QC($){let W=$.replace(/\r\n/g,`
263
263
  `);if(!W.startsWith(`---
264
264
  `))return{frontmatter:void 0,body:$};let Z=W.slice(4),Q=Z.indexOf(`
265
265
  ---`);if(Q===-1)return{frontmatter:void 0,body:$};let J=Z.slice(0,Q),j=Z.slice(Q+4);if(j.startsWith(`
266
- `))j=j.slice(1);return{frontmatter:J,body:j}}function $1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function tw($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function tJ($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function ew($){let W=tJ($);if(!W)return;let Z=$1(W.providerId),Q=$1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function $C($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function sF($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var WC=new Set(L$);function ZC($){let W=sF($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!WC.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var QC=new Set(["rules","skills","plugins"]);function JC($){let W=sF($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!QC.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function oJ($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function sJ($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function eJ($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>eJ(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${eJ(Q)}`).join(",")}}`}function tF($,W){let Z=nw("sha256");return Z.update(eJ($)),Z.update(`
267
- `),Z.update(W),Z.digest("hex")}function jC($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var XC=["schedule","timezone"],YC=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],VC=["cwd"];function oF($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:tF(Q,Z),error:J}}function E1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function eF($){let W=$.relativePath.replace(/\\/g,"/"),Z=ow(W),{frontmatter:Q,body:J}=sw($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let _=aw.parse(Q);if(_&&typeof _==="object"&&!Array.isArray(_))j=_;else if(_!==null&&_!==void 0)return oF(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(_){return oF(W,Z,J,{},_ instanceof Error?`failed to parse frontmatter: ${_.message}`:"failed to parse frontmatter")}let X=tF(j,J),Y=$1(j.id),V=Y??W;if(Z!=="schedule"){for(let _ of XC)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on *.cron.md specs`)}for(let _ of VC)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let _ of YC)if(j[_]!==void 0)return E1(V,W,Z,J,X,`field "${_}" is only allowed on .event.md specs`)}let B=$1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return E1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=$1(j.workspaceRoot);if(!K)return E1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=ZC(j.tools),A=JC(j.extensions)}catch(_){return E1(V,W,Z,J,X,_ instanceof Error?_.message:String(_))}let D=$C(j.mode);if(j.mode!==void 0&&D===void 0)return E1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:$1(j.title)??Y??jC(W),prompt:G,workspaceRoot:K,mode:D??"yolo",systemPrompt:$1(j.systemPrompt),modelSelection:ew(j.modelSelection),maxIterations:oJ(j.maxIterations),timeoutSeconds:oJ(j.timeoutSeconds),tools:F,notesDirectory:$1(j.notesDirectory),extensions:A,source:$1(j.source)??"user",tags:tw(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:tJ(j.metadata)},f;if(Z==="schedule"){let _=$1(j.schedule);if(!_)return E1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let R=$1(j.timezone);try{iF(_,R)}catch(O){return E1(V,W,Z,J,X,O instanceof Error?O.message:String(O))}f={...U,triggerKind:"schedule",schedule:_,timezone:R}}else if(Z==="event"){let _=$1(j.event);if(!_)return E1(V,W,Z,J,X,"event is required for .event.md specs");f={...U,triggerKind:"event",event:_,filters:tJ(j.filters),debounceSeconds:sJ(j.debounceSeconds),dedupeWindowSeconds:sJ(j.dedupeWindowSeconds),cooldownSeconds:sJ(j.cooldownSeconds),maxParallel:oJ(j.maxParallel)}}else f={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:f}}function UC($,W){return FC($,W).replace(/\\/g,"/")}function DC($){if(!BC($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=HC(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class $j{store;cronDir;constructor($){this.store=$.store,this.cronDir=AC($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=DC(this.cronDir),Z=new Set;for(let J of W){let j=UC(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=GC(W,"utf8"),J=KC(W).mtimeMs}catch{return}let X=eF({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=r2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as _C,mkdirSync as fC,watch as LC}from"node:fs";import{relative as OC,resolve as TC}from"node:path";var zC=250;class Wj{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??zC),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{fC($,{recursive:!0}),this.watcher=LC($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=TC(this.reconciler.getCronDir(),$);if(!_C(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=OC(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}import{randomUUID as n5}from"node:crypto";import{asOptionalString as c,asString as J0,loadSqliteDb as MC,nowIso as P0}from"@cline/shared/db";import{resolveCronDbPath as RC}from"@cline/shared/storage";var qC=[`CREATE TABLE IF NOT EXISTS cron_specs (
266
+ `))j=j.slice(1);return{frontmatter:J,body:j}}function Q1($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function JC($){if(!Array.isArray($))return;let W=$.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);return W.length>0?W:void 0}function tJ($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function jC($){let W=tJ($);if(!W)return;let Z=Q1(W.providerId),Q=Q1(W.modelId);if(Z===void 0&&Q===void 0)return;return{providerId:Z,modelId:Q}}function XC($){if(typeof $!=="string")return;let W=$.trim().toLowerCase();if(W==="act"||W==="plan"||W==="yolo")return W;return}function tF($,W={}){let Z=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Z)return;let Q=[...new Set(Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&W.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var YC=new Set(O$);function VC($){let W=tF($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!YC.has(Q));if(Z.length>0)throw Error(`unknown tool(s): ${Z.join(", ")}`);return W}var BC=new Set(["rules","skills","plugins"]);function HC($){let W=tF($,{preserveEmptyArray:!0});if(!W)return;let Z=W.filter((Q)=>!BC.has(Q));if(Z.length>0)throw Error(`unknown extension(s): ${Z.join(", ")}`);return W}function oJ($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function sJ($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function eJ($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Z)=>eJ(Z)).join(",")}]`;let W=Object.entries($).filter(([,Z])=>Z!==void 0);return W.sort(([Z],[Q])=>Z<Q?-1:Z>Q?1:0),`{${W.map(([Z,Q])=>`${JSON.stringify(Z)}:${eJ(Q)}`).join(",")}}`}function eF($,W){let Z=$C("sha256");return Z.update(eJ($)),Z.update(`
267
+ `),Z.update(W),Z.digest("hex")}function GC($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var KC=["schedule","timezone"],FC=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],AC=["cwd"];function sF($,W,Z,Q,J){return{externalId:$,relativePath:$,triggerKind:W,body:Z,contentHash:eF(Q,Z),error:J}}function w1($,W,Z,Q,J,j){return{externalId:$,relativePath:W,triggerKind:Z,body:Q,contentHash:J,error:j}}function $A($){let W=$.relativePath.replace(/\\/g,"/"),Z=ZC(W),{frontmatter:Q,body:J}=QC($.raw),j={};if(Q!==void 0&&Q.trim().length>0)try{let _=WC.parse(Q);if(_&&typeof _==="object"&&!Array.isArray(_))j=_;else if(_!==null&&_!==void 0)return sF(W,Z,J,{},"frontmatter must be a YAML mapping")}catch(_){return sF(W,Z,J,{},_ instanceof Error?`failed to parse frontmatter: ${_.message}`:"failed to parse frontmatter")}let X=eF(j,J),Y=Q1(j.id),V=Y??W;if(Z!=="schedule"){for(let _ of KC)if(j[_]!==void 0)return w1(V,W,Z,J,X,`field "${_}" is only allowed on *.cron.md specs`)}for(let _ of AC)if(j[_]!==void 0)return w1(V,W,Z,J,X,`field "${_}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Z!=="event"){for(let _ of FC)if(j[_]!==void 0)return w1(V,W,Z,J,X,`field "${_}" is only allowed on .event.md specs`)}let B=Q1(j.prompt),H=J.trim(),G=B??(H.length>0?H:void 0);if(!G)return w1(V,W,Z,J,X,"prompt is required (frontmatter `prompt` or markdown body)");let K=Q1(j.workspaceRoot);if(!K)return w1(V,W,Z,J,X,"workspaceRoot is required");let F,A;try{F=VC(j.tools),A=HC(j.extensions)}catch(_){return w1(V,W,Z,J,X,_ instanceof Error?_.message:String(_))}let D=XC(j.mode);if(j.mode!==void 0&&D===void 0)return w1(V,W,Z,J,X,"mode must be one of: act, plan, yolo");let U={id:Y,title:Q1(j.title)??Y??GC(W),prompt:G,workspaceRoot:K,mode:D??"yolo",systemPrompt:Q1(j.systemPrompt),modelSelection:jC(j.modelSelection),maxIterations:oJ(j.maxIterations),timeoutSeconds:oJ(j.timeoutSeconds),tools:F,notesDirectory:Q1(j.notesDirectory),extensions:A,source:Q1(j.source)??"user",tags:JC(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:tJ(j.metadata)},f;if(Z==="schedule"){let _=Q1(j.schedule);if(!_)return w1(V,W,Z,J,X,"schedule is required for *.cron.md specs");let R=Q1(j.timezone);try{nF(_,R)}catch(O){return w1(V,W,Z,J,X,O instanceof Error?O.message:String(O))}f={...U,triggerKind:"schedule",schedule:_,timezone:R}}else if(Z==="event"){let _=Q1(j.event);if(!_)return w1(V,W,Z,J,X,"event is required for .event.md specs");f={...U,triggerKind:"event",event:_,filters:tJ(j.filters),debounceSeconds:sJ(j.debounceSeconds),dedupeWindowSeconds:sJ(j.dedupeWindowSeconds),cooldownSeconds:sJ(j.cooldownSeconds),maxParallel:oJ(j.maxParallel)}}else f={...U,triggerKind:"one_off"};return{externalId:V,relativePath:W,triggerKind:Z,body:J,contentHash:X,spec:f}}function TC($,W){return LC($,W).replace(/\\/g,"/")}function zC($){if(!UC($))return[];let W=[],Z=[$];while(Z.length>0){let Q=Z.pop();if(!Q)continue;let J;try{J=DC(Q,{withFileTypes:!0})}catch{continue}for(let j of J){let X=`${Q}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Z.push(X);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;W.push(X)}}return W}class $j{store;cronDir;constructor($){this.store=$.store,this.cronDir=OC($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},W=zC(this.cronDir),Z=new Set;for(let J of W){let j=TC(this.cronDir,J);Z.add(j),$.scanned+=1;let X=await this.reconcileFile(j,J);if(X){if($.changes.push(X),$.upserted+=1,X.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of Q)if(!Z.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,W){let Z=this.store.getSpecBySourcePath($),Q,J;try{Q=_C(W,"utf8"),J=fC(W).mtimeMs}catch{return}let X=$A({relativePath:$,raw:Q}),Y=this.store.upsertSpec({externalId:X.externalId,sourcePath:$,triggerKind:X.triggerKind,sourceMtimeMs:J,sourceHash:X.contentHash,parseStatus:X.error?"invalid":"valid",parseError:X.error,spec:X.spec});if(!X.error&&X.triggerKind==="schedule"&&Y.record.enabled)this.applyScheduleNextRunAt(Y.record,{forceReset:!Z||Z.removed||!Z.enabled||Z.scheduleExpr!==Y.record.scheduleExpr||Z.timezone!==Y.record.timezone});return{relativePath:$,result:Y,parse:X}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of $)this.applyScheduleNextRunAt(W,{forceReset:!1})}applyScheduleNextRunAt($,W){if(!$.scheduleExpr)return;if(!W.forceReset&&$.nextRunAt)return;try{let Z=Date.now(),Q=$.lastRunAt?Math.max(Z,new Date($.lastRunAt).getTime()):Z,J=r2($.scheduleExpr,Q,$.timezone),j=new Date(J).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as qC,mkdirSync as MC,watch as RC}from"node:fs";import{relative as NC,resolve as EC}from"node:path";var wC=250;class Wj{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??wC),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{MC($,{recursive:!0}),this.watcher=RC($,{recursive:!0},(W,Z)=>{if(!Z)return;let Q=String(Z).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(W){this.onError(W)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let W=this.pending.get($);if(W)clearTimeout(W);let Z=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Z)}async reconcileNow($){try{let W=EC(this.reconciler.getCronDir(),$);if(!qC(W)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Z=NC(this.reconciler.getCronDir(),W).replace(/\\/g,"/");await this.reconciler.reconcileFile(Z,W),await this.onReconciled()}catch(W){this.onError(W)}}}import{randomUUID as a5}from"node:crypto";import{asOptionalString as u,asString as J0,loadSqliteDb as PC,nowIso as C0}from"@cline/shared/db";import{resolveCronDbPath as SC}from"@cline/shared/storage";var CC=[`CREATE TABLE IF NOT EXISTS cron_specs (
268
268
  spec_id TEXT PRIMARY KEY,
269
269
  external_id TEXT NOT NULL,
270
270
  source_path TEXT NOT NULL UNIQUE,
@@ -355,17 +355,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
355
355
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
356
356
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
357
357
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
358
- ON cron_specs(source_path);`];function $A($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of qC)$.exec(W)}function jQ($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function Zj($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function i2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function u$($){return{specId:J0($.spec_id),externalId:J0($.external_id),sourcePath:J0($.source_path),triggerKind:J0($.trigger_kind),sourceMtimeMs:i2($.source_mtime_ms),sourceHash:c($.source_hash),parseStatus:J0($.parse_status)==="invalid"?"invalid":"valid",parseError:c($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:J0($.title),prompt:c($.prompt),workspaceRoot:c($.workspace_root),scheduleExpr:c($.schedule_expr),timezone:c($.timezone),eventType:c($.event_type),filters:jQ(c($.filters_json)),debounceSeconds:i2($.debounce_seconds),dedupeWindowSeconds:i2($.dedupe_window_seconds),cooldownSeconds:i2($.cooldown_seconds),mode:c($.mode),systemPrompt:c($.system_prompt),providerId:c($.provider_id),modelId:c($.model_id),maxIterations:i2($.max_iterations),timeoutSeconds:i2($.timeout_seconds),maxParallel:i2($.max_parallel),tools:Zj(c($.tools_json),{preserveEmpty:!0}),notesDirectory:c($.notes_directory),extensions:Zj(c($.extensions_json),{preserveEmpty:!0}),source:c($.source),tags:Zj(c($.tags_json)),metadata:jQ(c($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:c($.last_materialized_run_id),lastRunAt:c($.last_run_at),nextRunAt:c($.next_run_at),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function Qj($){return{runId:J0($.run_id),specId:J0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:J0($.trigger_kind),status:J0($.status),claimToken:c($.claim_token),claimStartedAt:c($.claim_started_at),claimUntilAt:c($.claim_until_at),scheduledFor:c($.scheduled_for),triggerEventId:c($.trigger_event_id),startedAt:c($.started_at),completedAt:c($.completed_at),sessionId:c($.session_id),reportPath:c($.report_path),error:c($.error),attemptCount:Number($.attempt_count??0),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function WA($){return{eventId:J0($.event_id),eventType:J0($.event_type),source:J0($.source),subject:c($.subject),occurredAt:J0($.occurred_at),receivedAt:J0($.received_at),workspaceRoot:c($.workspace_root),dedupeKey:c($.dedupe_key),payload:jQ(c($.payload_json)),attributes:jQ(c($.attributes_json)),processingStatus:J0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:c($.error),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function ZA($){return $?JSON.stringify($):null}var NC=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function QA($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function EC($,W,Z,Q){for(let J of NC){let j=$[J],X=W[J];if(QA(j)!==QA(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function wC($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function CC($){return`hub/schedules/${$}.cron.md`}function PC($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function Jj($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:PC($)}}function JA($){return JSON.stringify(Jj($))}function SC($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class a5{db;constructor($={}){let W=$.dbPath??RC();this.db=MC(W),$A(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?u$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?u$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?u$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>u$(X))}createHubSchedule($){let W=`sched_${n5()}`,Z=this.upsertSpec({externalId:W,sourcePath:CC(W),triggerKind:"schedule",sourceHash:JA($),parseStatus:"valid",spec:Jj($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
358
+ ON cron_specs(source_path);`];function WA($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let W of CC)$.exec(W)}function jQ($){if(!$)return;try{let W=JSON.parse($);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return}function Zj($,W={}){if(!$)return;try{let Z=JSON.parse($);if(!Array.isArray(Z))return;let Q=Z.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(W.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function i2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function d$($){return{specId:J0($.spec_id),externalId:J0($.external_id),sourcePath:J0($.source_path),triggerKind:J0($.trigger_kind),sourceMtimeMs:i2($.source_mtime_ms),sourceHash:u($.source_hash),parseStatus:J0($.parse_status)==="invalid"?"invalid":"valid",parseError:u($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:J0($.title),prompt:u($.prompt),workspaceRoot:u($.workspace_root),scheduleExpr:u($.schedule_expr),timezone:u($.timezone),eventType:u($.event_type),filters:jQ(u($.filters_json)),debounceSeconds:i2($.debounce_seconds),dedupeWindowSeconds:i2($.dedupe_window_seconds),cooldownSeconds:i2($.cooldown_seconds),mode:u($.mode),systemPrompt:u($.system_prompt),providerId:u($.provider_id),modelId:u($.model_id),maxIterations:i2($.max_iterations),timeoutSeconds:i2($.timeout_seconds),maxParallel:i2($.max_parallel),tools:Zj(u($.tools_json),{preserveEmpty:!0}),notesDirectory:u($.notes_directory),extensions:Zj(u($.extensions_json),{preserveEmpty:!0}),source:u($.source),tags:Zj(u($.tags_json)),metadata:jQ(u($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:u($.last_materialized_run_id),lastRunAt:u($.last_run_at),nextRunAt:u($.next_run_at),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function Qj($){return{runId:J0($.run_id),specId:J0($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:J0($.trigger_kind),status:J0($.status),claimToken:u($.claim_token),claimStartedAt:u($.claim_started_at),claimUntilAt:u($.claim_until_at),scheduledFor:u($.scheduled_for),triggerEventId:u($.trigger_event_id),startedAt:u($.started_at),completedAt:u($.completed_at),sessionId:u($.session_id),reportPath:u($.report_path),error:u($.error),attemptCount:Number($.attempt_count??0),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function ZA($){return{eventId:J0($.event_id),eventType:J0($.event_type),source:J0($.source),subject:u($.subject),occurredAt:J0($.occurred_at),receivedAt:J0($.received_at),workspaceRoot:u($.workspace_root),dedupeKey:u($.dedupe_key),payload:jQ(u($.payload_json)),attributes:jQ(u($.attributes_json)),processingStatus:J0($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:u($.error),createdAt:J0($.created_at),updatedAt:J0($.updated_at)}}function QA($){return $?JSON.stringify($):null}var bC=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function JA($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function yC($,W,Z,Q){for(let J of bC){let j=$[J],X=W[J];if(JA(j)!==JA(X))return!0}if(Z===!1&&Q===!0)return!0;return!1}function hC($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function kC($){return`hub/schedules/${$}.cron.md`}function IC($){let W={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(W).length>0?W:void 0}function Jj($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((W)=>W.trim().length>0),enabled:$.enabled!==!1,metadata:IC($)}}function jA($){return JSON.stringify(Jj($))}function xC($,W){let Z=$.metadata?{...$.metadata}:{},Q=W.createdBy===null?void 0:W.createdBy!==void 0?W.createdBy:typeof Z.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,J=W.cwd!==void 0?W.cwd:typeof Z.__hubScheduleCwd==="string"?Z.__hubScheduleCwd:void 0,j=W.runtimeOptions!==void 0?W.runtimeOptions:Z.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0;return delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions,{name:W.name??$.title,cronPattern:W.cronPattern??$.scheduleExpr??"",prompt:W.prompt??$.prompt??"",workspaceRoot:W.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:W.modelSelection!==void 0?W.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:W.enabled??$.enabled,mode:W.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:W.systemPrompt===null?void 0:W.systemPrompt!==void 0?W.systemPrompt:$.systemPrompt,maxIterations:W.maxIterations===null?void 0:W.maxIterations!==void 0?W.maxIterations:$.maxIterations,timeoutSeconds:W.timeoutSeconds===null?void 0:W.timeoutSeconds!==void 0?W.timeoutSeconds:$.timeoutSeconds,maxParallel:W.maxParallel??$.maxParallel??1,createdBy:Q,tags:W.tags??$.tags,runtimeOptions:j,metadata:W.metadata!==void 0?W.metadata:Object.keys(Z).length>0?Z:void 0}}class o5{db;constructor($={}){let W=$.dbPath??SC();this.db=PC(W),WA(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return W?d$(W):void 0}getSpec($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return W?d$(W):void 0}getSpecByExternalId($){let W=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return W?d$(W):void 0}listSpecs($={}){let W=[],Z=[];if($.triggerKind)W.push("trigger_kind = ?"),Z.push($.triggerKind);if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.parseStatus)W.push("parse_status = ?"),Z.push($.parseStatus);if(!$.includeRemoved)W.push("removed = 0");let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>d$(X))}createHubSchedule($){let W=`sched_${a5()}`,Z=this.upsertSpec({externalId:W,sourcePath:kC(W),triggerKind:"schedule",sourceHash:jA($),parseStatus:"valid",spec:Jj($)});this.initializeScheduleNextRun(Z.record.specId);let Q=this.getSpec(Z.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let W=this.db.prepare(`SELECT * FROM cron_specs
359
359
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
360
- ORDER BY created_at ASC LIMIT 1`).get($);return W?u$(W):void 0}listHubSchedules($={}){let W=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Z=[];if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)W.push("tags_json LIKE ?"),Z.push(`%"${j.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
360
+ ORDER BY created_at ASC LIMIT 1`).get($);return W?d$(W):void 0}listHubSchedules($={}){let W=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Z=[];if(typeof $.enabled==="boolean")W.push("enabled = ?"),Z.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)W.push("tags_json LIKE ?"),Z.push(`%"${j.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
361
361
  WHERE ${W.join(" AND ")}
362
- ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>u$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=SC(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:JA(Q),parseStatus:"valid",spec:Jj(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:P0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
362
+ ORDER BY created_at DESC LIMIT ?`).all(...Z,Q).map((j)=>d$(j))}updateHubSchedule($,W){let Z=this.getHubSchedule($);if(!Z)return;let Q=xC(Z,W),J=this.upsertSpec({externalId:$,sourcePath:Z.sourcePath,triggerKind:"schedule",sourceHash:jA(Q),parseStatus:"valid",spec:Jj(Q)});if(W.cronPattern!==void 0||W.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let W=this.getHubSchedule($);if(!W)return!1;return this.markSpecRemoved(W.specId),this.cancelQueuedRunsForSpec(W.specId),!0}enqueueHubScheduleRun($,W="manual"){let Z=this.getHubSchedule($);if(!Z||!Z.enabled||Z.removed||Z.parseStatus!=="valid")return;return this.enqueueRun({specId:Z.specId,specRevision:Z.revision,triggerKind:W,scheduledFor:C0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
363
363
  WHERE trigger_kind = 'event'
364
364
  AND event_type = ?
365
365
  AND enabled = 1
366
366
  AND removed = 0
367
367
  AND parse_status = 'valid'
368
- ORDER BY created_at ASC`).all($).map((Z)=>u$(Z))}upsertSpec($){let W=P0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??wC($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${n5()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&EC(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
368
+ ORDER BY created_at ASC`).all($).map((Z)=>d$(Z))}upsertSpec($){let W=C0(),Z=this.getSpecBySourcePath($.sourcePath),Q=$.spec,J={title:Q?.title??Z?.title??hC($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},j=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!Z){let H=`cspec_${a5()}`;this.insertSpecRow(H,$,J,j,W);let G=this.getSpec(H);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let Y=Z.sourceHash!==$.sourceHash&&yC(Z,J,Z.enabled,j),V=Y?Z.revision+1:Z.revision;this.updateSpecRow(Z.specId,$,J,j,V,W);let B=this.getSpec(Z.specId);if(!B)throw Error("failed to reload cron_spec after update");return{record:B,created:!1,revisionChanged:Y}}insertSpecRow($,W,Z,Q,J){let j=W.spec;this.db.prepare(`INSERT INTO cron_specs (
369
369
  spec_id, external_id, source_path, trigger_kind,
370
370
  source_mtime_ms, source_hash, parse_status, parse_error,
371
371
  enabled, removed, title, prompt, workspace_root,
@@ -388,7 +388,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
388
388
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
389
389
  tags_json = ?, metadata_json = ?,
390
390
  revision = ?, updated_at = ?
391
- WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(P0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,P0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,P0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,P0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(r2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=u$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(r2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${n5()}`,Y;try{Y=new Date(r2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
391
+ WHERE spec_id = ?`).run(W.externalId,W.triggerKind,W.sourceMtimeMs??null,W.sourceHash,W.parseStatus,W.parseError??null,Q?1:0,Z.title??"",Z.prompt??null,Z.workspaceRoot??null,Z.scheduleExpr??null,Z.timezone??null,Z.eventType??null,Z.filters?JSON.stringify(Z.filters):null,Z.debounceSeconds??null,Z.dedupeWindowSeconds??null,Z.cooldownSeconds??null,Z.mode??null,Z.systemPrompt??null,Z.providerId??null,Z.modelId??null,Z.maxIterations??null,Z.timeoutSeconds??null,Z.maxParallel??null,Z.tools?JSON.stringify(Z.tools):null,Z.notesDirectory??null,Z.extensions?JSON.stringify(Z.extensions):null,Z.source??null,X?.tags?JSON.stringify(X.tags):null,X?.metadata?JSON.stringify(X.metadata):null,J,j,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(C0(),$)}updateSpecNextRunAt($,W){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W??null,C0(),$)}updateSpecLastRunAt($,W){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(W,C0(),$)}updateLastMaterializedRunId($,W){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(W,C0(),$)}initializeScheduleNextRun($){let W=this.getSpec($);if(!W||W.triggerKind!=="schedule"||!W.enabled||!W.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Z=new Date(r2(W.scheduleExpr,Date.now(),W.timezone)).toISOString();this.updateSpecNextRunAt($,Z)}materializeDueScheduleRun($){let W=$.nowMs,Z=new Date(W).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let J=d$(Q);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let j=J.nextRunAt;if(!j){let V=new Date(r2(J.scheduleExpr,W,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Z,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(j).getTime()>W)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:j};let X=`crun_${a5()}`,Y;try{Y=new Date(r2(J.scheduleExpr,W,J.timezone)).toISOString()}catch{Y=void 0}return this.db.prepare(`INSERT INTO cron_runs (
392
392
  run_id, spec_id, spec_revision, trigger_kind, status,
393
393
  scheduled_for, trigger_event_id, attempt_count,
394
394
  created_at, updated_at
@@ -397,22 +397,22 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
397
397
  last_run_at = ?,
398
398
  next_run_at = ?,
399
399
  updated_at = ?
400
- WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?Qj(W):void 0}insertEventLog($,W={}){let Z=P0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
400
+ WHERE spec_id = ?`).run(X,Z,Y??null,Z,J.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(X),nextRunAt:Y}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let W=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return W?Qj(W):void 0}insertEventLog($,W={}){let Z=C0(),Q=W.receivedAtIso??Z,J=$.eventId.trim();if(!J)throw Error("automation event requires eventId");let j=$.eventType.trim();if(!j)throw Error("automation event requires eventType");let X=$.source.trim();if(!X)throw Error("automation event requires source");let Y=$.occurredAt.trim()||Q,V=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
401
401
  event_id, event_type, source, subject,
402
402
  occurred_at, received_at, workspace_root, dedupe_key,
403
403
  payload_json, attributes_json, processing_status,
404
404
  matched_spec_count, queued_run_count, suppressed_count,
405
405
  error, created_at, updated_at
406
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,ZA($.payload),ZA($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?WA(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
406
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(J,j,X,$.subject?.trim()||null,Y,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,QA($.payload),QA($.attributes),"received",0,0,0,null,Z,Z).changes??0,B=this.getEventLog(J);if(!B)throw Error("failed to insert cron_event_log row");return{record:B,created:V===1}}getEventLog($){let W=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return W?ZA(W):void 0}listEventLogs($={}){let W=[],Z=[];if($.eventType)W.push("event_type = ?"),Z.push($.eventType);if($.source)W.push("source = ?"),Z.push($.source);if($.processingStatus)W.push("processing_status = ?"),Z.push($.processingStatus);let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
407
407
  ORDER BY received_at DESC, created_at DESC
408
- LIMIT ?`).all(...Z,J).map((X)=>WA(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
408
+ LIMIT ?`).all(...Z,J).map((X)=>ZA(X))}updateEventLogProcessing($,W){return(this.db.prepare(`UPDATE cron_event_log SET
409
409
  processing_status = ?,
410
410
  matched_spec_count = COALESCE(?, matched_spec_count),
411
411
  queued_run_count = COALESCE(?, queued_run_count),
412
412
  suppressed_count = COALESCE(?, suppressed_count),
413
413
  error = ?,
414
414
  updated_at = ?
415
- WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,P0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>Qj(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
415
+ WHERE event_id = ?`).run(W.status,W.matchedSpecCount??null,W.queuedRunCount??null,W.suppressedCount??null,W.error??null,C0(),$).changes??0)===1}listRuns($={}){let W=[],Z=[];if($.specId)W.push("spec_id = ?"),Z.push($.specId);if($.status){let X=Array.isArray($.status)?$.status:[$.status];if(X.length>0){let Y=X.map(()=>"?").join(",");W.push(`status IN (${Y})`);for(let V of X)Z.push(V)}}let Q=W.length>0?`WHERE ${W.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...Z,J).map((X)=>Qj(X))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
416
416
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
417
417
  WHERE r.spec_id = ?
418
418
  AND r.trigger_kind = 'event'
@@ -430,7 +430,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
430
430
  AND r.status = 'queued'
431
431
  AND e.dedupe_key = ?
432
432
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
433
- LIMIT 1`).get($.specId,$.dedupeKey);return W?Qj(W):void 0}updateQueuedEventRunForDebounce($){let W=P0();if((this.db.prepare(`UPDATE cron_runs SET
433
+ LIMIT 1`).get($.specId,$.dedupeKey);return W?Qj(W):void 0}updateQueuedEventRunForDebounce($){let W=C0();if((this.db.prepare(`UPDATE cron_runs SET
434
434
  trigger_event_id = ?,
435
435
  scheduled_for = ?,
436
436
  updated_at = ?
@@ -439,12 +439,12 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
439
439
  AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,W,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,W){return!!this.db.prepare(`SELECT run_id FROM cron_runs
440
440
  WHERE spec_id = ? AND spec_revision = ?
441
441
  AND trigger_kind = 'one_off'
442
- LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${n5()}`,Z=P0();this.db.prepare(`INSERT INTO cron_runs (
442
+ LIMIT 1`).get($,W)}enqueueRun($){let W=`crun_${a5()}`,Z=C0();this.db.prepare(`INSERT INTO cron_runs (
443
443
  run_id, spec_id, spec_revision, trigger_kind, status,
444
444
  scheduled_for, trigger_event_id, attempt_count,
445
445
  created_at, updated_at
446
446
  ) VALUES (?,?,?,?,?, ?,?,?, ?,?)`).run(W,$.specId,$.specRevision,$.triggerKind,"queued",$.scheduledFor??null,$.triggerEventId??null,0,Z,Z),this.updateLastMaterializedRunId($.specId,W);let Q=this.getRun(W);if(!Q)throw Error("failed to insert cron_run row");return Q}cancelQueuedRunsForSpec($){return this.db.prepare(`UPDATE cron_runs SET status = 'cancelled', updated_at = ?
447
- WHERE spec_id = ? AND status = 'queued'`).run(P0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
447
+ WHERE spec_id = ? AND status = 'queued'`).run(C0(),$).changes??0}claimDueRuns($){let W=$.nowIso,Z=Math.max(1000,Math.floor($.leaseMs)),Q=new Date(new Date(W).getTime()+Z).toISOString(),J=Math.max(1,Math.floor($.limit??25)),j=[];this.db.exec("BEGIN IMMEDIATE;");try{let X=this.db.prepare(`SELECT * FROM cron_runs
448
448
  WHERE (
449
449
  status = 'queued'
450
450
  OR (
@@ -456,7 +456,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
456
456
  )
457
457
  AND (scheduled_for IS NULL OR scheduled_for <= ?)
458
458
  ORDER BY COALESCE(scheduled_for, created_at) ASC
459
- LIMIT ?`).all(W,W,J);for(let Y of X){let V=J0(Y.run_id);if(!V)continue;let B=`cclaim_${n5()}`;if((this.db.prepare(`UPDATE cron_runs SET
459
+ LIMIT ?`).all(W,W,J);for(let Y of X){let V=J0(Y.run_id);if(!V)continue;let B=`cclaim_${a5()}`;if((this.db.prepare(`UPDATE cron_runs SET
460
460
  status = 'running',
461
461
  claim_token = ?,
462
462
  claim_started_at = ?,
@@ -478,7 +478,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
478
478
  AND completed_at IS NULL
479
479
  )
480
480
  )`).run(B,W,Q,W,W,V,W).changes??0)!==1)continue;let G=this.getRun(V);if(!G)continue;j.push({run:G,claimToken:B,claimUntilAt:Q})}this.db.exec("COMMIT;")}catch(X){throw this.db.exec("ROLLBACK;"),X}return j}renewClaim($,W,Z){return(this.db.prepare(`UPDATE cron_runs SET claim_until_at = ?, updated_at = ?
481
- WHERE run_id = ? AND claim_token = ?`).run(Z,P0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??P0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
481
+ WHERE run_id = ? AND claim_token = ?`).run(Z,C0(),$,W).changes??0)===1}completeRun($,W){let Z=W.completedAtIso??C0(),Q=W.claimToken?"WHERE run_id = ? AND claim_token = ?":"WHERE run_id = ?";return(this.db.prepare(`UPDATE cron_runs SET
482
482
  status = ?,
483
483
  session_id = COALESCE(?, session_id),
484
484
  report_path = COALESCE(?, report_path),
@@ -488,7 +488,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
488
488
  claim_token = NULL,
489
489
  claim_until_at = NULL,
490
490
  updated_at = ?
491
- ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=P0();return(this.db.prepare(`UPDATE cron_runs SET
491
+ ${Q}`).run(W.status,W.sessionId??null,W.reportPath??null,W.error??null,Z,Z,$,...W.claimToken?[W.claimToken]:[]).changes??0)>0}requeueRun($){let W=C0();return(this.db.prepare(`UPDATE cron_runs SET
492
492
  status = 'queued',
493
493
  claim_started_at = NULL,
494
494
  claim_token = NULL,
@@ -500,41 +500,41 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let W=Math.max(1000,Mat
500
500
  error = ?,
501
501
  scheduled_for = COALESCE(?, scheduled_for),
502
502
  updated_at = ?
503
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,P0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,P0(),$)}}class o5{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a5({dbPath:$.dbPath});let W=$.specs;this.reconciler=new $j({store:this.store,specs:W}),this.materializer=new l5({store:this.store}),this.eventIngress=new dJ({store:this.store,logger:$.logger}),this.runner=new p5({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Wj({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var GA={};w(GA,{manifestToSessionRecord:()=>YQ,listSessionHistoryFromBackend:()=>Vj,listSessionHistory:()=>VQ,hydrateSessionHistory:()=>HA});import{readdir as hC,readFile as YA}from"node:fs/promises";import{join as VA}from"node:path";import{formatDisplayUserInput as kC,normalizeUserInput as IC}from"@cline/shared";import{resolveSessionDataDir as BA}from"@cline/shared/storage";import{existsSync as bC}from"node:fs";import{readFile as yC}from"node:fs/promises";class s5{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function d$($){let W=$?.trim();if(!W||!bC(W))return[];try{let Z=(await yC(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function jj($){return $?{...$}:void 0}async function jA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function t5($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function W1($){let W=t5($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function XQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xC($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function Yj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function gC($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function mC($){return $.isSubagent!==!0&&!t5($.parentSessionId)}function vC($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function YQ($){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 cC($){let W=Yj($);if(W===0)return[];let Z=BA(),J=(await hC(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:vC(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=VA(Z,Y,`${Y}.json`),B=await YA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=x0.safeParse(H);if(!G.success)return;return YQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function uC($,W,Z){let Q=Yj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:gC(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(mC)).slice(0,Q)}function dC($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
504
- `).trim()}function XA($){return $.replace(/\s+/g," ").trim()}function lC($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function pC($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=XA(dC(Z.content));if(!Q)continue;let J=W==="user"?XA(kC(Q)):Q,j=IC(J.split(`
505
- `)[0]??J);return lC(j,50)}return}function rC($){let W=0;for(let Z of $)W+=XQ(Z.metrics?.cost)??0;return W}function iC($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=W1(J.modelInfo?.provider);if(!Z)Z=W1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function nC($){return W1($?.provider)??W1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function aC($){return W1($?.model)??W1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function Xj($,W){let Z=xC($.metadata),Q=t5(W?.title)??t5(Z?.title),J=XQ(W?.totalCost)??XQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:W1(W?.provider)??W1($.provider)??nC(Z)??"",model:W1(W?.model)??W1($.model)??aC(Z)??"",metadata:j}}function oC($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function sC($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!oC(Z)}async function tC($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return sC(Z,Q)?{...Z,status:"idle"}:Z}))}async function HA($,W){return await Promise.all(W.map(async(Z)=>{let Q=Xj(Z),J=Boolean(t5(Q.metadata?.title)),j=Boolean(W1(Q.provider)),X=Boolean(W1(Q.model)),Y=XQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=iC(B),G=rC(B);return Xj(Z,{title:J?void 0:pC(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function VQ($,W={}){let Z=Yj(W.limit),Q=W.includeSubagents===!0,J=await uC($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await cC(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await tC($,Y);if(W.hydrate===!1)return V.map((B)=>Xj(B));return await HA($,V)}async function eC($){let W=$.trim();if(!W)return;let Z=VA(BA(),W,`${W}.json`),Q=await YA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=x0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Vj($,W={}){let Z=new Map;return await VQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(a4)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await eC(J);return await d$(j)}},W)}var NU={};w(NU,{resolveSessionBackend:()=>pj,createRuntimeHost:()=>S6});import{captureSdkError as MU}from"@cline/shared";import{createSessionId as iP,isHubProtocolCompatible as nP,resolveClineBuildEnv as aP,resolveHubCommandTimeoutMs as oP}from"@cline/shared";import{spawn as MP}from"node:child_process";import{closeSync as RP,mkdirSync as NP,openSync as EP}from"node:fs";import{basename as wP,dirname as CP,join as PP}from"node:path";import{fileURLToPath as SP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as bP,isHubDaemonProcess as qA,isHubProtocolCompatible as yP,resolveClineBuildEnv as MA,withResolvedClineBuildEnv as hP}from"@cline/shared";import{createHash as $P,randomBytes as WP}from"node:crypto";import{existsSync as ZP}from"node:fs";import{chmod as QP,mkdir as Bj,readFile as AA,rm as Hj,writeFile as UA}from"node:fs/promises";import{dirname as DA,join as Gj}from"node:path";import{resolveClineDataDir as n2,resolveClineDir as _A}from"@cline/shared/storage";var JP="CLINE_HUB_DISCOVERY_PATH",jP="CLINE_HUB_BUILD_ID",KA=30000,XP=15000,YP=100;function VP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function BP($){return $P("sha256").update($).digest("hex").slice(0,12)}function HP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function BQ(){return WP(32).toString("hex")}function GP($){return new Promise((W)=>setTimeout(W,$))}function KP($){return`${$}.lock`}async function FP($){try{let W=JSON.parse(await AA(Gj($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function FA($){await Hj($,{recursive:!0,force:!0}).catch(()=>{return})}function HQ(){return process.env[jP]?.trim()||String(t4.version)}function J$($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${BP($)}`,Z=process.env[JP]?.trim()||Gj(n2(),"locks","hub","owners",`${VP(W)}.json`);return{ownerId:W,discoveryPath:Z}}function fA($=`hub-${Date.now().toString(36)}`){return J$($)}async function O0($){try{let W=JSON.parse(await AA($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function GQ($,W){await Bj(DA($),{recursive:!0}),await Hj($,{force:!0}).catch(()=>{return}),await UA($,`${JSON.stringify(W,null,2)}
506
- `,{encoding:"utf8",mode:384}),await QP($,384)}async function m0($){await Hj($,{force:!0}).catch(()=>{return})}async function KQ($,W){let Z=KP($);await Bj(DA(Z),{recursive:!0});let Q=Date.now()+XP;while(!0)try{await Bj(Z,{recursive:!1}),await UA(Gj(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
507
- `,"utf8");try{return await W()}finally{await FA(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await FP(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):KA+1;if(!X||!HP(X.pid)||Y>KA){await FA(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await GP(YP)}}async function j$($,W){try{let Z=await fetch(W?.authToken?Kj($):FQ($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function _1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function FQ($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function Kj($){let W=new URL(FQ($));return W.pathname="/status",W.toString()}function LA($){return ZP($)}import{CLINE_HUB_DEV_PORT as AP,CLINE_HUB_PORT as UP,resolveClineBuildEnv as DP}from"@cline/shared";var _P="CLINE_HUB_HOST",fP="CLINE_HUB_PORT",LP="CLINE_HUB_PATHNAME",Fj="127.0.0.1",Aj=UP,Uj="/hub";function OA($){return DP($)==="development"?AP:Aj}function Dj($={}){return($.env??process.env)[_P]?.trim()||Fj}function L6($={}){let Z=($.env??process.env)[fP]?.trim();if(!Z)return OA($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return OA($);return Q}function _j($={}){return($.env??process.env)[LP]?.trim()||Uj}function Z1($={},W={}){return{host:$.host??Dj(W),port:$.port??L6(W),pathname:$.pathname??_j(W)}}import{join as OP}from"node:path";var TP="shared:cline",zP="CLINE_HUB_DISCOVERY_PATH",qP="hub-production";function TA($){let W=N1($.trim());return J$(`workspace:${W||$.trim()}`)}function v0($=TP){return J$($)}function Q1(){return{ownerId:qP,discoveryPath:process.env[zP]?.trim()||OP(n2(),"locks","hub","production.json")}}var kP=8000,IP=200,xP=3000,gP=100,mP=[100,250,500,1000,2000],vP="--cline-hub-daemon";function cP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function uP(){try{let $=PP(n2(),"logs","hub-daemon.log");return NP(CP($),{recursive:!0}),{fd:EP($,"a"),logPath:$}}catch{return}}function RA(){return MA()==="production"?Q1():v0()}function a2($){return yP($).compatible}function zA($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function o2($,W){try{return await j$($,{authToken:W})}catch{return}}async function dP($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await o2($))?.url)return!0;await new Promise((J)=>setTimeout(J,gP))}return!1}async function AQ($,W){if(await $W($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await dP($.url,xP);return await m0(W).catch(()=>{return}),Z}async function e5($,W){if(a2($))return!0;return AQ($,W)}async function NA($){if(MA()!=="production")return;let W=v0();if(W.discoveryPath===$.discoveryPath)return;let Z=await O0(W.discoveryPath);if(Z?.url)await AQ(Z,W.discoveryPath);else await m0(W.discoveryPath).catch(()=>{return})}function lP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return SP(new URL(`./entry.${$}`,import.meta.url))}function pP($,W){let Z=lP(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=wP(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[vP]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...cP(W)],cwd:$,env:{...hP(process.env),CLINE_NO_INTERACTIVE:"1",[bP]:"1"}}}function rP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function fj($,W={}){if(qA())return;let Z=pP($,W),Q=uP();try{MP(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)RP(Q.fd)}}async function O6($,W={}){for(let Z=0;;Z++)try{fj($,W);return}catch(Q){let J=mP[Z];if(!rP(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function UQ($,W={}){if(qA())return;let Z=RA(),Q=Z1(W),J=_1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;NA(Z).catch(()=>{return}).then(()=>O0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await AQ(X,Z.discoveryPath)&&!j)return}else{let H=await o2(X.url,X.authToken);if(H?.url&&a2(H)&&await w1(H.url,{authToken:X.authToken}))return;if(H?.url)await e5({...H,authToken:X.authToken},Z.discoveryPath);else await m0(Z.discoveryPath).catch(()=>{return})}let V=await o2(J);if(V?.url){if(a2(V)){if(!j||!Y)return}else if(!await e5({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await O6($,B)}).catch(()=>{})}async function EA($,W={}){let Z=RA(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=Z1(W),j=_1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)l$(F.url,F.authToken);return F};await NA(Z).catch(()=>{return});let Y=await O0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await AQ(Y,Z.discoveryPath);else{let A=await o2(Y.url,F);if(A?.url&&a2(A)&&await w1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await e5({...A,authToken:F},Z.discoveryPath);else await m0(Z.discoveryPath).catch(()=>{return})}}let B=await o2(j);if(B?.url){let F=zA(B,Y,j);if(a2(B))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.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await e5(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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 G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await O6($,G);let K=Date.now()+kP;while(Date.now()<K){let F=await O0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await o2(F.url,F.authToken);if(D?.url&&a2(D)&&await w1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await o2(j);if(A?.url&&!a2(A)){let D=zA(A,F,j);if(!await e5(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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((D)=>setTimeout(D,IP))}throw Error("Timed out waiting for detached hub startup.")}function DQ(){return aP()==="production"?Q1():v0()}function sP(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function bA($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return bA($.data);return String($)}function tP($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function wA($){let W=$,Z=tP(W.reason);return new y0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:Lj,{closeCode:W.code,closeReason:Z||void 0})}function eP($,W){if($ instanceof y0)return $;if($ instanceof Error)return new y0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new y0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new y0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new y0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var $S=8000,WS=200,CA="*",PA=8000,ZS="cline-hub-auth.",yA=new Map,hA=new Set,QS=3000,JS=3000,jS=100,Lj="Hub connection closed",XS=250,YS=5000,SA=0.5;class y0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function zj($){return $ instanceof y0}class T6 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function _Q($,W){return $ instanceof T6&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function kA($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=qj($.toString());return Z?yA.get(Z):void 0}function VS($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function qj($){if(!VS($))return;let W=new URL(p$($));return W.search="",W.hash="",W.toString()}function Oj($){let W=qj($);return!!W&&hA.has(W)}function l$($,W){let Z=qj($);if(Z){if(hA.add(Z),W?.trim())yA.set(Z,W)}return $}class f1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new y0("hub_connection_closed",Lj);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),W=this.options.authToken?.trim()||kA($);$.hash="";let Q=new(sP())($.toString(),W?[`${ZS}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new y0("hub_connect_timeout",`Timed out connecting to hub after ${PA}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},PA);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=eP(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=wA(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(bA(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=wA(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=iP("hubreq_"),j=oP($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new T6($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, 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(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===l2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new Z$(V,Y.error.message)}throw new T6($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!Oj(this.currentUrl)||!zj($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await s2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(XS*2**this.reconnectAttempt,YS),W=Math.round($*(1-SA)+Math.random()*$*SA);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oj(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await s2({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 y0("hub_connection_closed",Lj),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 y0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??CA}subscriptionSessionIdFromKey($){return $===CA?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function p$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function w1($,W){let Z=new f1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function Tj($,W){let Z=p$($),Q=await j$(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!nP(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await w1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function BS($){let W=Date.now()+$S;while(Date.now()<W){let Z=await O0($.discoveryPath);if(Z?.url){let Q=await Tj(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return l$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,WS))}return}async function HS($){let W=Date.now()+JS;while(Date.now()<W){if(!(await j$($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,jS))}return!1}function GS($,W){try{return p$($)===p$(W)}catch{return!1}}function KS($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function FS($,W,Z){let Q=new f1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:QS});return!KS(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function WW($={}){if($.endpoint?.trim()){let J=await Tj($.endpoint);return J.status==="compatible"?J.url:void 0}let W=DQ(),Z=await O0(W.discoveryPath);if(!Z?.url)return;let Q=await Tj(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return l$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await m0(W.discoveryPath).catch(()=>{return});return}async function s2($={}){let W=await WW($);if(W&&await w1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=DQ();return await O6($.workspaceRoot??process.cwd()),await BS(Z)}async function $W($,W){let Z=new URL($),Q=W?.trim()||kA(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function Mj($=DQ()){let W=await O0($.discoveryPath);if(!W?.url)return!1;try{if(await $W(W.url,W.authToken))return!0}catch{}return!1}async function fQ($){if(!Oj($.url))return;let W=DQ(),Z=await O0(W.discoveryPath);if(!Z?.url||!GS(Z.url,$.url))return;if(!await FS(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await Mj())return;if(!await HS(Z.url))return;return await m0(W.discoveryPath).catch(()=>{return}),await s2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var nA={};w(nA,{HubRuntimeHost:()=>X$});import{resolveProviderRequestHeaders as _S}from"@cline/llms";import{captureSdkError as Rj,createSessionId as xA,HUB_CHECKPOINT_CAPABILITY as fS,HUB_COMPACTION_CAPABILITY as LS,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as OS,HUB_HOOK_CAPABILITY_PREFIX as TS,HUB_MISTAKE_LIMIT_CAPABILITY as zS,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as qS,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as MS,isHubToolExecutorName as RS}from"@cline/shared";var IA={};w(IA,{createCoreSessionSnapshot:()=>C1,coreSessionSnapshotToRecord:()=>LQ});function AS($){return $?JSON.parse(JSON.stringify($)):void 0}function US($){return $?JSON.parse(JSON.stringify($)):void 0}function DS($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function C1($){let{session:W}=$,Z=AS(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:US($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=DS(Z);return Q?{checkpoint:Q}:{}})()}}function LQ($){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 z6($){if(!$)return;return JSON.parse(JSON.stringify($))}var NS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function gA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function mA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function vA($,W){let Z={...$.config,sessionId:W},Q=_S({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:F0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:l8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function cA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function t2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function uA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(RS)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;t2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${qS}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...cA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])t2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:z6(J.inputSchema)??{},...J.lifecycle?{lifecycle:z6(J.lifecycle)}:{},capabilityName:`${OS}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...cA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of NS){let j=Q[J];if(typeof j!=="function")continue;t2(Z,{kind:"hook",name:J,capabilityName:`${TS}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;t2(Z,{kind:"compaction",capabilityName:LS,config:gA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;t2(Z,{kind:"checkpoint",capabilityName:fS,config:gA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;t2(Z,{kind:"mistakeLimit",capabilityName:zS},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;t2(Z,{kind:"userInstructionService",capabilityName:MS},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function rA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function ES($){return rA($)??"Capability request was cancelled."}function wS($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function CS($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function PS($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function dA($){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 Nj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function r$($,W){return Nj($?.[W])??0}function SS($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=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:r$(W,"inputTokens"),outputTokens:r$(W,"outputTokens"),cacheReadTokens:r$(W,"cacheReadTokens"),cacheWriteTokens:r$(W,"cacheWriteTokens"),cost:Nj(W?.totalCost),totalInputTokens:r$(Z,"inputTokens"),totalOutputTokens:r$(Z,"outputTokens"),totalCacheReadTokens:r$(Z,"cacheReadTokens"),totalCacheWriteTokens:r$(Z,"cacheWriteTokens"),totalCost:Nj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function bS($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=CS(Z)?Z:Z==="failed"?"error":"completed",J=PS($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function e2($,W){return $.error?.message??`hub command failed: ${W}`}function ZW($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function iA($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:F0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:ZW($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:ZW($.status)==="completed"?0:ZW($.status)==="failed"?1:void 0,status:ZW($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function i$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function yS($){let W=i$($?.snapshot);if(W)return LQ(W);let Z=$?.session;return Z?iA(Z):void 0}function lA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return x0.parse({version:1,session_id:$,source:W.source??F0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:ZW(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function pA($,W){return x0.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??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class X${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new s5;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=C0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new f1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!_Q($,"session.create"))return!1;let W=await fQ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=uA($.localRuntime,W),Q=$.config.sessionId?.trim()||xA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:z6(vA($,Q)),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:z6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=i$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?pA(X,$):lA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?uA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||xA(),Y=vA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:z6(Y),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.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:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:z6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=i$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?pA(B,Q??{}):lA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}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 W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=i$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=dA(Q?.usage),j=dA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:rA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(Q$(Z))return;throw Z}return yS(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=i$(J);return j?[LQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map(iA)}async listSettings($){let W=await this.client.command("settings.list",mA($));if(!W.ok)throw Error(e2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",mA($));if(!W.ok)throw Error(e2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(e2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(e2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(e2(Z,"session.compaction.get"));return K1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(e2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(e2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return C0(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:bS($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,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"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=SS($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=i$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=i$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&K0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Rj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(ES($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=wS($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var aA={};w(aA,{RemoteRuntimeHost:()=>q6});class q6 extends X${constructor($){super({url:p$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var oA={};w(oA,{SqliteSessionStore:()=>S1});import{existsSync as hS,mkdirSync as kS}from"node:fs";import{join as IS}from"node:path";import{asBool as QW,asOptionalString as P1,asString as Y$,ensureSessionSchema as xS,loadSqliteDb as gS,nowIso as OQ,toBoolInt as JW}from"@cline/shared/db";import{resolveDbDataDir as mS}from"@cline/shared/storage";class S1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??mS()}init(){this.getRawDb()}ensureSessionsDir(){if(!hS(this.sessionsDirPath))kS(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return IS(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=gS(this.sessionDbPath());return xS($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=OQ();this.run(`INSERT OR REPLACE INTO sessions (
503
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,W,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,W){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(W,C0(),$)}attachReportPathToRun($,W){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(W,C0(),$)}}class s5{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new o5({dbPath:$.dbPath});let W=$.specs;this.reconciler=new $j({store:this.store,specs:W}),this.materializer=new p5({store:this.store}),this.eventIngress=new dJ({store:this.store,logger:$.logger}),this.runner=new r5({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:W,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new Wj({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Z)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:Z});else Q.log("cron.watcher.failed",{error:Z})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var KA={};w(KA,{manifestToSessionRecord:()=>YQ,listSessionHistoryFromBackend:()=>Vj,listSessionHistory:()=>VQ,hydrateSessionHistory:()=>GA});import{readdir as vC,readFile as VA}from"node:fs/promises";import{join as BA}from"node:path";import{formatDisplayUserInput as cC,normalizeUserInput as uC}from"@cline/shared";import{resolveSessionDataDir as HA}from"@cline/shared/storage";import{existsSync as gC}from"node:fs";import{readFile as mC}from"node:fs/promises";class t5{listeners=new Set;subscribe($,W){let Z={listener:$,sessionId:W?.sessionId?.trim()||void 0};return this.listeners.add(Z),()=>{this.listeners.delete(Z)}}emit($){let W=$.payload.sessionId?.trim();for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==W)continue;Z.listener($)}}get size(){return this.listeners.size}}async function l$($){let W=$?.trim();if(!W||!gC(W))return[];try{let Z=(await mC(W,"utf8")).trim();if(!Z)return[];let Q=JSON.parse(Z);if(Array.isArray(Q))return Q;if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let J=Q.messages;if(Array.isArray(J))return J}return[]}catch{return[]}}function jj($){return $?{...$}:void 0}async function XA($,W){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await W.queueSpawnRequest($);let Q=await W.upsertSubagentSessionFromHook($);if(!Q)return;await W.appendSubagentHookAudit(Q,$),await W.applySubagentStatus(Q,$)}function e5($){if(typeof $!=="string")return;let W=$.trim();return W.length>0?W:void 0}function J1($){let W=e5($);if(!W)return;return W.toLowerCase()==="unknown"?void 0:W}function XQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function dC($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function Yj($){let W=$??200;return Number.isFinite(W)?Math.max(0,Math.floor(W)):200}function lC($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function pC($){return $.isSubagent!==!0&&!e5($.parentSessionId)}function rC($){let W=$.match(/\d{13,}/g);if(!W||W.length===0)return 0;let Z=0;for(let Q of W){let J=Number.parseInt(Q,10);if(Number.isFinite(J)&&J>Z)Z=J}return Z}function YQ($){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 iC($){let W=Yj($);if(W===0)return[];let Z=HA(),J=(await vC(Z,{withFileTypes:!0}).catch(()=>[])).filter((X)=>X.isDirectory()).map((X)=>({entry:X,recency:rC(X.name.trim())})).sort((X,Y)=>Y.recency-X.recency||Y.entry.name.localeCompare(X.entry.name));return(await Promise.all(J.map(async({entry:X})=>{let Y=X.name.trim();if(!Y)return;let V=BA(Z,Y,`${Y}.json`),B=await VA(V,"utf8").catch(()=>{return});if(!B)return;let H;try{H=JSON.parse(B)}catch{return}let G=m0.safeParse(H);if(!G.success)return;return YQ(G.data)}))).filter((X)=>Boolean(X)).sort((X,Y)=>Y.startedAt.localeCompare(X.startedAt)).slice(0,W)}async function nC($,W,Z){let Q=Yj(W);if(Q===0)return await $.listSessions(0),[];let J=Z.includeSubagents?Q:lC(Q),j=await $.listSessions(J);return(Z.includeSubagents?j:j.filter(pC)).slice(0,Q)}function aC($){if(typeof $==="string")return $.trim();let W=[];for(let Z of $){if(!Z||typeof Z!=="object")continue;let Q=Z;if(Q.type!=="text")continue;let J=Q.text?.trim();if(J)W.push(J)}return W.join(`
504
+ `).trim()}function YA($){return $.replace(/\s+/g," ").trim()}function oC($,W){if($.length<=W)return $;return`${$.slice(0,Math.max(0,W-3)).trimEnd()}...`}function sC($){for(let W of["user","assistant"])for(let Z of $){if(Z.role!==W)continue;let Q=YA(aC(Z.content));if(!Q)continue;let J=W==="user"?YA(cC(Q)):Q,j=uC(J.split(`
505
+ `)[0]??J);return oC(j,50)}return}function tC($){let W=0;for(let Z of $)W+=XQ(Z.metrics?.cost)??0;return W}function eC($){let W,Z;for(let Q=$.length-1;Q>=0;Q-=1){let J=$[Q];if(!W)W=J1(J.modelInfo?.provider);if(!Z)Z=J1(J.modelInfo?.id);if(W&&Z)break}return{provider:W,model:Z}}function $P($){return J1($?.provider)??J1($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function WP($){return J1($?.model)??J1($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function Xj($,W){let Z=dC($.metadata),Q=e5(W?.title)??e5(Z?.title),J=XQ(W?.totalCost)??XQ(Z?.totalCost),j=Z||Q!==void 0||J!==void 0?{...Z??{},...Q!==void 0?{title:Q}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:J1(W?.provider)??J1($.provider)??$P(Z)??"",model:J1(W?.model)??J1($.model)??WP(Z)??"",metadata:j}}function ZP($){let W=$.content;if(!Array.isArray(W))return!1;return W.some((Z)=>!!Z&&typeof Z==="object"&&Z.type==="tool-call")}function QP($,W){if($.status!=="running"||$.interactive!==!0)return!1;let Z=W.at(-1);return Z?.role==="assistant"&&!ZP(Z)}async function JP($,W){return await Promise.all(W.map(async(Z)=>{if(Z.status!=="running"||Z.interactive!==!0)return Z;let Q=await $.readSessionMessages(Z.sessionId);return QP(Z,Q)?{...Z,status:"idle"}:Z}))}async function GA($,W){return await Promise.all(W.map(async(Z)=>{let Q=Xj(Z),J=Boolean(e5(Q.metadata?.title)),j=Boolean(J1(Q.provider)),X=Boolean(J1(Q.model)),Y=XQ(Q.metadata?.totalCost),V=Y!==void 0&&Y>0;if(J&&j&&X&&V)return Q;let B=await $.readSessionMessages(Z.sessionId);if(B.length===0)return Q;let H=eC(B),G=tC(B);return Xj(Z,{title:J?void 0:sC(B),provider:j?void 0:H.provider,model:X?void 0:H.model,totalCost:V||G<=0?void 0:G})}))}async function VQ($,W={}){let Z=Yj(W.limit),Q=W.includeSubagents===!0,J=await nC($,Z,{includeSubagents:Q}),j=W.includeManifestFallback===!0&&J.length<Z?await iC(Math.min(Math.max(Z*2,100),500)):[],X=new Map;for(let B of[...J,...j]){if(X.has(B.sessionId))continue;X.set(B.sessionId,B)}let Y=j.length===0?J:Array.from(X.values()).sort((B,H)=>H.startedAt.localeCompare(B.startedAt)).slice(0,Z),V=await JP($,Y);if(W.hydrate===!1)return V.map((B)=>Xj(B));return await GA($,V)}async function jP($){let W=$.trim();if(!W)return;let Z=BA(HA(),W,`${W}.json`),Q=await VA(Z,"utf8").catch(()=>{return});if(!Q)return;try{let J=m0.safeParse(JSON.parse(Q));return J.success?J.data.messages_path:void 0}catch{return}}async function Vj($,W={}){let Z=new Map;return await VQ({listSessions:async(J)=>{let j=await $.listSessions(J);Z.clear();for(let X of j)Z.set(X.sessionId,X);return j.map(o4)},readSessionMessages:async(J)=>{let j=Z.get(J)?.messagesPath??await jP(J);return await l$(j)}},W)}var EU={};w(EU,{resolveSessionBackend:()=>pj,createRuntimeHost:()=>b6});import{captureSdkError as RU}from"@cline/shared";import{createSessionId as eP,isHubProtocolCompatible as $S,resolveClineBuildEnv as WS,resolveHubCommandTimeoutMs as ZS}from"@cline/shared";import{spawn as PP}from"node:child_process";import{closeSync as SP,mkdirSync as bP,openSync as yP}from"node:fs";import{basename as hP,dirname as kP,join as IP}from"node:path";import{fileURLToPath as xP}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as gP,isHubDaemonProcess as MA,isHubProtocolCompatible as mP,resolveClineBuildEnv as RA,withResolvedClineBuildEnv as vP}from"@cline/shared";import{createHash as XP,randomBytes as YP}from"node:crypto";import{existsSync as VP}from"node:fs";import{chmod as BP,mkdir as Bj,readFile as UA,rm as Hj,writeFile as DA}from"node:fs/promises";import{dirname as _A,join as Gj}from"node:path";import{resolveClineDataDir as n2,resolveClineDir as fA}from"@cline/shared/storage";var HP="CLINE_HUB_DISCOVERY_PATH",GP="CLINE_HUB_BUILD_ID",FA=30000,KP=15000,FP=100;function AP($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function UP($){return XP("sha256").update($).digest("hex").slice(0,12)}function DP($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(W){return W instanceof Error&&"code"in W?String(W.code)==="EPERM":!1}}function BQ(){return YP(32).toString("hex")}function _P($){return new Promise((W)=>setTimeout(W,$))}function fP($){return`${$}.lock`}async function LP($){try{let W=JSON.parse(await UA(Gj($,"owner.json"),"utf8"));if(typeof W.pid!=="number"||typeof W.acquiredAt!=="string")return;return{pid:W.pid,acquiredAt:W.acquiredAt}}catch{return}}async function AA($){await Hj($,{recursive:!0,force:!0}).catch(()=>{return})}function HQ(){return process.env[GP]?.trim()||String(e4.version)}function j$($=process.argv[1]?.trim()||process.cwd()){let W=`hub-${UP($)}`,Z=process.env[HP]?.trim()||Gj(n2(),"locks","hub","owners",`${AP(W)}.json`);return{ownerId:W,discoveryPath:Z}}function LA($=`hub-${Date.now().toString(36)}`){return j$($)}async function L0($){try{let W=JSON.parse(await UA($,"utf8"));if(typeof W.hubId!=="string"||typeof W.protocolVersion!=="string"||typeof W.authToken!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string"||typeof W.startedAt!=="string"||typeof W.updatedAt!=="string")return;return{hubId:W.hubId,protocolVersion:W.protocolVersion,minClientProtocolVersion:typeof W.minClientProtocolVersion==="string"?W.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof W.maxClientProtocolVersion==="string"?W.maxClientProtocolVersion:void 0,capabilities:Array.isArray(W.capabilities)?W.capabilities.filter((Z)=>typeof Z==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,authToken:W.authToken,host:W.host,port:W.port,url:W.url,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:W.startedAt,updatedAt:W.updatedAt}}catch{return}}async function GQ($,W){await Bj(_A($),{recursive:!0}),await Hj($,{force:!0}).catch(()=>{return}),await DA($,`${JSON.stringify(W,null,2)}
506
+ `,{encoding:"utf8",mode:384}),await BP($,384)}async function c0($){await Hj($,{force:!0}).catch(()=>{return})}async function KQ($,W){let Z=fP($);await Bj(_A(Z),{recursive:!0});let Q=Date.now()+KP;while(!0)try{await Bj(Z,{recursive:!1}),await DA(Gj(Z,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
507
+ `,"utf8");try{return await W()}finally{await AA(Z)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let X=await LP(Z),Y=X?Date.now()-Date.parse(X.acquiredAt):FA+1;if(!X||!DP(X.pid)||Y>FA){await AA(Z);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${Z}`);await _P(FP)}}async function X$($,W){try{let Z=await fetch(W?.authToken?Kj($):FQ($),{headers:W?.authToken?{authorization:`Bearer ${W.authToken}`}:void 0});if(!Z.ok)return;let Q=await Z.json();if(typeof Q.protocolVersion!=="string"||typeof Q.host!=="string"||typeof Q.port!=="number"||typeof Q.url!=="string")return;return{protocolVersion:Q.protocolVersion,minClientProtocolVersion:typeof Q.minClientProtocolVersion==="string"?Q.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Q.maxClientProtocolVersion==="string"?Q.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Q.capabilities)?Q.capabilities.filter((J)=>typeof J==="string"):void 0,coreVersion:typeof Q.coreVersion==="string"?Q.coreVersion:void 0,buildId:typeof Q.buildId==="string"?Q.buildId:void 0,host:Q.host,port:Q.port,url:Q.url,hubId:typeof Q.hubId==="string"?Q.hubId:void 0,authToken:typeof Q.authToken==="string"?Q.authToken:void 0,pid:typeof Q.pid==="number"?Q.pid:void 0,startedAt:typeof Q.startedAt==="string"?Q.startedAt:void 0,updatedAt:typeof Q.updatedAt==="string"?Q.updatedAt:void 0}}catch{return}}function L1($,W,Z="/hub"){return new URL(`ws://${$}:${W}${Z}`).toString()}function FQ($){let W=new URL($);return W.protocol=W.protocol==="wss:"?"https:":"http:",W.pathname="/health",W.search="",W.toString()}function Kj($){let W=new URL(FQ($));return W.pathname="/status",W.toString()}function OA($){return VP($)}import{CLINE_HUB_DEV_PORT as OP,CLINE_HUB_PORT as TP,resolveClineBuildEnv as zP}from"@cline/shared";var qP="CLINE_HUB_HOST",MP="CLINE_HUB_PORT",RP="CLINE_HUB_PATHNAME",Fj="127.0.0.1",Aj=TP,Uj="/hub";function TA($){return zP($)==="development"?OP:Aj}function Dj($={}){return($.env??process.env)[qP]?.trim()||Fj}function O6($={}){let Z=($.env??process.env)[MP]?.trim();if(!Z)return TA($);let Q=Number.parseInt(Z,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return TA($);return Q}function _j($={}){return($.env??process.env)[RP]?.trim()||Uj}function j1($={},W={}){return{host:$.host??Dj(W),port:$.port??O6(W),pathname:$.pathname??_j(W)}}import{join as NP}from"node:path";var EP="shared:cline",wP="CLINE_HUB_DISCOVERY_PATH",CP="hub-production";function zA($){let W=E1($.trim());return j$(`workspace:${W||$.trim()}`)}function u0($=EP){return j$($)}function X1(){return{ownerId:CP,discoveryPath:process.env[wP]?.trim()||NP(n2(),"locks","hub","production.json")}}var cP=8000,uP=200,dP=3000,lP=100,pP=[100,250,500,1000,2000],rP="--cline-hub-daemon";function iP($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function nP(){try{let $=IP(n2(),"logs","hub-daemon.log");return bP(kP($),{recursive:!0}),{fd:yP($,"a"),logPath:$}}catch{return}}function NA(){return RA()==="production"?X1():u0()}function a2($){return mP($).compatible}function qA($,W,Z){if(!W||W.url!==Z)return $;return{...$,authToken:$.authToken??W.authToken,pid:$.pid??W.pid}}async function o2($,W){try{return await X$($,{authToken:W})}catch{return}}async function aP($,W){let Z=Date.now()+W;while(Date.now()<Z){if(!(await o2($))?.url)return!0;await new Promise((J)=>setTimeout(J,lP))}return!1}async function AQ($,W){if(await WW($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Z=await aP($.url,dP);return await c0(W).catch(()=>{return}),Z}async function $W($,W){if(a2($))return!0;return AQ($,W)}async function EA($){if(RA()!=="production")return;let W=u0();if(W.discoveryPath===$.discoveryPath)return;let Z=await L0(W.discoveryPath);if(Z?.url)await AQ(Z,W.discoveryPath);else await c0(W.discoveryPath).catch(()=>{return})}function oP(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return xP(new URL(`./entry.${$}`,import.meta.url))}function sP($,W){let Z=oP(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let J=hP(Q).toLowerCase().includes("bun"),j=Z.startsWith("/$bunfs/"),X=J&&Z.toLowerCase().endsWith(".ts"),Y=j?[rP]:[...X?["--conditions=development"]:[],Z];return{launcher:Q,args:[...Y,"--cwd",$,...iP(W)],cwd:$,env:{...vP(process.env),CLINE_NO_INTERACTIVE:"1",[gP]:"1"}}}function tP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Z="message"in $?$.message:void 0;return typeof Z==="string"&&Z.includes("ETXTBSY")}function fj($,W={}){if(MA())return;let Z=sP($,W),Q=nP();try{PP(Z.launcher,Z.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:Z.env,cwd:Z.cwd,windowsHide:!0}).unref()}finally{if(Q)SP(Q.fd)}}async function T6($,W={}){for(let Z=0;;Z++)try{fj($,W);return}catch(Q){let J=pP[Z];if(!tP(Q)||J===void 0)throw Q;await new Promise((j)=>setTimeout(j,J))}}function UQ($,W={}){if(MA())return;let Z=NA(),Q=j1(W),J=L1(Q.host,Q.port,Q.pathname),j=W.allowPortFallback===!0&&Q.port!==0;EA(Z).catch(()=>{return}).then(()=>L0(Z.discoveryPath)).then(async(X)=>{let Y=!1;if(X?.url)if(!X.authToken){if(Y=!0,!await AQ(X,Z.discoveryPath)&&!j)return}else{let H=await o2(X.url,X.authToken);if(H?.url&&a2(H)&&await C1(H.url,{authToken:X.authToken}))return;if(H?.url)await $W({...H,authToken:X.authToken},Z.discoveryPath);else await c0(Z.discoveryPath).catch(()=>{return})}let V=await o2(J);if(V?.url){if(a2(V)){if(!j||!Y)return}else if(!await $W({...V,authToken:void 0},Z.discoveryPath)&&!j)return}let B=j?{...Q,port:0}:Q;await T6($,B)}).catch(()=>{})}async function wA($,W={}){let Z=NA(),Q=W.host!==void 0||W.port!==void 0||W.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=j1(W),j=L1(J.host,J.port,J.pathname),X=(F)=>{if(!Q)p$(F.url,F.authToken);return F};await EA(Z).catch(()=>{return});let Y=await L0(Z.discoveryPath),V=!1;if(Y?.url){let F=Y.authToken;if(!F)V=!0,await AQ(Y,Z.discoveryPath);else{let A=await o2(Y.url,F);if(A?.url&&a2(A)&&await C1(A.url,{authToken:F}))return X({url:A.url,authToken:F});if(A?.url)await $W({...A,authToken:F},Z.discoveryPath);else await c0(Z.discoveryPath).catch(()=>{return})}}let B=await o2(j);if(B?.url){let F=qA(B,Y,j);if(a2(B))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.${V?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await $W(F,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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 G=W.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await T6($,G);let K=Date.now()+cP;while(Date.now()<K){let F=await L0(Z.discoveryPath);if(F?.url&&F.authToken){let D=await o2(F.url,F.authToken);if(D?.url&&a2(D)&&await C1(D.url,{authToken:F.authToken}))return X({url:D.url,authToken:F.authToken})}let A=await o2(j);if(A?.url&&!a2(A)){let D=qA(A,F,j);if(!await $W(D,Z.discoveryPath)&&W.allowPortFallback!==!0&&J.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((D)=>setTimeout(D,uP))}throw Error("Timed out waiting for detached hub startup.")}function DQ(){return WS()==="production"?X1():u0()}function QS(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function yA($){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((W)=>Buffer.from(W))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return yA($.data);return String($)}function JS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function CA($){let W=$,Z=JS(W.reason);return new k0("hub_connection_closed",W.code||Z?`Hub connection closed (code=${W.code??0}${Z?`, reason=${Z}`:""})`:Lj,{closeCode:W.code,closeReason:Z||void 0})}function jS($,W){if($ instanceof k0)return $;if($ instanceof Error)return new k0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new k0("hub_connect_failed",$.error.message);let Z=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Z)return new k0("hub_connect_failed",Z);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new k0("hub_connect_failed",Q?`Failed to connect to hub at ${W.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${W.toString()}.`)}var XS=8000,YS=200,PA="*",SA=8000,VS="cline-hub-auth.",hA=new Map,kA=new Set,BS=3000,HS=3000,GS=100,Lj="Hub connection closed",KS=250,FS=5000,bA=0.5;class k0 extends Error{code;details;constructor($,W,Z){super(W);this.code=$;this.details=Z;this.name="HubTransportError"}}function zj($){return $ instanceof k0}class z6 extends Error{command;code;constructor($,W,Z){super(Z);this.command=$;this.code=W;this.name="HubCommandError"}}function _Q($,W){return $ instanceof z6&&$.code==="hub_command_timeout"&&(W===void 0||$.command===W)}function IA($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=qj($.toString());return Z?hA.get(Z):void 0}function AS($){try{let Z=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"}catch{return!1}}function qj($){if(!AS($))return;let W=new URL(r$($));return W.search="",W.hash="",W.toString()}function Oj($){let W=qj($);return!!W&&kA.has(W)}function p$($,W){let Z=qj($);if(Z){if(kA.add(Z),W?.trim())hA.set(Z,W)}return $}class O1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new k0("hub_connection_closed",Lj);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),W=this.options.authToken?.trim()||IA($);$.hash="";let Q=new(QS())($.toString(),W?[`${VS}${W}`]:void 0);this.socket=Q;let J=!1;this.connectPromise=new Promise((j,X)=>{let Y=!1,V=setTimeout(()=>{if(Y)return;Y=!0,J=!0,this.lastCloseError=new k0("hub_connect_timeout",`Timed out connecting to hub after ${SA}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}X(this.lastCloseError)},SA);Q.addEventListener("open",()=>{if(Y)return;Y=!0,clearTimeout(V),j()}),Q.addEventListener("error",(B)=>{if(Y)return;Y=!0,clearTimeout(V),this.lastCloseError=jS(B,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)}),Q.addEventListener("close",(B)=>{if(Y)return;if(Y=!0,clearTimeout(V),!J)this.lastCloseError=CA(B),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,X(this.lastCloseError)})}),Q.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(yA(j)))}),Q.addEventListener("close",(j)=>{if(this.socket!==Q)return;if(!J)this.lastCloseError=CA(j),this.sawSocketClose=!0;this.registered=!1;for(let X of this.pendingReplies.values())X.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,W){let Z=W?.sessionId?.trim()||void 0,Q={listener:$,sessionId:Z};return this.listeners.add(Q),this.adjustSubscriptionCount(Z,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(Z,-1)}}async command($,W,Z,Q){let J=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,W,Z,Q)}catch(X){if(!j||J>=1||!await this.recoverLocalHubTransport(X))throw X;J+=1}}async commandOnce($,W,Z,Q){await this.connect();let J=eP("hubreq_"),j=ZS($,Q?.timeoutMs),X=new Promise((V,B)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;B(new z6($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${J}, 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(J,{resolve:(G)=>{if(H)clearTimeout(H);V(G)},reject:(G)=>{if(H)clearTimeout(H);B(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Z,timeoutMs:j,payload:W}})}catch(V){throw this.pendingReplies.delete(J),V}let Y=await X;if(!Y.ok){if(Y.error?.code===l2){let V=Z??(typeof W?.sessionId==="string"?W.sessionId:void 0);throw new Q$(V,Y.error.message)}throw new z6($,Y.error?.code,Y.error?.message??`Hub command ${$} failed`)}return Y}async recoverLocalHubTransport($){if(!Oj(this.currentUrl)||!zj($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let W=await s2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!W)return!1;return this.currentUrl=W,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(KS*2**this.reconnectAttempt,FS),W=Math.round($*(1-bA)+Math.random()*$*bA);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},W)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!Oj(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await s2({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 k0("hub_connection_closed",Lj),this.sawSocketClose=!1;for(let W of this.pendingReplies.values())W.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 k0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,W){this.sendFrame({kind:$,clientId:this.clientId,...W?{sessionId:W}:{}})}adjustSubscriptionCount($,W){let Z=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(Z)??0)+W;if(Q<=0){if(this.subscriptionCounts.delete(Z),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(W<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Z,Q),W>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??PA}subscriptionSessionIdFromKey($){return $===PA?void 0:$}handleFrame($){switch($.kind){case"reply":{let W=$.envelope.requestId;if(!W)return;let Z=this.pendingReplies.get(W);if(!Z)return;this.pendingReplies.delete(W),Z.resolve($.envelope);return}case"event":for(let W of this.listeners){if(W.sessionId&&W.sessionId!==$.envelope.sessionId?.trim())continue;W.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function r$($){let W=new URL($);if(W.protocol==="http:")W.protocol="ws:";else if(W.protocol==="https:")W.protocol="wss:";return W.toString()}async function C1($,W){let Z=new O1({url:$,authToken:W?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd});try{return await Z.connect(),!0}catch{return!1}finally{Z.close()}}async function Tj($,W){let Z=r$($),Q=await X$(Z,{authToken:W?.authToken});if(!Q)return{status:"unreachable",url:Z};if(!$S(Q).compatible)return{status:"protocol_mismatch",url:Z};if(W?.verifyConnection===!0&&!await C1(Z,{workspaceRoot:W.workspaceRoot,cwd:W.cwd,authToken:W.authToken}))return{status:"unreachable",url:Z};return{status:"compatible",url:Z}}async function US($){let W=Date.now()+XS;while(Date.now()<W){let Z=await L0($.discoveryPath);if(Z?.url){let Q=await Tj(Z.url,{verifyConnection:!0,authToken:Z.authToken});if(Q.status==="compatible")return p$(Q.url,Z.authToken)}await new Promise((Q)=>setTimeout(Q,YS))}return}async function DS($){let W=Date.now()+HS;while(Date.now()<W){if(!(await X$($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,GS))}return!1}function _S($,W){try{return r$($)===r$(W)}catch{return!1}}function fS($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Z)=>{if(!Z||typeof Z!=="object")return!1;let Q=Z;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function LS($,W,Z){let Q=new O1({url:$,authToken:W,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{let J=await Q.command("session.list",{limit:500},void 0,{timeoutMs:BS});return!fS(J.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function ZW($={}){if($.endpoint?.trim()){let J=await Tj($.endpoint);return J.status==="compatible"?J.url:void 0}let W=DQ(),Z=await L0(W.discoveryPath);if(!Z?.url)return;let Q=await Tj(Z.url,{authToken:Z.authToken});if(Q.status==="compatible")return p$(Q.url,Z.authToken);if(Q.status==="protocol_mismatch")await c0(W.discoveryPath).catch(()=>{return});return}async function s2($={}){let W=await ZW($);if(W&&await C1(W,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return W;if($.endpoint?.trim())return;let Z=DQ();return await T6($.workspaceRoot??process.cwd()),await US(Z)}async function WW($,W){let Z=new URL($),Q=W?.trim()||IA(Z);if(Z.protocol==="ws:")Z.protocol="http:";else if(Z.protocol==="wss:")Z.protocol="https:";return Z.pathname="/shutdown",Z.hash="",(await fetch(Z,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function Mj($=DQ()){let W=await L0($.discoveryPath);if(!W?.url)return!1;try{if(await WW(W.url,W.authToken))return!0}catch{}return!1}async function fQ($){if(!Oj($.url))return;let W=DQ(),Z=await L0(W.discoveryPath);if(!Z?.url||!_S(Z.url,$.url))return;if(!await LS(Z.url,Z.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await Mj())return;if(!await DS(Z.url))return;return await c0(W.discoveryPath).catch(()=>{return}),await s2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var aA={};w(aA,{HubRuntimeHost:()=>Y$});import{resolveProviderRequestHeaders as qS}from"@cline/llms";import{captureSdkError as Rj,createSessionId as gA,HUB_CHECKPOINT_CAPABILITY as MS,HUB_COMPACTION_CAPABILITY as RS,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as NS,HUB_HOOK_CAPABILITY_PREFIX as ES,HUB_MISTAKE_LIMIT_CAPABILITY as wS,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as CS,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as PS,isHubToolExecutorName as SS}from"@cline/shared";var xA={};w(xA,{createCoreSessionSnapshot:()=>P1,coreSessionSnapshotToRecord:()=>LQ});function OS($){return $?JSON.parse(JSON.stringify($)):void 0}function TS($){return $?JSON.parse(JSON.stringify($)):void 0}function zS($){let W=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(W?.history)?W.history:[]).filter((X)=>!!X&&typeof X==="object"&&!Array.isArray(X)).flatMap((X)=>{let Y=typeof X.ref==="string"?X.ref.trim():"",V=Number(X.createdAt),B=Number(X.runCount);if(!Y||!Number.isFinite(V)||!Number.isInteger(B))return[];return[{ref:Y,createdAt:V,runCount:B,...X.kind==="stash"||X.kind==="commit"?{kind:X.kind}:{}}]}),J=Q.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Q.length===0)return;return{...j?{enabled:j}:{},...J?{latest:J}:{},history:Q}}function P1($){let{session:W}=$,Z=OS(W.metadata);return{version:1,sessionId:W.sessionId,source:W.source,status:W.status,createdAt:W.startedAt,updatedAt:W.updatedAt,endedAt:W.endedAt??null,exitCode:W.exitCode??null,interactive:W.interactive,workspace:{cwd:W.cwd,root:W.workspaceRoot},model:{providerId:W.provider,modelId:W.model},capabilities:{enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams},lineage:{...W.parentSessionId?{parentSessionId:W.parentSessionId}:{},...W.parentAgentId?{parentAgentId:W.parentAgentId}:{},...W.agentId?{agentId:W.agentId}:{},...W.conversationId?{conversationId:W.conversationId}:{},isSubagent:W.isSubagent},...W.teamName?{team:{name:W.teamName}}:{},...W.prompt?{prompt:W.prompt}:{},...Z?{metadata:Z}:{},...W.messagesPath?{artifacts:{messagesPath:W.messagesPath}}:{},...$.messages?{messages:TS($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=zS(Z);return Q?{checkpoint:Q}:{}})()}}function LQ($){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 q6($){if(!$)return;return JSON.parse(JSON.stringify($))}var bS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function mA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function vA($){if(!$)return;let{userInstructionService:W,...Z}=$;return JSON.parse(JSON.stringify(Z))}function cA($,W){let Z={...$.config,sessionId:W},Q=qS({providerId:$.config.providerId,sessionId:W,source:$.source,defaultSource:K0.CORE,client:{name:$.localRuntime?.extensionContext?.client?.name,version:$.localRuntime?.extensionContext?.client?.version,versionHeaderFallback:$.config.headers?.["X-CLIENT-VERSION"],platform:$.localRuntime?.extensionContext?.client?.platform,platformVersion:$.localRuntime?.extensionContext?.client?.platformVersion,isMultiRoot:$.localRuntime?.extensionContext?.client?.isMultiRoot},coreVersion:p8,openAiCodex:{accessToken:$.config.apiKey,userAgentVersion:process.env.npm_package_version},headers:{config:$.config.headers}});if(Q)Z.headers=Q;return Z}function uA($){let W=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof W.agentId==="string"?W.agentId:"",conversationId:typeof W.conversationId==="string"?W.conversationId:"",iteration:typeof W.iteration==="number"?W.iteration:0,metadata:W.metadata&&typeof W.metadata==="object"&&!Array.isArray(W.metadata)?W.metadata:void 0}}function t2($,W,Z){$.manifest.push(W),$.handlers.set(W.capabilityName,Z)}function dA($,W){let Z={manifest:[],handlers:new Map};for(let J of Object.keys(W.toolExecutors??{}).filter(SS)){let j=W.toolExecutors?.[J];if(typeof j!=="function")continue;t2(Z,{kind:"toolExecutor",executor:J,capabilityName:`${CS}${J}`},async({payload:X,abortSignal:Y})=>{let V=Array.isArray(X.args)?[...X.args]:[],B={...uA(X.context),signal:Y};return{result:await j(...V,B)}})}for(let J of $?.extraTools??[])t2(Z,{kind:"tool",name:J.name,description:J.description,inputSchema:q6(J.inputSchema)??{},...J.lifecycle?{lifecycle:q6(J.lifecycle)}:{},capabilityName:`${NS}${J.name}`},async({payload:j,abortSignal:X,progress:Y})=>{let V={...uA(j.context),signal:X};return{result:await J.execute(j.input,{...V,emitUpdate:(H)=>{Y({update:H})}})}});let Q=$?.hooks;if(Q)for(let J of bS){let j=Q[J];if(typeof j!=="function")continue;t2(Z,{kind:"hook",name:J,capabilityName:`${ES}${J}`},async({payload:X})=>({control:await j(X.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;t2(Z,{kind:"compaction",capabilityName:RS,config:mA($.compaction)},async({payload:j})=>({result:await J(j.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;t2(Z,{kind:"checkpoint",capabilityName:MS,config:mA($.checkpoint)},async({payload:j})=>({result:await J(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;t2(Z,{kind:"mistakeLimit",capabilityName:wS},async({payload:j})=>({result:await J(j.context)}))}if($?.userInstructionService){let J=$.userInstructionService;t2(Z,{kind:"userInstructionService",capabilityName:PS},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Z}function iA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let W=$.message;if(typeof W==="string"&&W.trim())return W.trim()}return}function yS($){return iA($)??"Capability request was cancelled."}function hS($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function kS($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function IS($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=typeof W.inputTokens==="number"?W.inputTokens:void 0,Q=typeof W.outputTokens==="number"?W.outputTokens:void 0;if(Z===void 0||Q===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:typeof W.cacheReadTokens==="number"?W.cacheReadTokens:0,cacheWriteTokens:typeof W.cacheWriteTokens==="number"?W.cacheWriteTokens:0,totalCost:typeof W.totalCost==="number"?W.totalCost:0}}function lA($){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 Nj($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function i$($,W){return Nj($?.[W])??0}function xS($){let W=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Z=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=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:i$(W,"inputTokens"),outputTokens:i$(W,"outputTokens"),cacheReadTokens:i$(W,"cacheReadTokens"),cacheWriteTokens:i$(W,"cacheWriteTokens"),cost:Nj(W?.totalCost),totalInputTokens:i$(Z,"inputTokens"),totalOutputTokens:i$(Z,"outputTokens"),totalCacheReadTokens:i$(Z,"cacheReadTokens"),totalCacheWriteTokens:i$(Z,"cacheWriteTokens"),totalCost:Nj(Z?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:J}}function gS($){let W=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Z=$?.reason??W?.finishReason,Q=kS(Z)?Z:Z==="failed"?"error":"completed",J=IS($?.usage??W?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof W?.text==="string"?W.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof W?.iterations==="number"?W.iterations:0,usage:J}}function e2($,W){return $.error?.message??`hub command failed: ${W}`}function QW($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function nA($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof W?.parentSessionId==="string"?W.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof W?.agentId==="string"?W.agentId:void 0),parentAgentId:typeof W?.parentAgentId==="string"?W.parentAgentId:void 0,conversationId:typeof W?.conversationId==="string"?W.conversationId:void 0,isSubagent:typeof W?.isSubagent==="boolean"?W.isSubagent:!1,source:typeof W?.source==="string"?W.source:K0.CORE,pid:typeof W?.pid==="number"?W.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:QW($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:QW($.status)==="completed"?0:QW($.status)==="failed"?1:void 0,status:QW($.status),interactive:W?.interactive===!0,provider:typeof W?.provider==="string"?W.provider:"hub",model:typeof W?.model==="string"?W.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof W?.teamName==="string"?W.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??W?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??W?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??W?.enableTeams===!0,prompt:typeof W?.prompt==="string"?W.prompt:void 0,metadata:W,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof W?.messagesPath==="string"?W.messagesPath:void 0,hookPath:typeof W?.hookPath==="string"?W.hookPath:void 0}}function n$($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$;return W.version===1&&typeof W.sessionId==="string"?JSON.parse(JSON.stringify(W)):void 0}function mS($){let W=n$($?.snapshot);if(W)return LQ(W);let Z=$?.session;return Z?nA(Z):void 0}function pA($,W,Z){let Q=Z?.workspaceRoot?.trim()||W.config.workspaceRoot||W.config.cwd;return m0.parse({version:1,session_id:$,source:W.source??K0.CORE,pid:process.pid,started_at:new Date(Z?.createdAt??Date.now()).toISOString(),status:QW(Z?.status),interactive:W.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:Z?.cwd?.trim()||W.config.cwd,workspace_root:Q,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,metadata:W.sessionMetadata&&Object.keys(W.sessionMetadata).length>0?W.sessionMetadata:void 0})}function rA($,W){return m0.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??W.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class Y${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new t5;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,W){this.clientContext=W,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:W?.workspaceRoot,cwd:W?.cwd},this.defaultCapabilities=w0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Z)=>this.requestPendingPromptsList(Z),update:(Z)=>this.requestPendingPromptUpdate(Z),delete:(Z)=>this.requestPendingPromptDelete(Z)},this.client=this.createClient($.url)}createClient($){return new O1({...this.clientOptions,url:$})}async replaceClient($){let W=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(W.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!_Q($,"session.create"))return!1;let W=await fQ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!W)return!1;return await this.replaceClient(W),!0}registerPlannedSession($,W,Z){if(this.sessionCapabilities.set($,W),Z.size>0)this.sessionClientContributionHandlers.set($,Z);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let W=this.resolveCapabilities($),Z=dA($.localRuntime,W),Q=$.config.sessionId?.trim()||gA(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:q6(cA($,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:{...Z.manifest.length>0?{clientContributions:Z.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:q6($.toolPolicies),initialMessages:$.initialMessages,...$.initialCompactionState?{initialCompactionState:$.initialCompactionState}:{}});this.registerPlannedSession(Q,W,Z.handlers);let j;try{j=await J()}catch(B){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(B)){this.registerPlannedSession(Q,W,Z.handlers);try{j=await J()}catch(H){throw this.cleanupPlannedSession(Q),H}}else throw B}let X=n$(j.payload?.snapshot),Y=j.payload?.session,V=(X?.sessionId??Y?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(V!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(V,W,Z.handlers);return{sessionId:V,manifest:X?rA(X,$):pA(V,$,Y),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,J=Q?this.resolveCapabilities(Q):void 0,j=Q?dA(Q.localRuntime,J??{}):{manifest:[],handlers:new Map},X,Y;if(Q)X=Q.config.sessionId?.trim()||gA(),Y=cA(Q,X);if(X&&J)this.sessionCapabilities.set(X,J);if(X&&j.handlers.size>0)this.sessionClientContributionHandlers.set(X,j.handlers),this.ensureSessionSubscription(X);let V;try{V=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:q6(Y),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:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:q6(Q.toolPolicies),...Q.initialCompactionState?{initialCompactionState:Q.initialCompactionState}:{}}:{}},W)}catch(A){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw A}if(!V.ok){let A=typeof V.payload?.error==="string"?V.payload.error:"session.restore failed";if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error(A)}let B=n$(V.payload?.snapshot),H=V.payload?.session,G=(B?.sessionId??H?.sessionId)?.trim();if(Z&&!G){if(X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);throw Error("Hub checkpoint restore returned no session id")}if(G&&X&&G!==X)this.sessionCapabilities.delete(X),this.sessionClientContributionHandlers.delete(X),this.disposeSessionSubscription(X);if(G&&J)this.sessionCapabilities.set(G,J);if(G&&j.handlers.size>0)this.sessionClientContributionHandlers.set(G,j.handlers);if(G)this.ensureSessionSubscription(G);let K=Array.isArray(V.payload?.messages)?V.payload.messages:void 0,F=V.payload?.checkpoint;if(!F)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:G,startResult:G?{sessionId:G,manifest:B?rA(B,Q??{}):pA(G,Q??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:K,checkpoint:F}}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 W=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(W.payload?.prompts)?W.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,updated:W.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let W=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(W.payload?.prompts)?W.payload.prompts:[],prompt:W.payload?.prompt,removed:W.payload?.removed===!0}}async getAccumulatedUsage($){let W=await this.client.command("session.get",{includeSnapshot:!0},$),Z=n$(W.payload?.snapshot);if(Z){let X=Z.usage?{...Z.usage}:void 0,Y=Z.aggregateUsage?{...Z.aggregateUsage}:void 0;return X||Y?{usage:X,aggregateUsage:Y}:void 0}let Q=W.payload?.session,J=lA(Q?.usage),j=lA(Q?.aggregateUsage);return J||j?{usage:J,aggregateUsage:j}:void 0}async abort($,W){await this.client.command("run.abort",{sessionId:$,reason:iA(W)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,W]of this.sessionSubscriptions){W();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 W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(J$(Z))return;throw Z}return mS(W.payload)}async listSessions($=100){let W=await this.client.command("session.list",{limit:$}),Z=Array.isArray(W.payload?.snapshots)?W.payload.snapshots.flatMap((J)=>{let j=n$(J);return j?[LQ(j)]:[]}):[];if(Z.length>0)return Z;return(W.payload?.sessions??[]).map(nA)}async listSettings($){let W=await this.client.command("settings.list",vA($));if(!W.ok)throw Error(e2(W,"settings.list"));return W.payload?.snapshot}async toggleSetting($){let W=await this.client.command("settings.toggle",vA($));if(!W.ok)throw Error(e2(W,"settings.toggle"));return{snapshot:W.payload?.snapshot,changedTypes:Array.isArray(W.payload?.changedTypes)?W.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,W){let Z={...W.metadata??{}};if(typeof W.prompt==="string")Z.prompt=W.prompt;if(typeof W.title==="string")Z.title=W.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Z})).ok}}async updateSessionConnection($,W){let Z=$.trim();if(!Z)return;let Q=await this.client.command("session.update_connection",{sessionId:Z,updates:W},Z);if(!Q.ok)throw Error(e2(Q,"session.update_connection"))}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=await this.client.command("session.compaction.update",{sessionId:Z,state:W},Z);if(!Q.ok)Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.update_session_compaction_state",error:Error(e2(Q,"session.compaction.update")),severity:"warn",handled:!0,context:{command:"session.compaction.update",sessionId:Z,errorCode:Q.error?.code}});return{updated:Q.ok&&Q.payload?.updated===!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=await this.client.command("session.compaction.get",{sessionId:W},W);if(!Z.ok)throw Error(e2(Z,"session.compaction.get"));return A1(Z.payload?.state)}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(e2(Z,"session.messages")),severity:Z.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:W,errorCode:Z.error?.code,runtimeAddress:this.runtimeAddress}}),Error(e2(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,W){return this.events.subscribe($,W)}ensureSessionSubscription($){let W=$.trim();if(!W||this.sessionSubscriptions.has(W))return;let Z=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:W});this.sessionSubscriptions.set(W,typeof Z==="function"?Z:()=>{})}disposeSessionSubscription($){let W=$.trim();if(!W)return;this.sessionSubscriptions.get(W)?.(),this.sessionSubscriptions.delete(W),this.agentDoneEmittedForCurrentRunBySession.delete(W)}resolveCapabilities($){return w0(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:gS($.payload)}})}handleHubEvent($){let W=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Z,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Z)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Z,$)});return}if(!W)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(W);let Z=n$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,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"session.notice":{let Z=$.payload?.noticeType,Q=$.payload?.displayRole,J=$.payload?.reason,j=$.payload?.agent&&typeof $.payload.agent==="object"?$.payload.agent:void 0,X=j?.teamRole==="lead"||j?.teamRole==="teammate"?j.teamRole:void 0;this.events.emit({type:"agent_event",payload:{sessionId:W,...X?{teamRole:X}:{},...typeof j?.teamAgentId==="string"?{teamAgentId:j.teamAgentId}:{},event:{type:"notice",...typeof j?.agentId==="string"?{agentId:j.agentId}:{},...typeof j?.conversationId==="string"?{conversationId:j.conversationId}:{},...typeof j?.parentAgentId==="string"?{parentAgentId:j.parentAgentId}:{},noticeType:Z==="recovery"||Z==="stop"?Z:"status",message:typeof $.payload?.message==="string"?$.payload.message:"",...Q==="system"||Q==="status"?{displayRole:Q}:{},...typeof J==="string"?{reason:J}:{},...$.payload?.metadata&&typeof $.payload.metadata==="object"?{metadata:$.payload.metadata}:{}}}});return}case"assistant.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"";if(!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"text",text:Z}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Z=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!Z&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_start",contentType:"reasoning",reasoning:Z,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:W,payload:$.payload});return}case"usage.updated":{let Z=xS($.payload);this.events.emit({type:"agent_event",payload:{sessionId:W,event:Z.event,teamAgentId:Z.teamAgentId,teamRole:Z.teamRole}});return}case"tool.started":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z&&this.pendingApprovalToolCallIds.delete(Z))return;this.emitToolCallContentStart({sessionId:W,toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Z)this.pendingApprovalToolCallIds.delete(Z);this.events.emit({type:"agent_event",payload:{sessionId:W,event:{type:"content_end",contentType:"tool",toolCallId:Z,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Z=n$($.payload?.snapshot),Q=$.payload?.session;if(Z)this.events.emit({type:"session_snapshot",payload:{sessionId:W,snapshot:Z}});this.events.emit({type:"status",payload:{sessionId:W,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:W,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Z=$.payload?.prompt;if(!Z)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:W,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Z=n$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:W,payload:{...$.payload,reason:Q}}),Z?.interactive===!0&&G0(Z.status))return;this.events.emit({type:"ended",payload:{sessionId:W,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,W,Z){try{Rj(this.telemetry,{component:"core",operation:$,error:W,severity:"warn",handled:!0,context:{event:Z.event,sessionId:Z.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let W=$.sessionId?.trim();if(!W)return;let Z=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Z&&Z!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let j=this.sessionClientContributionHandlers.get(W)?.get(J);if(!j){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${W}.`},W).catch(()=>{});return}let X=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},Y=new AbortController;this.activeCapabilityAbortControllers.set(Q,Y);let V=(B)=>{this.client.command("capability.progress",{requestId:Q,payload:B},W).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let B=await j({payload:X,abortSignal:Y.signal,progress:V});if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:B},W)}catch(B){if(Y.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:B instanceof Error?B.message:String(B)},W)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let W=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!W)return;let Z=this.activeCapabilityAbortControllers.get(W);if(!Z)return;Z.abort(yS($.payload.error))}async handleApprovalRequested($){let W=$.sessionId?.trim();if(!W)return;let Z=this.sessionCapabilities.get(W)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Z)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!J||!j)return;let X=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},Y=hS($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:W,toolCallId:J,toolName:j,toolInput:Y});let V=await Promise.resolve(Z({sessionId:W,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:W,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:j,input:Y,policy:X})).catch((B)=>({approved:!1,reason:B instanceof Error?B.message:`Tool approval request failed: ${String(B)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:V.approved,reason:V.reason},W).catch(()=>{})}}var oA={};w(oA,{RemoteRuntimeHost:()=>M6});class M6 extends Y${constructor($){super({url:r$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var sA={};w(sA,{SqliteSessionStore:()=>b1});import{existsSync as vS,mkdirSync as cS}from"node:fs";import{join as uS}from"node:path";import{asBool as JW,asOptionalString as S1,asString as V$,ensureSessionSchema as dS,loadSqliteDb as lS,nowIso as OQ,toBoolInt as jW}from"@cline/shared/db";import{resolveDbDataDir as pS}from"@cline/shared/storage";class b1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??pS()}init(){this.getRawDb()}ensureSessionsDir(){if(!vS(this.sessionsDirPath))cS(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return uS(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=lS(this.sessionDbPath());return dS($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}create($){let W=OQ();this.run(`INSERT OR REPLACE INTO sessions (
508
508
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
509
509
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
510
510
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
511
511
  metadata_json, transcript_path, hook_path, messages_path, updated_at
512
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,JW($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,JW($.enableTools),JW($.enableSpawn),JW($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,JW($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(OQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:K0(W)?null:OQ(),exitCode:K0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
512
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,jW($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,jW($.enableTools),jW($.enableSpawn),jW($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,jW($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,W])}update($){let W=[],Z=[];if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId);if(W.length===0)return;W.push("updated_at = ?"),Z.push(OQ()),Z.push($.sessionId),this.run(`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`,Z)}updateStatus($,W,Z){this.update({sessionId:$,status:W,endedAt:G0(W)?null:OQ(),exitCode:G0(W)?null:Z??(W==="failed"?1:0)})}get($){let W=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
513
513
  provider, model, cwd, workspace_root, team_name,
514
514
  enable_tools, enable_spawn, enable_teams,
515
515
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
516
516
  prompt, metadata_json, hook_path, messages_path, updated_at
517
- FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:Y$(W.session_id),source:Y$(W.source),pid:Number(W.pid??0),startedAt:Y$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:Y$(W.status),interactive:QW(W.interactive),provider:Y$(W.provider),model:Y$(W.model),cwd:Y$(W.cwd),workspaceRoot:Y$(W.workspace_root),teamName:P1(W.team_name),enableTools:QW(W.enable_tools),enableSpawn:QW(W.enable_spawn),enableTeams:QW(W.enable_teams),parentSessionId:P1(W.parent_session_id),parentAgentId:P1(W.parent_agent_id),agentId:P1(W.agent_id),conversationId:P1(W.conversation_id),isSubagent:QW(W.is_subagent),prompt:P1(W.prompt),metadata:(()=>{let Z=P1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:P1(W.hook_path),messagesPath:P1(W.messages_path),updatedAt:P1(W.updated_at)??OQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(Y$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}M6();import{existsSync as mj,mkdirSync as mb,readFileSync as DU,renameSync as vb,writeFileSync as cb}from"node:fs";import{join as _U}from"node:path";import{resolveSessionDataDir as ub}from"@cline/shared/storage";import{dirname as xb}from"node:path";import{nanoid as gb}from"nanoid";import{appendFileSync as Qb,existsSync as Jb,mkdirSync as $U,readFileSync as jb,writeFileSync as WU}from"node:fs";import{readFile as ZU,rm as Xb}from"node:fs/promises";import{dirname as QU,join as Yb}from"node:path";import{ensureHookLogDir as Vb}from"@cline/shared/storage";import{randomUUID as tS}from"node:crypto";import{mkdir as eS,open as tA,rename as $b,rm as Wb}from"node:fs/promises";import{dirname as sA}from"node:path";async function Zb($){let W;try{W=await tA($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function eA($,W){await eS(sA($),{recursive:!0});let Z=`${$}.${process.pid}.${tS()}.tmp`,Q;try{Q=await tA(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await $b(Z,$),await Zb(sA($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await Wb(Z,{force:!0})}catch{}throw J}}function Bb($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class Ej{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new TJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){AG(W,Z,x3($))}writeSessionManifest($,W){$U(QU($),{recursive:!0}),WU($,`${JSON.stringify(x0.parse(W),null,2)}
518
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await ZU(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!Jb(W))return{path:W};try{return{path:W,manifest:x0.parse(JSON.parse(jb(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=g3({updatedAt:X0(),context:x3($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
- `;if($U(QU(Q),{recursive:!0}),WU(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return K1(JSON.parse(await ZU(W,"utf8")))}catch(Z){if(Bb(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=F4.parse(W);await eA(Z,`${JSON.stringify(Q,null,2)}
520
- `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await Xb(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Yb(Vb(),"hooks.jsonl");Qb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
- `,"utf8")}}import{appendFileSync as Hb}from"node:fs";import{join as Gb}from"node:path";import{resolveRootSessionId as JU}from"@cline/shared";import{ensureHookLogDir as Kb}from"@cline/shared/storage";import{z as wj}from"zod";var Fb="subagent",Ab=wj.looseObject({task:wj.string().optional(),systemPrompt:wj.string().optional()});class TQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:Fb,pid:process.ppid,startedAt:W.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:o4({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=JU($.sessionContext);if(!W)return;let Z=Ab.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=v8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:o4({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=JU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=v8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,i4(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=K0(W)?null:X0(),J=K0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=p4($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Gb(Kb(),"hooks.jsonl");Hb(Z,`${JSON.stringify({ts:X0(),...$})}
522
- `,"utf8")}}import{formatUserInputBlock as Ib}from"@cline/shared";var UU={};w(UU,{toTeamProgressLifecycleEvent:()=>w6,sanitizeTeamName:()=>JG,reviveTeamStateDates:()=>a9,parseConfiguredAgentConfig:()=>jW,loadConfiguredAgentConfigs:()=>R6,createWorkerReviewerTeam:()=>AU,createSpawnAgentTool:()=>C$,createDelegatedAgentConfigProvider:()=>E$,createDelegatedAgent:()=>w$,createConfiguredAgentTools:()=>N6,createAgentTeamsTools:()=>M2,createAgentTeam:()=>Sj,buildTeamProgressSummary:()=>E6,buildDelegatedAgentConfig:()=>z2,buildConfiguredAgentToolName:()=>XW,buildConfiguredAgentToolDescriptors:()=>YW,bootstrapAgentTeams:()=>m8,AgentTeamsRuntime:()=>$8,AgentTeam:()=>P6});import{existsSync as Ub,readdirSync as Db,readFileSync as _b}from"node:fs";import{basename as jU,extname as fb,join as Lb}from"node:path";import{stripUtf8Bom as Ob}from"@cline/shared";import{resolveAgentConfigSearchPaths as Tb}from"@cline/shared/storage";import YU from"yaml";import{z as h0}from"zod";var VU=h0.object({name:h0.string().trim().min(1),description:h0.string().trim().min(1),tools:h0.union([h0.string(),h0.array(h0.string())]).optional(),skills:h0.union([h0.string(),h0.array(h0.string())]).optional(),providerId:h0.string().trim().min(1).optional(),modelId:h0.string().trim().min(1).optional(),maxIterations:h0.number().int().positive().optional()});function zb($){$=Ob($);let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=YU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;VU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function XU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function qb($){return $.trim().toLowerCase()}function Mb($){let W=fb($).toLowerCase();return W===".yml"||W===".yaml"}function jW($,W={}){let{frontmatter:Z,body:Q}=zb($),J=YU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=VU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:XU(j.tools),skills:XU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function R6($){let W=$.searchPaths??Tb($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!Ub(j))continue;let X;try{X=Db(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!Mb(Y.name))continue;let V=Lb(j,Y.name);try{let B=_b(V,"utf8"),H=jW(B,{path:V}),G=qb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?jU(j.path):j.name).localeCompare(X.path?jU(X.path):X.name)),errors:Q}}import{createTool as Rb,zodToJsonSchema as Nb}from"@cline/shared";import{z as BU}from"zod";var Cj="subagent_",zQ=64,Eb=BU.object({prompt:BU.string().trim().min(1).describe("Task for the subagent to perform")});function wb($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function Cb($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function XW($){let W=wb($)||"agent",Z=Cb($).slice(0,6),Q=`${Cj}${W}`;if(Q.length<=zQ)return Q;let J=zQ-Cj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${Cj}${j}_${Z}`.slice(0,zQ)}function YW($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=XW(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,zQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function Pb($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function N6($){return YW($.agents).map(({toolName:W,config:Z})=>{return Rb({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:Nb(Eb),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=E$(Pb(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=w$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),D={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:D,agentResult:A})}catch{}return D}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function b1(){return new Date().toISOString()}function HU($,W){if(W<=0)return 0;return Math.round($/W*100)}function Sb($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function E6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((_)=>{return K.get(_)?.status==="completed"}))H.push(U.id)}let F=[],A,D=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let f=U.startedAt.getTime();if(f>=D)D=f,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:b1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:HU(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:HU(j.finalized,W.outcomes.length),missingRequiredSections:Sb(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function w6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),taskId:W.task.id,agentId:W.task.assignee??W.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:b1()}}import{sanitizeFileName as bb,TeamMessageType as m}from"@cline/shared";import{nanoid as yb}from"nanoid";import{TeamMessageType as xo}from"@cline/shared";function Pj($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function GU($,W){return $?.status==="stopped"&&Pj(W)}var hb=600000,KU="recovered_queued";function kb($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
523
-
524
- ${$.message}`}class P6{agents=new Map;configs=new Map;onTeamEvent;constructor($,W){if(this.onTeamEvent=W,$)for(let[Z,Q]of Object.entries($))this.addAgent(Z,Q)}addAgent($,W){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Z={...W,onEvent:(J)=>{W.onEvent?.(J),this.emitEvent({type:m.AgentEvent,agentId:$,event:J})}},Q=new N$(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);this.agents.set($,Q),this.configs.set($,W)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.run(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async continueTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let Q=await Z.continue(W);return this.emitEvent({type:m.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:m.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async runParallel($){let W=$.map(async(Z)=>{let Q=this.agents.get(Z.agentId);if(!Q)return{agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata};this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),{agentId:Z.agentId,result:J,metadata:Z.metadata}}catch(J){let j=J instanceof Error?J:Error(String(J));return this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),{agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata}}});return Promise.all(W)}async runSequential($){let W=[];for(let Z of $){let Q=this.agents.get(Z.agentId);if(!Q){W.push({agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata});continue}this.emitEvent({type:m.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,result:J}),W.push({agentId:Z.agentId,result:J,metadata:Z.metadata})}catch(J){let j=J instanceof Error?J:Error(String(J));this.emitEvent({type:m.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),W.push({agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata})}}return W}async runPipeline($,W,Z){let Q=[],J=W;for(let j of $){let X=this.agents.get(j);if(!X){Q.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:m.TaskStart,agentId:j,message:J});try{let Y=await X.run(J);this.emitEvent({type:m.TaskEnd,agentId:j,result:Y}),Q.push({agentId:j,result:Y});let V=$.indexOf(j)+1;if(V<$.length){let B=$[V];J=Z?Z(Y,B):`Previous agent output:
517
+ FROM sessions WHERE session_id = ?`,[$]);if(!W)return;return{sessionId:V$(W.session_id),source:V$(W.source),pid:Number(W.pid??0),startedAt:V$(W.started_at),endedAt:W.ended_at??null,exitCode:W.exit_code??null,status:V$(W.status),interactive:JW(W.interactive),provider:V$(W.provider),model:V$(W.model),cwd:V$(W.cwd),workspaceRoot:V$(W.workspace_root),teamName:S1(W.team_name),enableTools:JW(W.enable_tools),enableSpawn:JW(W.enable_spawn),enableTeams:JW(W.enable_teams),parentSessionId:S1(W.parent_session_id),parentAgentId:S1(W.parent_agent_id),agentId:S1(W.agent_id),conversationId:S1(W.conversation_id),isSubagent:JW(W.is_subagent),prompt:S1(W.prompt),metadata:(()=>{let Z=S1(W.metadata_json);if(!Z)return;try{let Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:S1(W.hook_path),messagesPath:S1(W.messages_path),updatedAt:S1(W.updated_at)??OQ()}}list($=200){let W=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Z=[];for(let Q of W){let J=this.get(V$(Q.session_id));if(J)Z.push(J)}return Z}delete($,W=!1){let Z=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}}R6();import{existsSync as mj,mkdirSync as pb,readFileSync as _U,renameSync as rb,writeFileSync as ib}from"node:fs";import{join as fU}from"node:path";import{resolveSessionDataDir as nb}from"@cline/shared/storage";import{dirname as db}from"node:path";import{nanoid as lb}from"nanoid";import{appendFileSync as Bb,existsSync as Hb,mkdirSync as WU,readFileSync as Gb,writeFileSync as ZU}from"node:fs";import{readFile as QU,rm as Kb}from"node:fs/promises";import{dirname as JU,join as Fb}from"node:path";import{ensureHookLogDir as Ab}from"@cline/shared/storage";import{randomUUID as Jb}from"node:crypto";import{mkdir as jb,open as eA,rename as Xb,rm as Yb}from"node:fs/promises";import{dirname as tA}from"node:path";async function Vb($){let W;try{W=await eA($,"r"),await W.sync()}catch{}finally{if(W!==void 0)try{await W.close()}catch{}}}async function $U($,W){await jb(tA($),{recursive:!0});let Z=`${$}.${process.pid}.${Jb()}.tmp`,Q;try{Q=await eA(Z,"wx"),await Q.writeFile(W,"utf8"),await Q.sync(),await Q.close(),Q=void 0,await Xb(Z,$),await Vb(tA($))}catch(J){if(Q!==void 0)try{await Q.close()}catch{}try{await Yb(Z,{force:!0})}catch{}throw J}}function Ub($){return typeof $==="object"&&$!==null&&"code"in $&&$.code==="ENOENT"}class Ej{adapter;messagesArtifactUploader;logger;artifacts;constructor($,W,Z){this.adapter=$;this.messagesArtifactUploader=W;this.logger=Z;this.artifacts=new TJ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,W,Z){UG(W,Z,x3($))}writeSessionManifest($,W){WU(JU($),{recursive:!0}),ZU($,`${JSON.stringify(m0.parse(W),null,2)}
518
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}async readSessionManifestTitle($){let W=this.artifacts.sessionManifestPath($,!1),Z;try{Z=await QU(W,"utf8")}catch{return}try{let Q=JSON.parse(Z);if(!Q||typeof Q!=="object"||Array.isArray(Q))return;let J=Q.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let j=J.title;return typeof j==="string"?j:void 0}catch{return}}readManifestFile($){let W=this.artifacts.sessionManifestPath($,!1);if(!Hb(W))return{path:W};try{return{path:W,manifest:m0.parse(JSON.parse(Gb(W,"utf8")))}}catch{return{path:W}}}async resolveArtifactPath($,W,Z){let J=(await this.adapter.getSession($))?.[W];return typeof J==="string"&&J.trim().length>0?J:Z($)}async persistSessionMessages($,W,Z){let Q=await this.resolveArtifactPath($,"messagesPath",(X)=>this.artifacts.sessionMessagesPath(X)),J=g3({updatedAt:X0(),context:x3($),messages:W,systemPrompt:Z}),j=`${JSON.stringify(J,null,2)}
519
+ `;if(WU(JU(Q),{recursive:!0}),ZU(Q,j,"utf8"),!this.messagesArtifactUploader)return;try{let X=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:j,row:X})}catch(X){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:X})}}resolveCompactionPath($){let{manifest:W}=this.readManifestFile($);return W?.compaction_path?.trim()||this.artifacts.sessionCompactionPath($)}updateCompactionPath($,W){let Z=this.readManifestFile($);if(!Z.manifest)return;if(Z.manifest.compaction_path===W)return;this.writeSessionManifest(Z.path,{...Z.manifest,compaction_path:W})}async readSessionCompactionState($){let W=this.resolveCompactionPath($);try{return A1(JSON.parse(await QU(W,"utf8")))}catch(Z){if(Ub(Z))return;this.logger?.debug("Ignoring invalid session compaction state",{sessionId:$,path:W,error:Z,recovery:"Canonical history is unchanged; deleting the sidecar is safe."});return}}async persistSessionCompactionState($,W){let Z=this.resolveCompactionPath($),Q=A4.parse(W);await $U(Z,`${JSON.stringify(Q,null,2)}
520
+ `),this.updateCompactionPath($,Z)}async deleteSessionCompactionState($){await Kb(this.resolveCompactionPath($),{force:!0}),this.updateCompactionPath($,void 0)}appendStaleSessionHookLog($,W,Z,Q,J){let X=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Fb(Ab(),"hooks.jsonl");Bb(X,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:W,pid:Z,source:J})}
521
+ `,"utf8")}}import{appendFileSync as Db}from"node:fs";import{join as _b}from"node:path";import{resolveRootSessionId as jU}from"@cline/shared";import{ensureHookLogDir as fb}from"@cline/shared/storage";import{z as wj}from"zod";var Lb="subagent",Ob=wj.looseObject({task:wj.string().optional(),systemPrompt:wj.string().optional()});class TQ{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,W,Z,Q){this.adapter=$;this.manifestStore=W;this.toPersistedMessages=Z;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,W){return`${$}::${W}`}activeTeamTaskSessionId($,W){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,W))?.at(-1)}buildSubsessionRow($,W){return{sessionId:W.sessionId,source:Lb,pid:process.ppid,startedAt:W.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:W.parentSessionId,parentAgentId:W.parentAgentId,agentId:W.agentId,conversationId:W.conversationId??null,isSubagent:!0,prompt:W.prompt,metadata:s4({prompt:W.prompt}),hookPath:"",messagesPath:W.messagesPath,updatedAt:W.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let W=jU($.sessionContext);if(!W)return;let Z=Ob.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:W,parentAgentId:$.agent_id,task:Z.success?Z.data.task:void 0,systemPrompt:Z.success?Z.data.systemPrompt:void 0})}async upsertSubagentSession($){let W=$.rootSessionId;if(!W)return;let Z=await this.adapter.getSession(W);if(!Z)return;let Q=c8(W,$.agentId),J=await this.adapter.getSession(Q),j=X0(),X=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(W,$.parentAgentId)),Y=$.prompt??J?.prompt??void 0;if(!Y)Y=await this.adapter.claimSpawnRequest(W,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:Q,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Y,startedAt:j,...X})),this.manifestStore.initializeMessagesFile(Q,X.messagesPath,j),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:W,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??Y??null,metadata:s4({metadata:J.metadata??void 0,prompt:J.prompt??Y??null}),expectedStatusLock:J.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let W=jU($.sessionContext);if(!W)return;if($.hookName==="session_shutdown"){let Z=c8(W,$.agent_id);return await this.adapter.getSession(Z)?Z:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:W})}async applySubagentStatus($,W){await this.applySubagentStatusBySessionId($,n4(W))}async applySubagentStatusBySessionId($,W){let Z=await this.adapter.getSession($);if(!Z)return;let Q=G0(W)?null:X0(),J=G0(W)?null:W==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:W,endedAt:Q,exitCode:J,expectedStatusLock:Z.statusLock})}async applyStatusToRunningChildSessions($,W){if(!$)return;let Z=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of Z)await this.applySubagentStatusBySessionId(Q.sessionId,W)}async onTeamTaskStart($,W,Z){let Q=await this.adapter.getSession($);if(!Q)return;let J=r4($,W),j=X0(),{messagesPath:X}=this.manifestStore.artifacts.subagentArtifactPaths(J,W);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:W,prompt:Z||`Team task for ${W}`,startedAt:j,messagesPath:X})),this.manifestStore.initializeMessagesFile(J,X,j);let Y=this.teamTaskQueueKey($,W),V=this.teamTaskSessionsByAgent.get(Y)??[];V.push(J),this.teamTaskSessionsByAgent.set(Y,V)}async onTeamTaskEnd($,W,Z,Q,J,j){let X=this.teamTaskQueueKey($,W),Y=this.teamTaskSessionsByAgent.get(X);if(!Y||Y.length===0)return;let V=Y.shift();if(Y.length===0)this.teamTaskSessionsByAgent.delete(X);if(!V)return;let B=J?.messages??j,H=this.toPersistedMessages(B,J,j);if(H)await this.manifestStore.persistSessionMessages(V,H);await this.applySubagentStatusBySessionId(V,Z),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,W,Z,Q){let J=this.teamTaskQueueKey($,W),j=this.teamTaskSessionsByAgent.get(J)?.[0];if(!j)return;let X=Z.trim();if(!X)return;let Y=Q?.kind??"progress";if(Y==="heartbeat"){let B=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(B-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,B)}let V=Y==="heartbeat"?"[progress] heartbeat":Y==="text"?`[progress] text: ${X}`:`[progress] ${X}`;if(this.teamTaskLastProgressLineBySession.get(j)===V)return;this.teamTaskLastProgressLineBySession.set(j,V)}async handleSubAgentStart($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;await this.applySubagentStatusBySessionId(Z,"running")}async handleSubAgentEnd($,W){let Z=await this.upsertSubagentSession({agentId:W.subAgentId,parentAgentId:W.parentAgentId,conversationId:W.conversationId,prompt:W.input.task,rootSessionId:$});if(!Z)return;if(W.error){await this.applySubagentStatusBySessionId(Z,"failed");return}let Q=this.toPersistedMessages(W.agentResult?.messages,W.agentResult);if(Q)await this.manifestStore.persistSessionMessages(Z,Q);let J=W.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Z,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Z=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??_b(fb(),"hooks.jsonl");Db(Z,`${JSON.stringify({ts:X0(),...$})}
522
+ `,"utf8")}}import{formatUserInputBlock as ub}from"@cline/shared";var DU={};w(DU,{toTeamProgressLifecycleEvent:()=>C6,sanitizeTeamName:()=>jG,reviveTeamStateDates:()=>a9,parseConfiguredAgentConfig:()=>XW,loadConfiguredAgentConfigs:()=>N6,createWorkerReviewerTeam:()=>UU,createSpawnAgentTool:()=>P$,createDelegatedAgentConfigProvider:()=>w$,createDelegatedAgent:()=>C$,createConfiguredAgentTools:()=>E6,createAgentTeamsTools:()=>M2,createAgentTeam:()=>Sj,buildTeamProgressSummary:()=>w6,buildDelegatedAgentConfig:()=>z2,buildConfiguredAgentToolName:()=>YW,buildConfiguredAgentToolDescriptors:()=>VW,bootstrapAgentTeams:()=>v8,AgentTeamsRuntime:()=>$8,AgentTeam:()=>S6});import{existsSync as Tb,readdirSync as zb,readFileSync as qb}from"node:fs";import{basename as XU,extname as Mb,join as Rb}from"node:path";import{stripUtf8Bom as Nb}from"@cline/shared";import{resolveAgentConfigSearchPaths as Eb}from"@cline/shared/storage";import VU from"yaml";import{z as I0}from"zod";var BU=I0.object({name:I0.string().trim().min(1),description:I0.string().trim().min(1),tools:I0.union([I0.string(),I0.array(I0.string())]).optional(),skills:I0.union([I0.string(),I0.array(I0.string())]).optional(),providerId:I0.string().trim().min(1).optional(),modelId:I0.string().trim().min(1).optional(),maxIterations:I0.number().int().positive().optional()});function wb($){$=Nb($);let W=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!W)throw Error("Missing YAML frontmatter block in agent config file.");let Z=W[0].length,Q=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Q.lastIndex=Z;let J,j=Array.from($.matchAll(Q)).filter((X)=>X.index>=Z);for(let X of j){let Y=X.index,V=$.slice(Z,Y);try{let B=VU.parse(V);if(!B||typeof B!=="object"||Array.isArray(B))continue;BU.parse(B);let H=$.slice(Y+X[0].length);J={frontmatter:V,body:H}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function YU($){if($===void 0)return;let W=Array.isArray($)?$:$.split(",");return Array.from(new Set(W.map((Z)=>Z.trim()).filter((Z)=>Z.length>0)))}function Cb($){return $.trim().toLowerCase()}function Pb($){let W=Mb($).toLowerCase();return W===".yml"||W===".yaml"}function XW($,W={}){let{frontmatter:Z,body:Q}=wb($),J=VU.parse(Z);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let j=BU.parse(J),X=Q.trim();if(!X)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:YU(j.tools),skills:YU(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:X,path:W.path}}function N6($){let W=$.searchPaths??Eb($.workspaceRoot),Z=new Map,Q=[];for(let j of W.filter(Boolean)){if(!Tb(j))continue;let X;try{X=zb(j,{withFileTypes:!0})}catch(Y){Q.push({path:j,error:Y instanceof Error?Y:Error(String(Y))});continue}for(let Y of X){if(!Y.isFile()||!Pb(Y.name))continue;let V=Rb(j,Y.name);try{let B=qb(V,"utf8"),H=XW(B,{path:V}),G=Cb(H.name);if(!Z.has(G))Z.set(G,H)}catch(B){Q.push({path:V,error:B instanceof Error?B:Error(String(B))})}}}return{configs:Array.from(Z.values()).sort((j,X)=>(j.path?XU(j.path):j.name).localeCompare(X.path?XU(X.path):X.name)),errors:Q}}import{createTool as Sb,zodToJsonSchema as bb}from"@cline/shared";import{z as HU}from"zod";var Cj="subagent_",zQ=64,yb=HU.object({prompt:HU.string().trim().min(1).describe("Task for the subagent to perform")});function hb($){let W="",Z=!0;for(let Q of $.trim().toLowerCase()){let J=Q.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||Q==="_")||Q==="_"){if(!Z)W+="_",Z=!0;continue}W+=Q,Z=!1}return Z?W.slice(0,-1):W}function kb($){let W=2166136261;for(let Z=0;Z<$.length;Z++)W^=$.charCodeAt(Z),W=Math.imul(W,16777619);return(W>>>0).toString(36)}function YW($){let W=hb($)||"agent",Z=kb($).slice(0,6),Q=`${Cj}${W}`;if(Q.length<=zQ)return Q;let J=zQ-Cj.length-Z.length-1,j=W.slice(0,Math.max(1,J));return`${Cj}${j}_${Z}`.slice(0,zQ)}function VW($){let W=new Set,Z=[];for(let Q of[...$].sort((J,j)=>J.name.localeCompare(j.name))){let J=YW(Q.name),j=J,X=2;while(W.has(j)){let Y=`_${X++}`,V=Math.max(1,zQ-Y.length);j=`${J.slice(0,V)}${Y}`}W.add(j),Z.push({toolName:j,config:Q})}return Z}function Ib($,W){return{...$,providerId:W.providerId??$.providerId,modelId:W.modelId??$.modelId,maxIterations:W.maxIterations??$.maxIterations}}function E6($){return VW($.agents).map(({toolName:W,config:Z})=>{return Sb({name:W,description:`Use the "${Z.name}" subagent: ${Z.description}`,inputSchema:bb(yb),execute:async(J,j)=>{let X=$.configProvider.getRuntimeConfig(),Y=w$(Ib(X,Z)),V=$.createSubAgentTools?await $.createSubAgentTools(Z,J,j):[],B=C$({kind:"subagent",prompt:Z.systemPrompt,configProvider:Y,tools:V,maxIterations:Z.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=B.getAgentId(),G=B.getConversationId(),K=j.agentId,F={systemPrompt:Z.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await B.run(J.prompt),D={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,result:D,agentResult:A})}catch{}return D}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function y1(){return new Date().toISOString()}function GU($,W){if(W<=0)return 0;return Math.round($/W*100)}function xb($,W){let Z=new Set;for(let J of W)if(J.status==="reviewed")Z.add(`${J.outcomeId}:${J.section}`);let Q=new Set;for(let J of $){if(J.status==="finalized")continue;for(let j of J.requiredSections)if(!Z.has(`${J.id}:${j}`))Q.add(`${J.id}:${j}`)}return[...Q].sort((J,j)=>J.localeCompare(j))}function w6($,W){let Z={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},X={draft:0,reviewed:0,rejected:0},Y=0,V=0;for(let U of W.members)if(Z[U.status]+=1,U.role==="lead")Y+=1;else V+=1;let B=[],H=[],G=W.tasks.filter((U)=>U.status==="completed").length,K=new Map(W.tasks.map((U)=>[U.id,U]));for(let U of W.tasks){if(Q[U.status]+=1,U.status==="blocked"){B.push(U.id);continue}if(U.status!=="pending")continue;if(U.dependsOn.every((_)=>{return K.get(_)?.status==="completed"}))H.push(U.id)}let F=[],A,D=0;for(let U of W.runs){if(J[U.status]+=1,U.status==="queued"||U.status==="running")F.push(U.id);let f=U.startedAt.getTime();if(f>=D)D=f,A=U.id}for(let U of W.outcomes)j[U.status]+=1;for(let U of W.outcomeFragments)X[U.status]+=1;return{teamName:$,updatedAt:y1(),members:{total:W.members.length,byStatus:Z,leadCount:Y,teammateCount:V},tasks:{total:W.tasks.length,byStatus:Q,blockedTaskIds:B,readyTaskIds:H,completionPct:GU(G,W.tasks.length)},runs:{total:W.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:W.outcomes.length,byStatus:j,finalizedPct:GU(j.finalized,W.outcomes.length),missingRequiredSections:xb(W.outcomes,W.outcomeFragments)},fragments:{total:W.outcomeFragments.length,byStatus:X}}}function C6($){let{event:W}=$;switch(W.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),taskId:W.task.id,agentId:W.task.assignee??W.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),runId:W.run.id,taskId:W.run.taskId,agentId:W.run.agentId,message:W.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),outcomeId:W.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),outcomeId:W.fragment.outcomeId,fragmentId:W.fragment.id,agentId:W.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),taskId:W.message.taskId,agentId:W.message.fromAgentId,message:W.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),taskId:W.entry.taskId,agentId:W.entry.agentId,message:W.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1(),agentId:W.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:W.type,ts:y1()}}import{sanitizeFileName as gb,TeamMessageType as g}from"@cline/shared";import{nanoid as mb}from"nanoid";import{TeamMessageType as po}from"@cline/shared";function Pj($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function KU($,W){return $?.status==="stopped"&&Pj(W)}var vb=600000,FU="recovered_queued";function cb($){return`This is an automatic recovery of interrupted team run ${$.id}. The previous process stopped before completion. Continue the task safely, inspect the current workspace state before making changes, and avoid duplicating completed work.
523
+
524
+ ${$.message}`}class S6{agents=new Map;configs=new Map;onTeamEvent;constructor($,W){if(this.onTeamEvent=W,$)for(let[Z,Q]of Object.entries($))this.addAgent(Z,Q)}addAgent($,W){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Z={...W,onEvent:(J)=>{W.onEvent?.(J),this.emitEvent({type:g.AgentEvent,agentId:$,event:J})}},Q=new E$(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);this.agents.set($,Q),this.configs.set($,W)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:g.TaskStart,agentId:$,message:W});try{let Q=await Z.run(W);return this.emitEvent({type:g.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:g.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async continueTo($,W){let Z=this.agents.get($);if(!Z)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:g.TaskStart,agentId:$,message:W});try{let Q=await Z.continue(W);return this.emitEvent({type:g.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let J=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:g.TaskEnd,agentId:$,error:J,messages:Z.getMessages()}),Q}}async runParallel($){let W=$.map(async(Z)=>{let Q=this.agents.get(Z.agentId);if(!Q)return{agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata};this.emitEvent({type:g.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);return this.emitEvent({type:g.TaskEnd,agentId:Z.agentId,result:J}),{agentId:Z.agentId,result:J,metadata:Z.metadata}}catch(J){let j=J instanceof Error?J:Error(String(J));return this.emitEvent({type:g.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),{agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata}}});return Promise.all(W)}async runSequential($){let W=[];for(let Z of $){let Q=this.agents.get(Z.agentId);if(!Q){W.push({agentId:Z.agentId,result:void 0,error:Error(`Agent "${Z.agentId}" not found in team`),metadata:Z.metadata});continue}this.emitEvent({type:g.TaskStart,agentId:Z.agentId,message:Z.message});try{let J=await Q.run(Z.message);this.emitEvent({type:g.TaskEnd,agentId:Z.agentId,result:J}),W.push({agentId:Z.agentId,result:J,metadata:Z.metadata})}catch(J){let j=J instanceof Error?J:Error(String(J));this.emitEvent({type:g.TaskEnd,agentId:Z.agentId,error:j,messages:Q.getMessages()}),W.push({agentId:Z.agentId,result:void 0,error:j,metadata:Z.metadata})}}return W}async runPipeline($,W,Z){let Q=[],J=W;for(let j of $){let X=this.agents.get(j);if(!X){Q.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:g.TaskStart,agentId:j,message:J});try{let Y=await X.run(J);this.emitEvent({type:g.TaskEnd,agentId:j,result:Y}),Q.push({agentId:j,result:Y});let V=$.indexOf(j)+1;if(V<$.length){let B=$[V];J=Z?Z(Y,B):`Previous agent output:
525
525
  ${Y.text}
526
526
 
527
- Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:m.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function Sj($,W){return new P6($,W)}function AU($){let W=Sj({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
527
+ Please continue from here.`}}catch(Y){let V=Y instanceof Error?Y:Error(String(Y));this.emitEvent({type:g.TaskEnd,agentId:j,error:V,messages:X.getMessages()}),Q.push({agentId:j,result:void 0,error:V});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function Sj($,W){return new S6($,W)}function UU($){let W=Sj({worker:$.worker,reviewer:$.reviewer}),Z=W;return Z.doAndReview=async(Q)=>{let J=await W.routeTo("worker",Q),j=await W.routeTo("reviewer",`Please review this work:
528
528
 
529
- ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class $8{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${bb(yb(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,C6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,C6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,C6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,C6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,C6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,C6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:hb,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:m.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new N$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:m.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!Pj(Q))throw Q}Z.status="stopped",this.emitEvent({type:m.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:m.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:m.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:m.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
529
+ ${J.text}`);return{workerResult:J,reviewResult:j}},Z}class $8{teamId;teamName;onTeamEvent;members=new Map;tasks=new Map;missionLog=[];mailbox=[];missionStepCounter=0;taskCounter=0;messageCounter=0;missionCounter=0;runCounter=0;outcomeCounter=0;outcomeFragmentCounter=0;runs=new Map;runQueue=[];queuedRunDispatchTimer;outcomes=new Map;outcomeFragments=new Map;missionLogIntervalSteps;missionLogIntervalMs;maxConcurrentRuns;constructor($){this.teamName=$.teamName,this.teamId=`t_${gb(mb(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let W=$.leadAgentId??"lead";this.members.set(W,{agentId:W,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((W)=>{let Z=this.getUnresolvedDependencies(W);return{...W,blockedBy:Z,isReady:W.status==="pending"&&!W.assignee&&Z.length===0}}).filter((W)=>{if($?.status&&W.status!==$.status)return!1;if($?.assignee&&W.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,W){let Z=W?.unreadOnly??!0,Q=W?.markRead??!0,J=W?.limit,j=this.mailbox.filter((Y)=>Y.toAgentId===$&&(!Z||!Y.readAt)),X=typeof J==="number"&&J>0?j.slice(Math.max(0,j.length-J)):j;if(Q){let Y=new Date;for(let V of X)if(!V.readAt)V.readAt=Y}return X.map((Y)=>({...Y}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Z of this.tasks.values())$[Z.status]++;let W={draft:0,in_review:0,finalized:0};for(let Z of this.outcomes.values())W[Z.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Z)=>({agentId:Z.agentId,role:Z.role,description:Z.description,status:Z.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Z)=>!Z.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").length,outcomeCounts:W}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Z of $.tasks)this.tasks.set(Z.id,{...Z});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Z)=>({...Z}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Z)=>({...Z}))),this.runs.clear();for(let Z of $.runs??[])this.runs.set(Z.id,{...Z});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Z)=>Z.status==="queued").map((Z)=>Z.id)),this.outcomes.clear();for(let Z of $.outcomes??[])this.outcomes.set(Z.id,{...Z});this.outcomeFragments.clear();for(let Z of $.outcomeFragments??[])this.outcomeFragments.set(Z.id,{...Z});let W=Array.from(this.members.values()).filter((Z)=>Z.role==="lead");this.members.clear();for(let Z of W)this.members.set(Z.agentId,{...Z,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Z of $.members){if(Z.role!=="teammate")continue;this.members.set(Z.agentId,{agentId:Z.agentId,role:"teammate",description:Z.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,P6($.tasks.map((Z)=>Z.id),"task_")),this.messageCounter=Math.max(this.messageCounter,P6($.mailbox.map((Z)=>Z.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,P6($.missionLog.map((Z)=>Z.id),"log_")),this.runCounter=Math.max(this.runCounter,P6(($.runs??[]).map((Z)=>Z.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,P6(($.outcomes??[]).map((Z)=>Z.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,P6(($.outcomeFragments??[]).map((Z)=>Z.id),"frag_"))}isTeammateActive($){let W=this.members.get($);return!!W&&W.role==="teammate"&&!!W.agent}spawnTeammate({agentId:$,config:W}){let Z=this.members.get($);if(Z&&Z.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Z&&Z.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...W,apiTimeoutMs:vb,consumePendingUserMessage:()=>{let X=this.members.get($);if(!X||!X.pendingSteerMessage)return;let Y=X.pendingSteerMessage;return X.pendingSteerMessage=void 0,Y},onEvent:(X)=>{W.onEvent?.(X),this.emitEvent({type:g.AgentEvent,agentId:$,event:X}),this.trackMeaningfulEvent($,X)}},J=new E$(Q);if(Q.onEvent)J.subscribeEvents(Q.onEvent);let j={agentId:$,role:"teammate",description:W.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:g.TeammateSpawned,agentId:$,role:W.role,teammate:{rolePrompt:W.systemPrompt,modelId:W.modelId,maxIterations:W.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,W){let Z=this.members.get($);if(!Z||Z.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Z.agent?.abort()}catch(Q){if(!Pj(Q))throw Q}Z.status="stopped",this.emitEvent({type:g.TeammateShutdown,agentId:$,reason:W})}updateTeammateConnections($){for(let W of this.members.values()){if(W.role!=="teammate"||!W.agent)continue;W.agent.updateConnection($)}}createTask($){let W=`task_${String(++this.taskCounter).padStart(4,"0")}`,Z=new Date,Q={id:W,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Z,updatedAt:Z,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(W,Q),this.emitEvent({type:g.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,W){let Z=this.requireTask($);return this.assertDependenciesResolved(Z),Z.status="in_progress",Z.assignee=W,Z.updatedAt=new Date,this.emitEvent({type:g.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:W,taskId:$,kind:"progress",summary:`Claimed task "${Z.title}"`}),{...Z}}blockTask($,W,Z){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=Z,this.emitEvent({type:g.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"blocked",summary:Z}),{...Q}}completeTask($,W,Z){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=Z,!Q.assignee)Q.assignee=W;return this.emitEvent({type:g.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:W,taskId:$,kind:"done",summary:Z}),{...Q}}async routeToTeammate($,W,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:g.TaskStart,agentId:$,message:W});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=J.length>0?`${this.buildMailboxNotification(J)}
530
530
 
531
- ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:m.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:m.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!GU(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:m.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===KU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:m.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?kb($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:m.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(GU(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:m.RunCancelled,run:{...$},reason:J});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:m.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await FU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await FU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:m.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=KU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:m.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:m.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:m.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:m.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(W.id,W),this.emitEvent({type:m.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:m.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:m.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:m.OutcomeFinalized,outcome:{...W}}),{...W}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(W){if(!Pj(W))throw W}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:m.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function FU($){return new Promise((W)=>setTimeout(W,$))}function C6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function bj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),qQ($);break}default:break}}async function yj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function hj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:w6({teamName:J,sessionId:W,event:Z}),summary:E6(J,$.runtime.teamRuntime.exportState())}})}function VW($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function kj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&VW($)}function qQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function Ij($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function xj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return BW(`System-delivered teammate async run updates:
531
+ ${W}`:W,X=Z?.continueConversation?await Q.agent.continue(j):await Q.agent.run(j);return this.emitEvent({type:g.TaskEnd,agentId:$,result:X}),this.recordProgressStep($,`Completed a delegated run (${X.iterations} iterations)`,Z?.taskId,!0),X}catch(J){let j=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:g.TaskEnd,agentId:$,error:j,messages:Q.agent.getMessages()}),!KU(Q,j))this.appendMissionLog({agentId:$,taskId:Z?.taskId,kind:"error",summary:j.message});throw j}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,W,Z){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:Q,agentId:$,taskId:Z?.taskId,status:"queued",message:W,priority:Z?.priority??0,retryCount:0,maxRetries:Math.max(0,Z?.maxRetries??0),continueConversation:Z?.continueConversation,startedAt:new Date(0),leaseOwner:Z?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,J),this.runQueue.push(Q),this.emitEvent({type:g.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let W=this.selectNextDispatchableQueuedRun();$=W.nextDelayedAttemptAt;let Z=W.index;if(Z<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(Z,1),J=Q?this.runs.get(Q):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,W=Number.NEGATIVE_INFINITY,Z,Q=Date.now();for(let J=0;J<this.runQueue.length;J++){let j=this.runs.get(this.runQueue[J]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Q){if(!Z||j.nextAttemptAt<Z)Z=j.nextAttemptAt;continue}if(j.priority>W)W=j.priority,$=J}return{index:$,nextDelayedAttemptAt:Z}}scheduleQueuedRunDispatch($){if(!$)return;let W=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},W)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let W of this.runs.values())if(W.status==="running")$++;return $}async executeQueuedRun($){let W=$.currentActivity===FU;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:g.RunStarted,run:{...$}});let Z=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=W?cb($):$.message,J=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});if(J.finishReason==="error")throw Error(J.text||"Teammate run failed");$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:g.RunCompleted,run:{...$}})}catch(Q){let J=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=J,$.endedAt=new Date;let j=this.members.get($.agentId);if(KU(j,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:g.RunCancelled,run:{...$},reason:J});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:g.RunFailed,run:{...$}})}finally{clearInterval(Z),this.dispatchQueuedRuns()}}listRuns($){let W=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Z)=>{if(!W&&!["running","queued"].includes(Z.status))return!1;if($?.status&&Z.status!==$.status)return!1;if($?.agentId&&Z.agentId!==$.agentId)return!1;return!0}).map((Z)=>({...Z}))}getRun($){let W=this.runs.get($);return W?{...W}:void 0}async awaitRun($,W=250){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);while(Z.status==="queued"||Z.status==="running")await AU(W);return{...Z}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((W)=>["queued","running"].includes(W.status)))await AU($);return this.listRuns()}cancelRun($,W){let Z=this.runs.get($);if(!Z)throw Error(`Run "${$}" was not found`);if(Z.status==="completed"||Z.status==="failed")return{...Z};Z.status="cancelled",Z.error=W,Z.endedAt=new Date,Z.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:g.RunCancelled,run:{...Z},reason:W}),{...Z}}recoverActiveRuns($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;let Q=this.members.get(Z.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){Z.status="interrupted",Z.error="teammate_unavailable_after_recovery",Z.endedAt=new Date,Z.currentActivity="interrupted",this.emitEvent({type:g.RunInterrupted,run:{...Z},reason:Z.error});continue}let J=new Date;if(Z.status="queued",Z.error=void 0,Z.endedAt=void 0,Z.heartbeatAt=J,Z.lastProgressAt=J,Z.lastProgressMessage=$,Z.currentActivity=FU,!this.runQueue.includes(Z.id))this.runQueue.push(Z.id);W.push({...Z}),this.emitEvent({type:g.RunQueued,run:{...Z}})}return this.dispatchQueuedRuns(),W}markStaleRunsInterrupted($="runtime_recovered"){let W=[];for(let Z of this.runs.values()){if(!["queued","running"].includes(Z.status))continue;Z.status="interrupted",Z.error=$,Z.endedAt=new Date,Z.currentActivity="interrupted",W.push({...Z}),this.emitEvent({type:g.RunInterrupted,run:{...Z},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),W}sendMessage($,W,Z,Q,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(W);if(!j)throw Error(`Unknown recipient "${W}"`);let X={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:W,subject:Z,body:Q,taskId:J,sentAt:new Date};if(this.mailbox.push(X),this.emitEvent({type:g.TeamMessage,message:{...X}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Z}". Use the team_read_mailbox tool to read it at your convenience.`;return{...X}}broadcast($,W,Z,Q){let J=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;J.push(this.sendMessage($,j.agentId,W,Z,Q?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let W={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(W);let Z=this.members.get($.agentId);if(Z)Z.lastMissionAt=Date.now(),Z.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:g.TeamMissionLog,entry:{...W}}),{...W}}createOutcome($){let W={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(W.id,W),this.emitEvent({type:g.OutcomeCreated,outcome:{...W}}),{...W}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let W=this.outcomes.get($.outcomeId);if(!W)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!W.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Z={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Z.id,Z),W.status==="draft")W.status="in_review";return this.emitEvent({type:g.OutcomeFragmentAttached,fragment:{...Z}}),{...Z}}reviewOutcomeFragment($){let W=this.outcomeFragments.get($.fragmentId);if(!W)throw Error(`Fragment "${$.fragmentId}" was not found`);return W.status=$.approved?"reviewed":"rejected",W.reviewedBy=$.reviewedBy,W.reviewedAt=new Date,this.emitEvent({type:g.OutcomeFragmentReviewed,fragment:{...W}}),{...W}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((W)=>W.outcomeId===$).map((W)=>({...W}))}finalizeOutcome($){let W=this.outcomes.get($);if(!W)throw Error(`Outcome "${$}" was not found`);let Z=this.listOutcomeFragments($);for(let Q of W.requiredSections)if(!Z.some((j)=>j.section===Q&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return W.status="finalized",W.finalizedAt=new Date,this.emitEvent({type:g.OutcomeFinalized,outcome:{...W}}),{...W}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(W){if(!Pj(W))throw W}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,W]of this.members.entries())if(W.role==="teammate")this.members.delete($)}requireTask($){let W=this.tasks.get($);if(!W)throw Error(`Task "${$}" was not found`);return W}assertDependenciesResolved($){let W=this.getUnresolvedDependencies($);if(W.length>0)throw Error(`Task "${$.id}" is blocked by "${W[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((W)=>{let Z=this.tasks.get(W);return!Z||Z.status!=="completed"})}trackMeaningfulEvent($,W){if(this.recordRunActivityFromAgentEvent($,W),W.type==="iteration_end"&&W.hadToolCalls){this.recordProgressStep($,`Completed iteration ${W.iteration} with ${W.toolCallCount} tool call(s)`);return}if(W.type==="content_end"&&W.contentType==="tool"&&!W.error){this.recordProgressStep($,`Finished tool "${W.toolName??"unknown"}"`);return}if(W.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${W.iterations} iterations)`});return}if(W.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:W.error.message})}recordRunActivityFromAgentEvent($,W){let Z;switch(W.type){case"iteration_start":Z=`iteration_${W.iteration}_started`;break;case"content_start":if(W.contentType==="tool")Z=`running_tool_${W.toolName??"unknown"}`;break;case"content_end":if(W.contentType==="tool")Z=W.error?this.formatProgressErrorActivity(`tool_${W.toolName??"unknown"}_error`,W.error):`finished_tool_${W.toolName??"unknown"}`;break;case"done":Z="finalizing_response";break;case"error":Z=this.formatProgressErrorActivity("run_error",W.error.message);break;default:break}if(!Z)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,Z)}}recordRunProgress($,W){let Z=new Date;$.heartbeatAt=Z,$.lastProgressAt=Z,$.lastProgressMessage=W,$.currentActivity=W,this.emitEvent({type:g.RunProgress,run:{...$},message:W})}formatProgressErrorActivity($,W){let Z=W.replace(/\s+/g," ").trim();if(Z.length===0)return $;let Q=Z.length>240?`${Z.slice(0,237).trimEnd()}...`:Z;return`${$}: ${Q}`}recordProgressStep($,W,Z,Q=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let j=this.missionStepCounter-J.lastMissionStep,X=Date.now()-J.lastMissionAt;if(!Q&&j<this.missionLogIntervalSteps&&X<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Z,kind:"progress",summary:W})}buildMailboxNotification($){if($.length===0)return"";let W=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Z of $)W.push(`--- Message from ${Z.fromAgentId} | subject: ${Z.subject} ---`),W.push(Z.body);return W.push("---"),W.join(`
532
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function AU($){return new Promise((W)=>setTimeout(W,$))}function P6($,W){let Z=0;for(let Q of $){if(!Q.startsWith(W))continue;let J=Number.parseInt(Q.slice(W.length),10);if(Number.isFinite(J))Z=Math.max(Z,J)}return Z}function bj($,W){switch(W.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(W.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Z;if(W.type==="run_failed")Z=W.run.error;else if(W.type==="run_cancelled"||W.type==="run_interrupted")Z=W.run.error??W.reason;$.activeTeamRunIds.delete(W.run.id),$.pendingTeamRunUpdates.push({runId:W.run.id,agentId:W.run.agentId,taskId:W.run.taskId,status:W.type.replace("run_",""),error:Z,iterations:W.run.result?.iterations}),qQ($);break}default:break}}async function yj($,W,Z){switch(W.type){case"run_progress":await Z("onTeamTaskProgress",$,W.run.agentId,W.message,{kind:W.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(W.event.type==="content_start"&&W.event.contentType==="text"&&typeof W.event.text==="string"){let Q=W.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await Z("onTeamTaskProgress",$,W.agentId,Q,{kind:"text"})}break;case"task_start":await Z("onTeamTaskStart",$,W.agentId,W.message);break;case"task_end":{if(W.error)await Z("onTeamTaskEnd",$,W.agentId,"failed",`[error] ${W.error.message}`,void 0,W.messages);else if(W.result?.finishReason==="aborted")await Z("onTeamTaskEnd",$,W.agentId,"cancelled","[done] aborted",W.result,W.result.messages);else await Z("onTeamTaskEnd",$,W.agentId,"completed",`[done] ${W.result?.finishReason??"completed"}`,W.result,W.result?.messages);break}default:break}}function hj($,W,Z,Q){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:W,teamName:J,lifecycle:C6({teamName:J,sessionId:W,event:Z}),summary:w6(J,$.runtime.teamRuntime.exportState())}})}function BW($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function kj($,W){if($.aborting)return!1;if(!(W==="completed"||W==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&BW($)}function qQ($){let W=$.teamRunWaiters.splice(0);for(let Z of W)Z()}async function Ij($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let W=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,W}if($.activeTeamRunIds.size===0)return[];await new Promise((W)=>{$.teamRunWaiters.push(W)})}}function xj($,W){let Z=W.map((j)=>{let X=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)X.push(` task=${j.taskId}`);if(typeof j.iterations==="number")X.push(` iterations=${j.iterations}`);if(j.error)X.push(` error=${j.error}`);return X.join("")}),Q=$.activeTeamRunIds.size,J=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return HW(`System-delivered teammate async run updates:
533
533
  ${Z.join(`
534
534
  `)}
535
535
 
536
- ${J}`,$.config.mode)}function BW($,W){return Ib($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var gj=4;class V${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new Ej($,W.messagesArtifactUploader,W.logger),this.teamChildren=new TQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),V$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?$Z(W.messages,W,Z):e9($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${gb(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=o4({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:V.prompt??null,metadata:P$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await DG(()=>this.adapter.getSession($),async(j)=>{return Q=K0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:K0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},gj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<gj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?P$($.metadata)??{}:P$(Q)??{},j=w2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?w2($.title):j??I3($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?P$($.metadata)??{}:P$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=e9(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(K0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=V$.STALE_REASON;for(let Q=0;Q<gj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(K0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:V$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=UG(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,V$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=P$(j.metadata??void 0),V=w2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await QJ(J.cwd,J.sessionId),_5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),_5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await QJ(Z.cwd,W),_5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),_5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(xb(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function vj(){return new Date().toISOString()}function fU($,W){let Z=`${$}.tmp`;cb(Z,`${JSON.stringify(W,null,2)}
537
- `,"utf8"),vb(Z,$)}class LU{sessionsDirPath;constructor($=ub()){this.sessionsDirPath=$}ensureSessionsDir(){if(!mj(this.sessionsDirPath))mb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return _U(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return _U(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!mj($))return{version:1,sessions:{}};try{let W=JSON.parse(DU($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){fU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!mj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(DU($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){fU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:vj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:vj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=vj(),this.writeQueue(Z),Q.task}}class cj extends V${constructor($,W={}){super(new LU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var zU={};w(zU,{CoreSessionService:()=>y1});import{existsSync as db,mkdirSync as lb}from"node:fs";import{resolveSessionDataDir as pb}from"@cline/shared/storage";var uj=`
536
+ ${J}`,$.config.mode)}function HW($,W){return ub($,W==="plan"?"plan":W==="yolo"?"yolo":"act")}var gj=4;class B${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,W={}){this.adapter=$;this.manifestStore=new Ej($,W.messagesArtifactUploader,W.logger),this.teamChildren=new TQ($,this.manifestStore,(Z,Q,J)=>this.toPersistedMessages(Z,Q,J),B$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,W,Z){if(!$)return;return W?$Z(W.messages,W,Z):e9($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,W){this.manifestStore.writeSessionManifest($,W)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let W=$.startedAt??X0(),Z=$.sessionId.trim(),Q=Z.length>0?Z:`${Date.now()}_${lb(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(Q),j=this.manifestStore.artifacts.sessionCompactionPath(Q),X=this.manifestStore.artifacts.sessionManifestPath(Q),Y=s4({metadata:$.metadata,prompt:$.prompt}),V={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:W,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:Y,messages_path:J};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:W,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:V.prompt??null,metadata:S$(V.metadata),hookPath:"",messagesPath:J,updatedAt:X0()}),this.manifestStore.initializeMessagesFile(Q,J,W),this.manifestStore.writeSessionManifest(X,V),{manifestPath:X,messagesPath:J,compactionPath:j,manifest:V}}async updateSessionStatus($,W,Z){let Q;if((await _G(()=>this.adapter.getSession($),async(j)=>{return Q=G0(W)?void 0:X0(),this.adapter.updateSession({sessionId:$,status:W,endedAt:Q??null,exitCode:G0(W)?null:typeof Z==="number"?Z:null,expectedStatusLock:j.statusLock})},gj)).updated){if(W==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let W=0;W<gj;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return{updated:!1};let Q=Z.metadata??void 0,J=$.metadata!==void 0?S$($.metadata)??{}:S$(Q)??{},j=w2(typeof Q?.title==="string"?Q.title:void 0),X=$.title!==void 0?w2($.title):j??I3($.prompt);if(X)J.title=X;else delete J.title;let Y=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:Y?Object.keys(J).length>0?J:null:void 0,title:X,expectedStatusLock:Z.statusLock})).updated)continue;let{path:B,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let G=$.metadata!==void 0?S$($.metadata)??{}:S$(H.metadata)??{};if(X)G.title=X;H.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(B,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,W){return this.teamChildren.appendSubagentHookAudit(W),Promise.resolve()}persistSessionMessages($,W,Z){let Q=e9(W);return this.manifestStore.persistSessionMessages($,Q,Z)}async readSessionCompactionState($){return await this.manifestStore.readSessionCompactionState($)}async persistSessionCompactionState($,W){await this.manifestStore.persistSessionCompactionState($,W)}async deleteSessionCompactionState($){await this.manifestStore.deleteSessionCompactionState($)}applySubagentStatus($,W){return this.teamChildren.applySubagentStatus($,W)}applySubagentStatusBySessionId($,W){return this.teamChildren.applySubagentStatusBySessionId($,W)}applyStatusToRunningChildSessions($,W){return this.teamChildren.applyStatusToRunningChildSessions($,W)}onTeamTaskStart($,W,Z){return this.teamChildren.onTeamTaskStart($,W,Z)}onTeamTaskEnd($,W,Z,Q,J,j){return this.teamChildren.onTeamTaskEnd($,W,Z,Q,J,j)}onTeamTaskProgress($,W,Z,Q){return this.teamChildren.onTeamTaskProgress($,W,Z,Q)}handleSubAgentStart($,W){return this.teamChildren.handleSubAgentStart($,W)}handleSubAgentEnd($,W){return this.teamChildren.handleSubAgentEnd($,W)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(W){return typeof W==="object"&&W!==null&&"code"in W&&W.code==="EPERM"}}async reconcileDeadRunningSession($){if(G0($.status)===!1||this.isPidAlive($.pid))return $;let W=X0(),Z=B$.STALE_REASON;for(let Q=0;Q<gj;Q++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(G0(J.status)===!1)return J;let j={...J.metadata??{},terminal_marker:Z,terminal_marker_at:W,terminal_marker_pid:J.pid,terminal_marker_source:B$.STALE_SOURCE},X=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:W,exitCode:1,metadata:j,expectedStatusLock:J.statusLock});if(!X.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let Y=DG(J,{status:"failed",endedAt:W,exitCode:1,metadata:j}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,Y),this.manifestStore.appendStaleSessionHookLog(W,J.sessionId,J.pid,Z,B$.STALE_SOURCE),{...J,status:"failed",endedAt:W,exitCode:1,metadata:j,statusLock:X.statusLock,updatedAt:W}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let W=Math.max(1,Math.floor($)),Z=Math.min(W*5,2000);await this.reconcileDeadSessions(Z);let Q=(await this.adapter.listSessions({limit:Z})).slice(0,W),J=await Promise.all(Q.map((j)=>this.manifestStore.readSessionManifestTitle(j.sessionId)));return Q.map((j,X)=>{let Y=S$(j.metadata??void 0),V=w2(J[X]),B=V?{...Y??{},title:V}:Y;return{...j,metadata:B}})}async reconcileDeadSessions($=2000){let W=Math.max(1,Math.floor($)),Z=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:W,status:J})))).flat(),Q=0;for(let J of Z){let j=await this.reconcileDeadRunningSession(J);if(j&&j.status!==J.status)Q++}return Q}async deleteSession($){let W=$.trim();if(!W)throw Error("session id is required");let Z=await this.adapter.getSession(W);if(!Z)return{deleted:!1};if(await this.adapter.deleteSession(W,!1),!Z.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:W});await this.adapter.deleteSession(W,!0),await Promise.allSettled(Q.map(async(J)=>{await QJ(J.cwd,J.sessionId),f5(J.messagesPath),await this.deleteSessionCompactionStateIfExists(J.sessionId),f5(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await QJ(Z.cwd,W),f5(Z.messagesPath),await this.deleteSessionCompactionStateIfExists(W),f5(this.manifestStore.artifacts.sessionManifestPath(W,!1)),Z.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(W);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(W)]);for(let J of[Z.messagesPath])if(typeof J==="string"&&J.trim().length>0)Q.add(db(J));for(let J of Q)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}async deleteSessionCompactionStateIfExists($){try{await this.manifestStore.deleteSessionCompactionState($)}catch{}}}function vj(){return new Date().toISOString()}function LU($,W){let Z=`${$}.tmp`;ib(Z,`${JSON.stringify(W,null,2)}
537
+ `,"utf8"),rb(Z,$)}class OU{sessionsDirPath;constructor($=nb()){this.sessionsDirPath=$}ensureSessionsDir(){if(!mj(this.sessionsDirPath))pb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return fU(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return fU(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!mj($))return{version:1,sessions:{}};try{let W=JSON.parse(_U($,"utf8"));if(W?.version===1&&W.sessions)return W}catch{}return{version:1,sessions:{}}}writeIndex($){LU(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!mj($))return{version:1,nextId:1,requests:[]};try{let W=JSON.parse(_U($,"utf8"));if(W?.version===1&&typeof W.nextId==="number"&&Array.isArray(W.requests))return W}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){LU(this.spawnQueuePath(),$)}async upsertSession($){let W=this.readIndex();W.sessions[$.sessionId]=$,this.writeIndex(W)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((W)=>$.parentSessionId!==void 0?W.parentSessionId===$.parentSessionId:!0).filter((W)=>$.status!==void 0?W.status===$.status:!0).sort((W,Z)=>Z.startedAt.localeCompare(W.startedAt)).slice(0,$.limit)}async updateSession($){let W=this.readIndex(),Z=W.sessions[$.sessionId];if(!Z)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Z.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Z.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Z.statusLock,J={...Z,status:$.status??Z.status,endedAt:$.endedAt!==void 0?$.endedAt:Z.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Z.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Z.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Z.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Z.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Z.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Z.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Z.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Z.isSubagent,updatedAt:vj()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return W.sessions[$.sessionId]=J,this.writeIndex(W),{updated:!0,statusLock:J.statusLock}}async deleteSession($,W){let Z=this.readIndex();if(!Z.sessions[$])return!1;if(delete Z.sessions[$],W){for(let J of Object.values(Z.sessions))if(J.parentSessionId===$)delete Z.sessions[J.sessionId]}return this.writeIndex(Z),!0}async enqueueSpawnRequest($){let W=this.readQueue();W.requests.push({id:W.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:vj()}),W.nextId+=1,this.writeQueue(W)}async claimSpawnRequest($,W){let Z=this.readQueue(),Q=Z.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===W&&!J.consumedAt);if(!Q)return;return Q.consumedAt=vj(),this.writeQueue(Z),Q.task}}class cj extends B${constructor($,W={}){super(new OU($),W)}ensureSessionsDir(){return super.ensureSessionsDir()}}var qU={};w(qU,{CoreSessionService:()=>h1});import{existsSync as ab,mkdirSync as ob}from"node:fs";import{resolveSessionDataDir as sb}from"@cline/shared/storage";var uj=`
538
538
  session_id AS sessionId,
539
539
  source,
540
540
  pid,
@@ -561,7 +561,7 @@ ${J}`,$.config.mode)}function BW($,W){return Ib($,W==="plan"?"plan":W==="yolo"?"
561
561
  metadata_json AS metadata,
562
562
  hook_path AS hookPath,
563
563
  messages_path AS messagesPath,
564
- updated_at AS updatedAt`;function dj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function lj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function OU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class TU{store;sessionsDirPath;constructor($,W=pb()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!db(this.sessionsDirPath))lb(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
564
+ updated_at AS updatedAt`;function dj($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let W=$.metadata;if(typeof W==="string"&&W.trim())try{let Z=JSON.parse(W);$.metadata=Z&&typeof Z==="object"&&!Array.isArray(Z)?Z:null}catch{$.metadata=null}else $.metadata=null;return $}function lj($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function TU($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class zU{store;sessionsDirPath;constructor($,W=sb()){this.store=$;this.sessionsDirPath=W}ensureSessionsDir(){if(!ab(this.sessionsDirPath))ob(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
565
565
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
566
566
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
567
567
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -577,36 +577,36 @@ ${J}`,$.config.mode)}function BW($,W){return Ib($,W==="plan"?"plan":W==="yolo"?"
577
577
  WHERE session_id = ? AND status_lock = ?`,[X0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let W=[],Z=[];if($.status!==void 0)W.push("status = ?"),Z.push($.status);if($.endedAt!==void 0)W.push("ended_at = ?"),Z.push($.endedAt);if($.exitCode!==void 0)W.push("exit_code = ?"),Z.push($.exitCode);if($.prompt!==void 0)W.push("prompt = ?"),Z.push($.prompt??null);if($.metadata!==void 0)W.push("metadata_json = ?"),Z.push(lj($.metadata));if($.parentSessionId!==void 0)W.push("parent_session_id = ?"),Z.push($.parentSessionId??null);if($.parentAgentId!==void 0)W.push("parent_agent_id = ?"),Z.push($.parentAgentId??null);if($.agentId!==void 0)W.push("agent_id = ?"),Z.push($.agentId??null);if($.conversationId!==void 0)W.push("conversation_id = ?"),Z.push($.conversationId??null);if(W.length===0){let X=await this.getSession($.sessionId);return{updated:!!X,statusLock:X?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,W.push("status_lock = ?"),Z.push(Q);W.push("updated_at = ?"),Z.push(X0());let J=`UPDATE sessions SET ${W.join(", ")} WHERE session_id = ?`;if(Z.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Z.push($.expectedStatusLock);if((this.store.run(J,Z).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,W){let Z=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(W)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Z>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
578
578
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,X0()])}async claimSpawnRequest($,W){let Z=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
579
579
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
580
- ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class y1 extends V${store;constructor($,W={}){super(new TU($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
580
+ ORDER BY id ASC LIMIT 1`,[$,W]);if(!Z||typeof Z.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[X0(),Z.id]),Z.task??void 0}}class h1 extends B${store;constructor($,W={}){super(new zU($,W.sessionArtifactsDir),W);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
581
581
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
582
582
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
583
583
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
584
584
  metadata_json, transcript_path, hook_path, messages_path, updated_at
585
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,X0()])}}function rb($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var HW,GW;function ib($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;UQ(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function nb($){await $.reconcileDeadSessions?.().catch(()=>{})}function RU($){try{let W=new S1;return W.init(),new y1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),MU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new cj(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function qU($,W,Z){return new h1({sessionService:Z??$.sessionService??RU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function pj($){if(HW)return HW;if(GW)return await GW;return GW=(async()=>{return HW=RU($),await nb(HW),HW})().finally(()=>{GW=void 0}),await GW}async function S6($){let W=c0($.distinctId);$.telemetry?.setDistinctId(W);let Z=rb($);if(ib(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new q6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await s2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new X$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await WW({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new X$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),MU($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),qU($,W)}return qU($,W)}var CU={};w(CU,{NoOpFeatureFlagsProvider:()=>Z8,FeatureFlagsService:()=>W8});import{existsSync as ab,mkdirSync as ob,readFileSync as sb,writeFileSync as tb}from"node:fs";import{dirname as eb}from"node:path";import{FEATURE_FLAGS as EU,FeatureFlagDefaultValue as rj}from"@cline/shared";var $y=3600000,Wy=604800000,wU=1;class W8{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??$y,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Wy,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:EU.length>0?EU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!ab(this.cacheFilePath))return;let $=JSON.parse(sb(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==wU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;ob(eb(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:wU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};tb(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??rj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:v.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),rj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??rj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class Z8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}M6();var IU={};w(IU,{createCheckpointComparePlan:()=>RQ,compareCheckpointToWorkspace:()=>KW,buildCheckpointWorkspaceDiff:()=>NQ});import{execFile as Jy}from"node:child_process";import*as hU from"node:fs/promises";import*as h6 from"node:path";import{promisify as jy}from"node:util";var bU={};w(bU,{trimMessagesToCheckpoint:()=>SU,trimMessagesBeforeCheckpoint:()=>nj,readSessionCheckpointHistory:()=>Q8,findCheckpointForRun:()=>y6,createRestoredCheckpointMetadata:()=>ij,createCheckpointRestorePlan:()=>aj,applyCheckpointToWorktree:()=>oj});import{execFile as Zy}from"node:child_process";import{promisify as Qy}from"node:util";var b6=Qy(Zy);function Q8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function ij($,W){let Z=Q8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function y6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function PU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function SU($,W){let Z=PU($,W);return $.slice(0,Z+1)}function nj($,W){let Z=PU($,W);return $.slice(0,Z)}function aj($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=y6(Q8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:SU($.messages??[],W)}:{}}}async function oj($,W){if((await b6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await b6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await b6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await b6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await b6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await b6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var Xy=jy(Jy),Yy=52428800;async function MQ($,W){let{stdout:Z}=await Xy("git",["-C",$,...W],{windowsHide:!0,maxBuffer:Yy,encoding:"utf8"});return Z}function yU($){return $.split("\x00").filter(Boolean)}function kU($,W){let Z=h6.resolve($,W),Q=h6.relative($,Z);if(Q.startsWith("..")||h6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function Vy($,W,Z){try{return await MQ($,["show",`${W}:${Z}`])}catch{return""}}async function By($,W){try{return await hU.readFile(kU($,W),"utf8")}catch{return""}}async function Hy($,W){await MQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([MQ($,["diff","--name-only","-z",W.ref,"--"]),MQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...yU(Z),...yU(Q)])].sort((j,X)=>j.localeCompare(X))}function RQ($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=y6(Q8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function NQ($,W){let Z=await Hy($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([Vy($,W.ref,J),By($,J)]);return{filePath:kU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function KW($){let W=RQ($),Z=await NQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class FW{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=IF($),this.pendingPrompts=xF($),this.automation=new zJ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new o5({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:PK(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:SK({host:$,getExtensionContext:()=>mZ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=c0($.distinctId),Z=C0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await S6(Q),j=CK($.automation),X=$.featureFlags||new W8({provider:new Z8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new FW(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=mF($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(vJ(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>mZ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return vF({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await VQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?vJ($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>mZ({automationService:this.automationService,automation:this.automation,context:Z,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return KW({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var gU={};w(gU,{resolvePluginSkillDirectoriesFromPaths:()=>e1,resolvePluginConfigSearchPaths:()=>Q5,resolveAndLoadAgentPlugins:()=>o8,resolveAgentPluginPaths:()=>t1,loadAgentPluginsFromPathsWithDiagnostics:()=>P2,loadAgentPluginsFromPaths:()=>ZZ,loadAgentPluginFromPath:()=>W5,discoverPluginModulePaths:()=>J5});var cU={};w(cU,{toHookConfigFileName:()=>Y5,runSubprocessEvent:()=>k6,runHook:()=>x6,resolveHooksConfigSearchPaths:()=>j5,parseHookEventPayload:()=>I6,mergeAgentHooks:()=>h2,listHookConfigFiles:()=>b$,createSubprocessHooks:()=>CQ,createHookConfigFileHooks:()=>V5,createHookConfigFileExtension:()=>$6,createHookAuditHooks:()=>e8,createAgentHooksExtension:()=>s8,HookEventPayloadSchema:()=>wQ,HookEventNameSchema:()=>EQ,HookConfigFileName:()=>t8,HOOK_CONFIG_FILE_EVENT_MAP:()=>X5,HOOKS_CONFIG_DIRECTORY_NAME:()=>VZ});import{HookEventNameSchema as EQ,HookEventPayloadSchema as wQ,parseHookEventPayload as I6,resolveHookSessionContext as _y}from"@cline/shared";import{z as J8}from"zod";import{spawn as Gy}from"node:child_process";import{augmentNodeCommandForDebug as Ky,withResolvedClineBuildEnv as Fy}from"@cline/shared";function Ay($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function Uy($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${J}": ${Z.message}`)}async function Dy($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function k6($,W){let Z=Ky(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=Gy(Z[0],Z.slice(1),{cwd:W.cwd,env:Fy(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(Uy(A,Z))})});if(await Dy(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=Ay(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,X])}var fy=J8.object({contextModification:J8.string().optional(),cancel:J8.boolean().optional(),review:J8.boolean().optional(),errorMessage:J8.string().optional(),context:J8.string().optional(),overrideInput:J8.unknown().optional()}).passthrough();var Ly=["agent","hook"];async function x6($,W={}){let Z=W.command??Ly;return await k6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function vU($){return $ instanceof Error?$:Error(String($))}function Oy($){if(!$||typeof $!=="object")return;let W=fy.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function mU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function B$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:_y(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function Ty($){return{name:$.name,message:$.message,stack:$.stack}}function zy($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function qy($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function My($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function Ry($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function Ny($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function j8($,W){try{let Z=await x6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(vU(Z),$)}}function CQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=qy(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...B$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await j8(H,$)}else{let H={...B$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await j8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...B$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:mU(Y.input)}};try{let H=await x6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return Ny(Oy(H?.parsedJson))}catch(H){$.onDispatchError?.(vU(H),B);return}},afterTool:async(Y)=>{let V=Ry(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...B$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:mU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await j8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...B$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await j8(K,$);return}let H=V.status==="aborted"||zy(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...B$(H,B,$),hookName:H,iteration:V.iterations,error:Ty(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...B$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await j8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...B$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:My(Y.message.content),attachments:[]}};await j8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...B$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await j8(G,$)}}}var Z_={};w(Z_,{writeHubDiscovery:()=>GQ,withHubStartupLock:()=>KQ,verifyHubConnection:()=>w1,truncateNotificationBody:()=>fW,toHubStatusUrl:()=>Kj,toHubHealthUrl:()=>FQ,stopLocalHubServerGracefully:()=>Mj,startHubWebSocketServer:()=>V8,startHubServer:()=>$_,spawnDetachedHubServerWithRetry:()=>O6,spawnDetachedHubServer:()=>fj,sendHubCommand:()=>iU,restartLocalHubIfIdleAfterStartupTimeout:()=>fQ,resolveWorkspaceHubOwnerContext:()=>TA,resolveSharedHubOwnerContext:()=>v0,resolveProductionHubOwnerContext:()=>Q1,resolveHubUrl:()=>WX,resolveHubOwnerContext:()=>J$,resolveHubEndpointOptions:()=>Z1,resolveHubBuildId:()=>HQ,resolveDefaultHubPort:()=>L6,resolveDefaultHubPathname:()=>_j,resolveDefaultHubHost:()=>Dj,resolveCompatibleLocalHubUrl:()=>WW,resolveClineDir:()=>_A,resolveClineDataDir:()=>n2,requestHubShutdown:()=>$W,rememberRecoverableLocalHubUrl:()=>l$,readHubDiscovery:()=>O0,readBearerToken:()=>gQ,probeHubServer:()=>j$,probeHubConnection:()=>rU,prewarmDetachedHubServer:()=>UQ,normalizeHubWebSocketUrl:()=>p$,isLocalHubOrigin:()=>MX,isLocalHubHostName:()=>mQ,isHubReconnectableTransportError:()=>zj,isHubCommandTimeoutError:()=>_Q,isDiscoveryFilePresent:()=>LA,ensureHubWebSocketServer:()=>vQ,ensureHubServer:()=>W_,ensureDetachedHubServer:()=>EA,ensureCompatibleLocalHubUrl:()=>s2,createLocalHubScheduleRuntimeHandlers:()=>cQ,createInMemoryHubOwnerContext:()=>fA,createHubServerUrl:()=>_1,createHubAuthToken:()=>BQ,createConfiguredTelemetryService:()=>H$,createConfiguredTelemetryHandle:()=>n$,connectToHub:()=>bQ,clearHubDiscovery:()=>m0,NodeHubClient:()=>f1,NativeHubTransportAdapter:()=>qW,HubUIClient:()=>JX,HubTransportError:()=>y0,HubSessionClient:()=>QX,HubServerTransport:()=>d6,HubScheduleService:()=>m6,HubScheduleCommandService:()=>g6,HubCommandError:()=>T6,DEFAULT_HUB_PORT:()=>Aj,DEFAULT_HUB_PATHNAME:()=>Uj,DEFAULT_HUB_HOST:()=>Fj,BrowserWebSocketHubAdapter:()=>zW});import{createSessionId as Ey}from"@cline/shared";function J1($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function uU($,W,Z){return{version:$.version,requestId:$.requestId??Ey("hubreq_"),ok:!1,error:{code:W,message:Z}}}class g6{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return J1($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return J1($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return J1($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return J1($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return J1($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return J1($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return J1($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return J1($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return J1($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return J1($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return J1($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return J1($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return uU($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return uU($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}function SQ($){return $?new Date($).getTime():void 0}function wy($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function PQ($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:SQ($.nextRunAt),lastRunAt:SQ($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:wy($)}}function Cy($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function sj($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:SQ($.startedAt),endedAt:SQ($.completedAt),status:Cy($.status),errorMessage:$.error}}class m6{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a5({dbPath:$.dbPath}),this.materializer=new l5({store:this.store}),this.runner=new p5({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(aJ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return PQ(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?PQ(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>PQ(W))}updateSchedule($,W){if(W.cronPattern!==void 0)aJ(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?PQ(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 W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return sj(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),sj(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return sj(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}_W();import{resolveClineBuildEnv as ty}from"@cline/shared";function ey($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var $h="cline-hub-auth.";function Wh($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function Zh($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function pU(){return ty()==="production"?Q1():v0()}async function Qh($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=pU(),Q=await O0(Z.discoveryPath);if(Q?.url&&Zh($.toString(),Q.url))return Q.authToken;return}async function WX($={}){let W=Z1($);if(!Wh($)){let Z=pU(),Q=await O0(Z.discoveryPath);if(Q?.url)return Q.url}return _1(W.host,W.port,W.pathname)}async function bQ($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await Qh(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${$h}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(ey(V,$))})})().catch(Z)})}async function rU($){try{return(await bQ($)).close(),!0}catch{return!1}}async function iU($,W){let Z=await WX($),Q=await bQ(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function ZX($){return $?JSON.parse(JSON.stringify($)):{}}function yQ($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?ZX(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function nU($,W){return $.error?.message??`hub command failed: ${W}`}function Jh($){let W=ZX($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function aU($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function jh($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function Xh($){let W=ZX($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||aU(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||aU(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:Jh($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class QX{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new f1({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 W=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Z=yQ(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(Q$(Z))return;throw Z}return yQ(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(nU(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(nU(J,"session.restore"));let j=yQ(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=jh(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>yQ({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).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($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=Xh(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).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($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class JX{client;constructor($){this.client=new f1({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 W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{resolveClineBuildEnv as tD}from"@cline/shared";function Yh($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
588
- `).trim()||void 0}var oU=120,jX="...";function fW($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=oU)return W;let Z=oU-Buffer.byteLength(jX,"utf8");if(Z<=0)return jX;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${jX}`}async function sU($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await d$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?Yh(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:fW(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as xQ,createSessionId as Bk}from"@cline/shared";import{createSessionId as Gh}from"@cline/shared";import{createSessionId as Hh}from"@cline/shared";function Vh($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Bh($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function hQ($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:Vh($.status),participants:W?[...W.participants.values()]:[],metadata:Bh($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function u($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function u6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function S0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function X8($,W,Z){return{version:"v1",event:$,eventId:Hh("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function b0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return hQ(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function u0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return C1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function XX($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function tU($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function YX($,W){let Z=Gh("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function VX($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function BX($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function eU($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=VX($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),u(W,{approvalId:Z,approved:j})}import{createSessionId as Ah}from"@cline/shared";function Kh($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var $D={debug:10,info:20,warn:30,error:40,silent:50};function Fh(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function i($,W,Z={}){if($D[$]<$D[Fh()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,Kh(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function HX($,W){let Z=W instanceof Error?W.stack||W.message:String(W);i("error",$,{error:Z})}async function WD($,W,Z,Q,J,j){let X=Ah("capreq_"),Y=performance.now();return i("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(i(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),i("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function ZD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),u(W,{requestId:Z})}function a$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),i("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function QD($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return u(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function JD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return i(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),u(W,{requestId:Z,ok:Y})}import{createSessionId as Uh}from"@cline/shared";function jD($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||Uh("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),u(W,{clientId:Q})}function XD($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=u6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return u(W)}function YD($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return u(W)}function VD($,W){return u(W,{clients:[...$.clients.values()]})}D0();import{existsSync as GD,mkdirSync as Dh,readdirSync as _h,readFileSync as fh,rmSync as Lh,writeFileSync as Oh}from"node:fs";import{dirname as Th,join as BD}from"node:path";import{CONNECTOR_PLATFORMS as zh,connectorChannelsFromPlatforms as qh,listConnectorCatalog as KD,shouldIncludeConnectorField as Mh}from"@cline/shared";import{resolveConnectorDataDir as Rh,resolveConnectorSettingsPath as KX}from"@cline/shared/storage";var Nh=1,HD={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},Eh={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function o$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function LW($){return typeof $==="string"?$.trim():void 0}function FD($){if(!GD($))return;try{let W=JSON.parse(fh($,"utf8"));return o$(W)?W:void 0}catch{return}}function FX(){let $=FD(KX()),W=o$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!o$(J))continue;let j=LW(J.type),X=LW(J.configuredAt),Y=LW(J.updatedAt);if(!j||!X||!Y)continue;let V=kQ(J.values),B=o$(J.security)?{enabled:J.security.enabled===!0,values:kQ(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:Nh,connectors:Z}}function AD($){let W=KX();Dh(Th(W),{recursive:!0}),Oh(W,`${JSON.stringify($,null,2)}
589
- `,"utf8")}function kQ($){if(!o$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function wh($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Ch($){let W=BD(Rh(),$);if(!GD(W))return[];return _h(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>BD(W,Z))}function Ph($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function Sh($,W){let Z=FD(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!wh(Q))return;let j=Eh[$];if(!j)return;let X={};for(let Y of j.required){let V=HD[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=HD[Y](Z);if(V!==void 0)X[Y]=V}return{id:Ph($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function bh(){let $=[];for(let{name:W}of KD())for(let Z of Ch(W)){let Q=Sh(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function yh(){let $=FX();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function AX(){return{available:qh(),active:bh(),configured:yh()}}function hh($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function kh($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!Mh(J,Z))continue;hh(J,Z),Q[J.flag]=Z[J.flag]}return Q}function Ih($){if(!o$($))throw Error("connector.configure payload must be an object.");let W=LW($.channel);if(!W)throw Error("channel is required");let Z=zh.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(KD().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=kQ($.values),j=kh(Z,J),X=o$($.security)?$.security:{},Y=X.enabled===!0,V=kQ(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=FX(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},AD(B),AX()}function xh($){if(!o$($))throw Error("connector.delete_config payload must be an object.");let W=LW($.channel);if(!W)throw Error("channel is required");let Z=FX();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)AD(Z);else Lh(KX(),{force:!0});return AX()}function gh($){return $==="connector.configure"||$==="connector.delete_config"}function GX($,W,Z){if(!gh(W.command))return;_8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function UD($,W){try{if(W.command==="connector.channels")return u(W,AX());if(W.command==="connector.configure"){let Z=Ih(W.payload);return GX($,W,!0),u(W,Z)}if(W.command==="connector.delete_config"){let Z=xh(W.payload);return GX($,W,!0),u(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return GX($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var mh=30000;function vh($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function ch($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function uh($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,l2,Q)}function dh($){return $?$:void 0}function lh($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function ph($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);i("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},mh),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;i("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;i("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),i("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),BX($,(F)=>F.sessionId===Z.sessionId,K),a$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{i("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function DD($,W){let Z=S0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=lh(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await ph($,W,{sessionId:Z,prompt:J,mode:dh(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(Q$(H))return uh(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await u0($,Z),G=ch(V);if($.publish($.buildEvent(vh(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await u0($,Z);return u(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function _D($,W){let Z=S0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";BX($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){i("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{a$($,(J)=>J.sessionId===Z,Q)}return u(W,{applied:!0})}async function fD($,W){let Z=I6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),u(W,{applied:!0})}async function LD($,W){switch(W.type){case"chunk":return;case"agent_event":await rh($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await ih($,W);return;default:return}}async function rh($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function ih($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([b0($,W.payload.sessionId),u0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await sU(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as MD,parseRuntimeConfigExtensions as RD}from"@cline/shared";var OD={};w(OD,{SessionVersioningService:()=>s$,SessionVersioningError:()=>d0});class d0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function nh($){let W=$.sessionId.trim();if(!W)throw new d0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new d0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new d0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new d0("invalid_restore","checkpointRunCount must be a positive integer");return W}class s${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=nh({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new d0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new d0("session_messages_not_found",`No messages found for session ${Q}`);let X=aj({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??oj)(X.cwd,X.checkpoint);let Y=C1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=ij(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?nj(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new d0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??lG)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:C1({session:A,messages:B})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as Ie,HUB_COMPACTION_CAPABILITY as xe,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ge,HUB_HOOK_CAPABILITY_PREFIX as me,HUB_MISTAKE_LIMIT_CAPABILITY as ve,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ce,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ue,isHubToolExecutorName as ah}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as ne,HUB_COMPACTION_CAPABILITY as ae,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as oe,HUB_HOOK_CAPABILITY_PREFIX as se,HUB_MISTAKE_LIMIT_CAPABILITY as te,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ee,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $00}from"@cline/shared";var oh=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Y8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function sh($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=Y8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...Y8($.lifecycle)?{lifecycle:Y8($.lifecycle)}:{}}}function DX($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=sh(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!ah(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...Y8(J.config)?{config:Y8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...Y8(J.config)?{config:Y8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function zD($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W[R9];return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:W&&Object.keys(W).length>0?W:void 0}}function th($){return Object.hasOwn($,"update")?$.update:$}function OW($){return $.trim().replace(/^\/+/,"").toLowerCase()}function eh($){let W=($??[]).map(OW).filter(Boolean);return W.length>0?new Set(W):void 0}function $k($,W,Z){if(!Z)return!0;let Q=OW($),J=OW(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function UX($,W){let Z=eh(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>$k(Q.id,Q.name,Z))}function TD($,W){let Z=async(Q,J)=>{let j=OW(Q),Y=UX($,W).filter((K)=>K.id===j||OW(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
585
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,null,null,"running",0,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,null,null,null,null,0,$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"","",$.messagesPath,X0()])}}function tb($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let W=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(W==="local"||W==="hub"||W==="remote")return W;return"auto"}var GW,KW;function eb($,W){if($!=="auto"&&$!=="hub")return;if(W.hub?.endpoint?.trim())return;UQ(W.hub?.workspaceRoot?.trim()||W.hub?.cwd?.trim()||process.cwd())}async function $y($){await $.reconcileDeadSessions?.().catch(()=>{})}function NU($){try{let W=new b1;return W.init(),new h1(W,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(W){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),RU($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:W,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new cj(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function MU($,W,Z){return new k1({sessionService:Z??$.sessionService??NU($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:W,fetch:$.fetch})}async function pj($){if(GW)return GW;if(KW)return await KW;return KW=(async()=>{return GW=NU($),await $y(GW),GW})().finally(()=>{KW=void 0}),await KW}async function b6($){let W=d0($.distinctId);$.telemetry?.setDistinctId(W);let Z=tb($);if(eb(Z,$),Z==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new M6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Z==="hub"){let Q=$.hub?.endpoint?.trim(),J=Q||await s2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!J)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:J,explicitEndpoint:Q||void 0}),new Y$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Z==="auto"){let Q=await ZW({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let J=new Y$({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await J.connect(),J}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),RU($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),MU($,W)}return MU($,W)}var PU={};w(PU,{NoOpFeatureFlagsProvider:()=>Z8,FeatureFlagsService:()=>W8});import{existsSync as Wy,mkdirSync as Zy,readFileSync as Qy,writeFileSync as Jy}from"node:fs";import{dirname as jy}from"node:path";import{FEATURE_FLAGS as wU,FeatureFlagDefaultValue as rj}from"@cline/shared";var Xy=3600000,Yy=604800000,CU=1;class W8{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Xy,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Yy,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let W=$??this.context.userId??null,Z=Date.now();if(Z-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===W)return}let Q=this.cacheInfo;this.cacheInfo={updateTime:Z,userId:W||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:wU.length>0?wU:void 0,context:{...this.context,userId:W}});if(this.cacheInfo.userId!==W)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==W)return;throw this.cacheInfo=Q.updateTime?Q:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:J}),J}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((W)=>this.isFeatureFlagPayload(W));if(typeof $==="object")return Object.values($).every((W)=>this.isFeatureFlagPayload(W));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=Object.entries($).filter(([,Q])=>this.isFeatureFlagPayload(Q));if(W.length===0)return;let Z={};for(let[Q,J]of W)Z[Q]=J;return Z}readPersistentCache(){try{if(!this.cacheFilePath||!Wy(this.cacheFilePath))return;let $=JSON.parse(Qy(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let W=$;if(W.version!==CU||typeof W.updatedAt!=="number"||!Number.isFinite(W.updatedAt)||Date.now()-W.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:W.updatedAt,userId:W.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(W.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(W.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;Zy(jy(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),W={version:CU,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};Jy(this.cacheFilePath,`${JSON.stringify(W,null,2)}
586
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let W=new Map;for(let Z of this.getReturnedFlagKeys($)){let Q=this.getFeatureFlag(Z);W.set(Z,Q??!1)}this.cache=W}getFeatureFlag($){try{let W=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Z=this.cacheInfo.flagsPayload?.featureFlags?.[$],Q=W??Z??rj[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Q)this.telemetry?.capture({event:m.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Z}});return Q}catch(W){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:W}),rj[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??rj[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,W){if(process.env.IS_TEST==="true")this.cache.set($,W)}async dispose(){await this.provider.dispose()}}class Z8{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}R6();var xU={};w(xU,{createCheckpointComparePlan:()=>RQ,compareCheckpointToWorkspace:()=>FW,buildCheckpointWorkspaceDiff:()=>NQ});import{execFile as Hy}from"node:child_process";import*as kU from"node:fs/promises";import*as k6 from"node:path";import{promisify as Gy}from"node:util";var yU={};w(yU,{trimMessagesToCheckpoint:()=>bU,trimMessagesBeforeCheckpoint:()=>nj,readSessionCheckpointHistory:()=>Q8,findCheckpointForRun:()=>h6,createRestoredCheckpointMetadata:()=>ij,createCheckpointRestorePlan:()=>aj,applyCheckpointToWorktree:()=>oj});import{execFile as Vy}from"node:child_process";import{promisify as By}from"node:util";var y6=By(Vy);function Q8($){let W=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(W?.history)?W.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let J=String(Q.ref??"").trim(),j=Number(Q.createdAt??0),X=Number(Q.runCount??0);if(J.length===0||!Number.isFinite(j)||!Number.isInteger(X)||X<1)return[];let Y=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:J,createdAt:j,runCount:X,...Y?{kind:Y}:{}}]})}function ij($,W){let Z=Q8($).filter((J)=>J.runCount<=W),Q=Z.at(-1);return Q?{latest:Q,history:Z}:void 0}function h6($,W){return $.reduce((Z,Q)=>{if(Q.runCount>W)return Z;if(!Z||Q.runCount>Z.runCount)return Q;return Z},void 0)}function SU($,W){let Z=0;for(let Q=0;Q<$.length;Q+=1){let J=$[Q];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Z+=1,Z===W)return Q}throw Error(`Could not find user message for checkpoint run ${W}`)}function bU($,W){let Z=SU($,W);return $.slice(0,Z+1)}function nj($,W){let Z=SU($,W);return $.slice(0,Z)}function aj($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=h6(Q8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Z,cwd:Q,...$.restoreMessages!==!1?{messages:bU($.messages??[],W)}:{}}}async function oj($,W){if((await y6("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await y6("git",["-C",$,"cat-file","-e",`${W.ref}^{commit}`],{windowsHide:!0}),await y6("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await y6("git",["-C",$,"clean","-fd"],{windowsHide:!0}),W.kind==="commit"){await y6("git",["-C",$,"reset","--hard",W.ref],{windowsHide:!0});return}await y6("git",["-C",$,"stash","apply",W.ref],{windowsHide:!0})}var Ky=Gy(Hy),Fy=52428800;async function MQ($,W){let{stdout:Z}=await Ky("git",["-C",$,...W],{windowsHide:!0,maxBuffer:Fy,encoding:"utf8"});return Z}function hU($){return $.split("\x00").filter(Boolean)}function IU($,W){let Z=k6.resolve($,W),Q=k6.relative($,Z);if(Q.startsWith("..")||k6.isAbsolute(Q))throw Error(`Checkpoint diff path escapes workspace: ${W}`);return Z}async function Ay($,W,Z){try{return await MQ($,["show",`${W}:${Z}`])}catch{return""}}async function Uy($,W){try{return await kU.readFile(IU($,W),"utf8")}catch{return""}}async function Dy($,W){await MQ($,["cat-file","-e",`${W.ref}^{tree}`]);let[Z,Q]=await Promise.all([MQ($,["diff","--name-only","-z",W.ref,"--"]),MQ($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...hU(Z),...hU(Q)])].sort((j,X)=>j.localeCompare(X))}function RQ($){let W=$.checkpointRunCount;if(!Number.isInteger(W)||W<1)throw Error("checkpointRunCount must be a positive integer");let Z=h6(Q8($.session),W);if(!Z)throw Error(`No checkpoint found at or before run ${W} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Z,cwd:Q}}async function NQ($,W){let Z=await Dy($,W);return(await Promise.all(Z.map(async(J)=>{let[j,X]=await Promise.all([Ay($,W.ref,J),Uy($,J)]);return{filePath:IU($,J),leftContent:j,rightContent:X}}))).filter((J)=>J.leftContent!==J.rightContent)}async function FW($){let W=RQ($),Z=await NQ(W.cwd,W.checkpoint);return{...W,diffs:Z}}class AW{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,W,Z,Q,J,j,X,Y,V,B){this.clientName=W,this.runtimeAddress=Z,this.host=$,this.prepare=Q,this.capabilities=J,this.logger=j,this.telemetry=X,this.distinctId=Y,this.featureFlags=V,this.settings=xF($),this.pendingPrompts=gF($),this.automation=new zJ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=B?new s5({workspaceRoot:B.workspaceRoot??process.cwd(),specs:{cronSpecsDir:B.cronSpecsDir??B.cronDir,scope:SK(B.cronScope),workspaceRoot:B.workspaceRoot},runtimeHandlers:bK({host:$,getExtensionContext:()=>mZ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:B.dbPath,logger:B.logger,pollIntervalMs:B.pollIntervalMs,claimLeaseSeconds:B.claimLeaseSeconds,globalMaxConcurrency:B.globalMaxConcurrency,watcherDebounceMs:B.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let W=d0($.distinctId),Z=w0($.capabilities),Q={...$,capabilities:Z,distinctId:W},J=await b6(Q),j=PK($.automation),X=$.featureFlags||new W8({provider:new Z8,telemetry:$.telemetry,logger:$.logger,context:{distinctId:W,clientName:$.clientName}}),Y=new AW(J,$.clientName,J.runtimeAddress,$.prepare,Z,$.logger,$.telemetry,W,X,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await Y.automation.start();return Y}async disposeSessionBootstrap($){let W=this.activeSessionBootstraps.get($);if(!W)return;this.activeSessionBootstraps.delete($),await Promise.resolve(W.dispose?.())}async start($){let W=vF($),Z=await this.prepare?.(W);try{let Q=Z?await Z.applyToStartSessionInput(W):W,J=await this.host.startSession(vJ(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>mZ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Z)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Z);else await Promise.resolve(Z.dispose?.());return cF({input:Q,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(Q){throw await Promise.resolve(Z?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let W=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(W.map((Z)=>this.disposeSessionBootstrap(Z)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await VQ(this.host,$);list=async($=200,W={})=>await this.listHistory({...W,limit:$});delete=async($)=>{let W=await this.host.deleteSession($);if(W)await this.disposeSessionBootstrap($);return W};update=(...$)=>this.host.updateSession(...$);updateSessionCompactionState=(...$)=>this.host.updateSessionCompactionState(...$);readSessionCompactionState=(...$)=>this.host.readSessionCompactionState(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let W=$.start?vJ($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Z)=>mZ({automationService:this.automationService,automation:this.automation,context:Z,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:W})}async compareCheckpoint($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=await this.host.getSession(W);if(!Z)throw Error(`Session ${W} not found`);return FW({session:Z,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,W){return this.host.subscribe($,W)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()};updateSessionConnection=(...$)=>{return this.host.updateSessionConnection?.(...$)??Promise.resolve()}}var mU={};w(mU,{resolvePluginSkillDirectoriesFromPaths:()=>$$,resolvePluginConfigSearchPaths:()=>J5,resolveAndLoadAgentPlugins:()=>s8,resolveAgentPluginPaths:()=>e1,loadAgentPluginsFromPathsWithDiagnostics:()=>P2,loadAgentPluginsFromPaths:()=>ZZ,loadAgentPluginFromPath:()=>Z5,discoverPluginModulePaths:()=>j5});var uU={};w(uU,{toHookConfigFileName:()=>V5,runSubprocessEvent:()=>I6,runHook:()=>g6,resolveHooksConfigSearchPaths:()=>X5,parseHookEventPayload:()=>x6,mergeAgentHooks:()=>h2,listHookConfigFiles:()=>y$,createSubprocessHooks:()=>CQ,createHookConfigFileHooks:()=>B5,createHookConfigFileExtension:()=>W6,createHookAuditHooks:()=>$6,createAgentHooksExtension:()=>t8,HookEventPayloadSchema:()=>wQ,HookEventNameSchema:()=>EQ,HookConfigFileName:()=>e8,HOOK_CONFIG_FILE_EVENT_MAP:()=>Y5,HOOKS_CONFIG_DIRECTORY_NAME:()=>VZ});import{HookEventNameSchema as EQ,HookEventPayloadSchema as wQ,parseHookEventPayload as x6,resolveHookSessionContext as qy}from"@cline/shared";import{z as J8}from"zod";import{spawn as _y}from"node:child_process";import{augmentNodeCommandForDebug as fy,withResolvedClineBuildEnv as Ly}from"@cline/shared";function Oy($){let W=$.trim();if(!W)return{};let Q=W.split(`
587
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),J=Q.length>0?Q[Q.length-1]:W;try{return{parsedJson:JSON.parse(J)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function Ty($,W){let Z=$ instanceof Error?$:Error(String($)),Q=Z,J=W.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${J}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${J}": ${Z.message}`)}async function zy($,W){let Z=$.stdin;if(!Z)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,J)=>{let j=(X)=>{Z.off("error",j);let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X)};Z.once("error",j),Z.end(W,(X)=>{if(Z.off("error",j),X){let Y=X.code;if(Y==="EPIPE"||Y==="ERR_STREAM_DESTROYED"){Q();return}J(X);return}Q()})})}async function I6($,W){let Z=fy(W.command,{env:W.env,debugRole:"hook"});if(!Array.isArray(Z)||Z.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!W.detached,J=_y(Z[0],Z.slice(1),{cwd:W.cwd,env:Ly(W.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q,windowsHide:!0}),j=new Promise((K)=>{J.once("spawn",()=>{try{W.onSpawn?.({command:Z,pid:J.pid??void 0,detached:Q})}catch{}K()})}),X=new Promise((K,F)=>{J.once("error",(A)=>{F(Ty(A,Z))})});if(await zy(J,JSON.stringify($)),Q){await Promise.race([j,X]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let Y="",V="",B=!1,H;J.stdout.on("data",(K)=>{Y+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((W.timeoutMs??0)>0)H=setTimeout(()=>{B=!0,J.kill("SIGKILL")},W.timeoutMs);J.once("close",(F)=>{if(H)clearTimeout(H);let{parsedJson:A,parseError:D}=Oy(Y);K({exitCode:F,stdout:Y,stderr:V,parsedJson:A,parseError:D,timedOut:B})})});return await Promise.race([G,X])}var My=J8.object({contextModification:J8.string().optional(),cancel:J8.boolean().optional(),review:J8.boolean().optional(),errorMessage:J8.string().optional(),context:J8.string().optional(),overrideInput:J8.unknown().optional()}).passthrough();var Ry=["agent","hook"];async function g6($,W={}){let Z=W.command??Ry;return await I6($,{command:Z,cwd:W.cwd,env:W.env,detached:W.detached,timeoutMs:W.timeoutMs,onSpawn:W.onSpawn})}function cU($){return $ instanceof Error?$:Error(String($))}function Ny($){if(!$||typeof $!=="object")return;let W=My.safeParse($);if(!W.success)return;let Z=W.data;if(!(("cancel"in Z)||("review"in Z)||("context"in Z)||("contextModification"in Z)||("overrideInput"in Z)||("errorMessage"in Z)))return;let J=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"&&Z.errorMessage.length>0?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:J,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function vU($){if(!$||typeof $!=="object")return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q;else W[Z]=JSON.stringify(Q);return W}function H$($,W,Z){let Q=Z.env??process.env,J=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",j=Z.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:W.conversationId,sessionContext:qy(Z.sessionContext,{hookName:$,conversationId:W.conversationId,agentId:W.agentId,parentAgentId:W.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Z.workspaceInfo,userId:J,agent_id:W.agentId,parent_agent_id:W.parentAgentId}}function Ey($){return{name:$.name,message:$.message,stack:$.stack}}function wy($){let W=String($??"").toLowerCase();return W.includes("cancel")||W.includes("abort")||W.includes("interrupt")}function Cy($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function Py($){return $.filter((W)=>W.type==="text"&&typeof W.text==="string").map((W)=>W.text).join("")}function Sy($){return{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input,output:$.result.output,error:$.result.isError?String($.result.output):void 0,durationMs:$.durationMs,startedAt:$.startedAt,endedAt:$.endedAt}}function by($){if(!$)return;let W={};if($.cancel===!0)W.stop=!0;if($.overrideInput!==void 0)W.input=$.overrideInput;return Object.keys(W).length>0?W:void 0}async function j8($,W){try{let Z=await g6($,{command:W.command,cwd:W.cwd,env:W.env,detached:!0,onSpawn:W.onSpawn});W.onDispatch?.({payload:$,result:Z,detached:!0})}catch(Z){W.onDispatchError?.(cU(Z),$)}}function CQ($={}){return{hooks:{beforeRun:async(Y)=>{let V=Cy(Y);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...H$("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await j8(H,$)}else{let H={...H$("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await j8(H,$)}return},beforeTool:async(Y)=>{let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("tool_call",V,$),hookName:"tool_call",iteration:Y.snapshot.iteration,tool_call:{id:Y.toolCall.toolCallId,name:Y.toolCall.toolName,input:Y.input},preToolUse:{toolName:Y.toolCall.toolName,parameters:vU(Y.input)}};try{let H=await g6(B,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:B,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return by(Ny(H?.parsedJson))}catch(H){$.onDispatchError?.(cU(H),B);return}},afterTool:async(Y)=>{let V=Sy(Y),B={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},H={...H$("tool_result",B,$),hookName:"tool_result",iteration:Y.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:vU(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await j8(H,$);return},afterRun:async({snapshot:Y,result:V})=>{let B={agentId:Y.agentId,conversationId:Y.conversationId??Y.runId??Y.agentId,parentAgentId:Y.parentAgentId??null};if(V.status==="completed"){let K={...H$("agent_end",B,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await j8(K,$);return}let H=V.status==="aborted"||wy(V.error?.message)?"agent_abort":"agent_error",G=H==="agent_error"?{...H$(H,B,$),hookName:H,iteration:V.iterations,error:Ey(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...H$(H,B,$),hookName:H,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await j8(G,$)},onEvent:async(Y)=>{if(Y.type!=="message-added"||Y.message.role!=="user")return;let V={agentId:Y.snapshot.agentId,conversationId:Y.snapshot.conversationId??Y.snapshot.runId??Y.snapshot.agentId,parentAgentId:Y.snapshot.parentAgentId??null},B={...H$("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Py(Y.message.content),attachments:[]}};await j8(B,$)}},shutdown:async({agentId:Y,conversationId:V,parentAgentId:B,reason:H})=>{let G={...H$("session_shutdown",{agentId:Y,conversationId:V,parentAgentId:B},$),hookName:"session_shutdown",reason:H};await j8(G,$)}}}var Q_={};w(Q_,{writeHubDiscovery:()=>GQ,withHubStartupLock:()=>KQ,verifyHubConnection:()=>C1,truncateNotificationBody:()=>LW,toHubStatusUrl:()=>Kj,toHubHealthUrl:()=>FQ,stopLocalHubServerGracefully:()=>Mj,startHubWebSocketServer:()=>V8,startHubServer:()=>W_,spawnDetachedHubServerWithRetry:()=>T6,spawnDetachedHubServer:()=>fj,sendHubCommand:()=>nU,restartLocalHubIfIdleAfterStartupTimeout:()=>fQ,resolveWorkspaceHubOwnerContext:()=>zA,resolveSharedHubOwnerContext:()=>u0,resolveProductionHubOwnerContext:()=>X1,resolveHubUrl:()=>WX,resolveHubOwnerContext:()=>j$,resolveHubEndpointOptions:()=>j1,resolveHubBuildId:()=>HQ,resolveDefaultHubPort:()=>O6,resolveDefaultHubPathname:()=>_j,resolveDefaultHubHost:()=>Dj,resolveCompatibleLocalHubUrl:()=>ZW,resolveClineDir:()=>fA,resolveClineDataDir:()=>n2,requestHubShutdown:()=>WW,rememberRecoverableLocalHubUrl:()=>p$,readHubDiscovery:()=>L0,readBearerToken:()=>gQ,probeHubServer:()=>X$,probeHubConnection:()=>iU,prewarmDetachedHubServer:()=>UQ,normalizeHubWebSocketUrl:()=>r$,isLocalHubOrigin:()=>MX,isLocalHubHostName:()=>mQ,isHubReconnectableTransportError:()=>zj,isHubCommandTimeoutError:()=>_Q,isDiscoveryFilePresent:()=>OA,ensureHubWebSocketServer:()=>vQ,ensureHubServer:()=>Z_,ensureDetachedHubServer:()=>wA,ensureCompatibleLocalHubUrl:()=>s2,createLocalHubScheduleRuntimeHandlers:()=>cQ,createInMemoryHubOwnerContext:()=>LA,createHubServerUrl:()=>L1,createHubAuthToken:()=>BQ,createConfiguredTelemetryService:()=>G$,createConfiguredTelemetryHandle:()=>a$,connectToHub:()=>bQ,clearHubDiscovery:()=>c0,NodeHubClient:()=>O1,NativeHubTransportAdapter:()=>MW,HubUIClient:()=>JX,HubTransportError:()=>k0,HubSessionClient:()=>QX,HubServerTransport:()=>l6,HubScheduleService:()=>v6,HubScheduleCommandService:()=>m6,HubCommandError:()=>z6,DEFAULT_HUB_PORT:()=>Aj,DEFAULT_HUB_PATHNAME:()=>Uj,DEFAULT_HUB_HOST:()=>Fj,BrowserWebSocketHubAdapter:()=>qW});import{createSessionId as yy}from"@cline/shared";function Y1($,W){return{version:$.version,requestId:$.requestId,ok:!0,payload:W}}function dU($,W,Z){return{version:$.version,requestId:$.requestId??yy("hubreq_"),ok:!1,error:{code:W,message:Z}}}class m6{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return Y1($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return Y1($,{schedules:this.schedules.listSchedules({enabled:typeof $.payload?.enabled==="boolean"?$.payload.enabled:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0,tags:Array.isArray($.payload?.tags)?$.payload?.tags:void 0})});case"schedule.get":return Y1($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return Y1($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return Y1($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return Y1($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return Y1($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return Y1($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return Y1($,{executions:this.schedules.listScheduleExecutions({scheduleId:typeof $.payload?.scheduleId==="string"?$.payload.scheduleId:void 0,status:typeof $.payload?.status==="string"?$.payload.status:void 0,limit:typeof $.payload?.limit==="number"?$.payload.limit:void 0})});case"schedule.stats":return Y1($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return Y1($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return Y1($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return dU($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(W){return dU($,"schedule_command_failed",W instanceof Error?W.message:String(W))}}toCreateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:W}}toUpdateInput($){let W=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:W}}}function SQ($){return $?new Date($).getTime():void 0}function hy($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W.__hubScheduleCreatedBy,delete W.__hubScheduleCwd,delete W.__hubRuntimeOptions;return W}function PQ($){let W=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof W?.__hubScheduleCwd==="string"?W.__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:SQ($.nextRunAt),lastRunAt:SQ($.lastRunAt),createdBy:typeof W?.__hubScheduleCreatedBy==="string"?W.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:W?.__hubRuntimeOptions&&typeof W.__hubRuntimeOptions==="object"&&!Array.isArray(W.__hubRuntimeOptions)?W.__hubRuntimeOptions:void 0,metadata:hy($)}}function ky($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function sj($,W){return{executionId:$.runId,scheduleId:W,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:SQ($.startedAt),endedAt:SQ($.completedAt),status:ky($.status),errorMessage:$.error}}class v6{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new o5({dbPath:$.dbPath}),this.materializer=new p5({store:this.store}),this.runner=new r5({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(aJ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return PQ(this.store.createHubSchedule($))}getSchedule($){let W=this.store.getHubSchedule($);return W?PQ(W):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((W)=>PQ(W))}updateSchedule($,W){if(W.cronPattern!==void 0)aJ(W.cronPattern);let Z=this.store.getHubSchedule($);if(!Z)return;let Q=W.workspaceRoot!==void 0?W.workspaceRoot.trim():Z.workspaceRoot;if((W.enabled??Z.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...W,scheduleId:$});return j?PQ(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 W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;await this.runner.tick();let Z=this.store.getRun(W.runId)??W;return sj(Z,$)}triggerScheduleNowDetached($){let W=this.store.enqueueHubScheduleRun($,"manual");if(!W)return;return this.runner.tick().catch(()=>{return}),sj(W,$)}listScheduleExecutions($){let W=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Z={specId:W?.specId,limit:$.limit};return this.store.listRuns(Z).map((J)=>{let j=W??this.store.getSpec(J.specId);if(!j||j.source!=="hub-schedule")return;return sj(J,j.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let W=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(W.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Z=0,Q=0,J=0,j;for(let X of W){if(X.status==="success"||X.status==="completed")Z+=1;if(!j&&X.status!=="success"&&X.status!=="completed")j=X;if(X.startedAt&&X.endedAt)J+=X.endedAt-X.startedAt,Q+=1}return{totalRuns:W.length,successRate:Z/W.length,avgDurationSeconds:Q>0?J/Q/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let W=this.store.getSpec($.specId);if(!W||W.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:W.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:W.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+W.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let W={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(W).flatMap((Z)=>Z.source==="hub-schedule"&&Z.nextRunAt?[{spec:Z,nextRunAt:Z.nextRunAt}]:[]).sort((Z,Q)=>String(Z.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:Z,nextRunAt:Q})=>({scheduleId:Z.externalId,name:Z.title,nextRunAt:Q}))}}fW();import{resolveClineBuildEnv as Jh}from"@cline/shared";function jh($,W){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Z?`Failed to connect to hub at ${W} (${Z} event before socket open).`:`Failed to connect to hub at ${W}.`)}var Xh="cline-hub-auth.";function Yh($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function Vh($,W){let Z=new URL($),Q=new URL(W);return Z.search="",Z.hash="",Q.search="",Q.hash="",Z.toString()===Q.toString()}function rU(){return Jh()==="production"?X1():u0()}async function Bh($){let W=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),W)return W;let Z=rU(),Q=await L0(Z.discoveryPath);if(Q?.url&&Vh($.toString(),Q.url))return Q.authToken;return}async function WX($={}){let W=j1($);if(!Yh($)){let Z=rU(),Q=await L0(Z.discoveryPath);if(Q?.url)return Q.url}return L1(W.host,W.port,W.pathname)}async function bQ($){return await new Promise((W,Z)=>{(async()=>{let Q=new URL($),J=await Bh(Q);Q.hash="";let j=new WebSocket(Q.toString(),J?[`${Xh}${J}`]:void 0),X=new Map,Y=0;j.addEventListener("open",()=>{W({send(V){let B=V.requestId??`hub-client-${++Y}`;return new Promise((H,G)=>{X.set(B,{resolve:H,reject:G});let K={kind:"command",envelope:{...V,requestId:B}};j.send(JSON.stringify(K))})},close(){j.close()}})}),j.addEventListener("message",(V)=>{let B=JSON.parse(String(V.data));if(B.kind==="reply"&&B.envelope.requestId){let H=X.get(B.envelope.requestId);if(H)X.delete(B.envelope.requestId),H.resolve(B.envelope)}}),j.addEventListener("close",()=>{for(let V of X.values())V.reject(Error("Hub connection closed"));X.clear()}),j.addEventListener("error",(V)=>{Z(jh(V,$))})})().catch(Z)})}async function iU($){try{return(await bQ($)).close(),!0}catch{return!1}}async function nU($,W){let Z=await WX($),Q=await bQ(Z);try{return await Q.send({version:W.version??"v1",clientId:W.clientId??"hub-client",...W})}finally{Q.close()}}function ZX($){return $?JSON.parse(JSON.stringify($)):{}}function yQ($){let W=$?.session&&typeof $.session==="object"?$.session:void 0;if(!W)return;let Z=W.metadata&&typeof W.metadata==="object"?ZX(W.metadata):void 0;return{sessionId:typeof W.sessionId==="string"?W.sessionId:"",parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,metadata:Z}}function aU($,W){return $.error?.message??`hub command failed: ${W}`}function Hh($){let W=ZX($);if(typeof W.error==="string"&&W.error.trim())return{...W,error:W.error.trim()};let Z=W.result&&typeof W.result==="object"?W.result:void 0;if(typeof Z?.text==="string"&&Z.text.trim())return{...W,error:Z.text.trim()};let Q=Z?.error&&typeof Z.error==="object"?Z.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...W,error:Q.message.trim()};return W}function oU($){let W=$?.sessionId;return typeof W==="string"&&W.trim()?W.trim():void 0}function Gh($){let W=$?.checkpoint;if(!W||typeof W!=="object"||Array.isArray(W))throw Error("hub checkpoint restore returned no checkpoint");let Z=W;if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Z}function Kh($){let W=ZX($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||oU(W)||"",eventType:"schedule.execution.completed",payload:W};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||oU(W)||"",eventType:"schedule.execution.failed",payload:W};let Z=$.sessionId?.trim();if(!Z)return;switch($.event){case"iteration.started":return{sessionId:Z,eventType:"runtime.chat.iteration_start",payload:W};case"iteration.finished":return{sessionId:Z,eventType:"runtime.chat.iteration_end",payload:W};case"assistant.delta":return{sessionId:Z,eventType:"runtime.chat.text_delta",payload:W};case"usage.updated":return{sessionId:Z,eventType:"runtime.chat.usage",payload:W};case"session.notice":return{sessionId:Z,eventType:"runtime.chat.notice",payload:W};case"tool.started":return{sessionId:Z,eventType:"runtime.chat.tool_call_start",payload:W};case"tool.finished":return{sessionId:Z,eventType:"runtime.chat.tool_call_end",payload:W};case"approval.requested":return{sessionId:Z,eventType:"approval.requested",payload:W};case"run.aborted":return{sessionId:Z,eventType:"runtime.chat.aborted",payload:W};case"run.failed":return{sessionId:Z,eventType:"runtime.chat.failed",payload:Hh($.payload)};case"run.completed":return{sessionId:Z,eventType:"runtime.chat.completed",payload:W};default:return}}class QX{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new O1({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 W=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Z=yQ(W.payload);if(!Z?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:"",messagesPath:Z.messagesPath??""}}}async sendRuntimeSession($,W,Z){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:W.prompt,mode:W.config.mode,attachments:W.attachments,delivery:W.delivery,timeoutSeconds:W.config.timeoutSeconds},$,Z)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let W;try{W=await this.client.command("session.get",void 0,$)}catch(Z){if(J$(Z))return;throw Z}return yQ(W.payload)}async readMessages($){let W=$.trim();if(!W)return[];await this.ensureMetadataApplied();let Z=await this.client.command("session.messages",{sessionId:W},W);if(!Z.ok)throw Error(aU(Z,"session.messages"));let Q=Z.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let W=$.sessionId.trim();if(!W)throw Error("sessionId is required");let Z=$.restore?.messages!==!1;if(Z&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,J=await this.client.command("session.restore",{sessionId:W,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},W);if(!J.ok)throw Error(aU(J,"session.restore"));let j=yQ(J.payload);if(Z&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let X=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,Y=Gh(J.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...X?{messages:X}:{},checkpoint:Y}}async listSessions($){await this.ensureMetadataApplied();let W=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(W.payload?.sessions)?W.payload?.sessions:[]).map((Q)=>yQ({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,W=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:W})).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($,W){let Z=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),Q=this.client.subscribe((J)=>{let j=Kh(J);if(!j)return;if(Z.size>0&&!Z.has(j.sessionId))return;W.onEvent?.(j)});return this.ensureMetadataApplied().catch((J)=>{W.onError?.(J instanceof Error?J:Error(String(J)))}),Q}streamTeamProgress($,W){let Z=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;W.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{W.onError?.(Q instanceof Error?Q:Error(String(Q)))}),Z}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.list");return Array.isArray(W.payload?.schedules)?W.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,W){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...W})).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($,W){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list_executions",{scheduleId:$,limit:W});return Array.isArray(Z.payload?.executions)?Z.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let W=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(W.payload?.upcoming)?W.payload?.upcoming:[]}}class JX{client;constructor($){this.client=new O1({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 W=await this.client.command("session.list",{limit:$});return Array.isArray(W.payload?.sessions)?W.payload.sessions:[]}subscribeUI($){return this.client.subscribe((W)=>{switch(W.event){case"ui.notify":$.onNotify?.(W.payload);break;case"ui.show_window":$.onShowWindow?.(W.payload);break;case"hub.client.registered":$.onClientRegistered?.(W.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(W.payload??{});break;case"session.created":$.onSessionCreated?.(W.payload??{});break;case"session.updated":$.onSessionUpdated?.(W.payload??{});break;case"session.detached":$.onSessionDetached?.(W.payload??{});break}})}}import{resolveClineBuildEnv as eD}from"@cline/shared";function Fh($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Z)=>{if(Z&&typeof Z==="object"&&"type"in Z&&Z.type==="text"&&"text"in Z&&typeof Z.text==="string")return Z.text.trim();return""}).filter(Boolean).join(`
588
+ `).trim()||void 0}var sU=120,jX="...";function LW($){let W=$.trim();if(!W)return"";if(Buffer.byteLength(W,"utf8")<=sU)return W;let Z=sU-Buffer.byteLength(jX,"utf8");if(Z<=0)return jX;let Q="";for(let J of W){if(Buffer.byteLength(Q+J,"utf8")>Z)break;Q+=J}return`${Q}${jX}`}async function tU($){let W=$?.sessionId?.trim()||"unknown",Z=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await l$(Z)].reverse().find((V)=>V.role==="assistant"),j=J?Fh(J.content):void 0,X=$?.workspaceRoot?.trim()||"workspace",Y=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():X;return{title:`Task completed (${W})`,body:LW(j&&j.length>0?j:Y.length>0?Y:X),severity:"info"}}import{captureSdkError as xQ,createSessionId as Uk}from"@cline/shared";import{createSessionId as _h}from"@cline/shared";import{createSessionId as Dh}from"@cline/shared";function Ah($){switch($){case"idle":return"idle";case"pending":return"pending";case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Uh($){let W=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())W.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())W.parentAgentId=$.parentAgentId;if($.agentId?.trim())W.agentId=$.agentId;if($.conversationId?.trim())W.conversationId=$.conversationId;if($.messagesPath?.trim())W.messagesPath=$.messagesPath;if($.prompt?.trim())W.prompt=$.prompt;if($.provider?.trim())W.provider=$.provider;if($.model?.trim())W.model=$.model;if($.source?.trim())W.source=$.source;if(typeof $.pid==="number")W.pid=$.pid;return Object.keys(W).length>0?W:void 0}function hQ($,W,Z,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:W?.createdByClientId??"hub",status:Ah($.status),participants:W?[...W.participants.values()]:[],metadata:Uh($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Z?{usage:{...Z}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function d($,W){return{version:$.version,requestId:$.requestId,ok:!0,...W!==void 0?{payload:W}:{}}}function h($,W,Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:W,message:Z}}}function d6($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function P0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function X8($,W,Z){return{version:"v1",event:$,eventId:Dh("hevt_"),sessionId:Z,timestamp:Date.now(),payload:W}}async function b0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let Q=await $.sessionHost.getAccumulatedUsage?.(W);return hQ(Z,$.sessionState.get(W),Q?.usage,Q?.aggregateUsage)}async function l0($,W){let Z=await $.sessionHost.getSession(W);if(!Z)return;let[Q,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(W):[],$.sessionHost.getAccumulatedUsage?.(W)]);return P1({session:Z,messages:Q,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function XX($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(Q==="creator"&&!j.createdByClientId)j.createdByClientId=Z;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={createdByClientId:Z,interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}function eU($,W,Z,Q,J={}){let j=$.sessionState.get(W);if(j){if(J.interactive!==void 0)j.interactive=J.interactive;if(!j.participants.has(Z))j.participants.set(Z,{clientId:Z,attachedAt:Date.now(),role:Q});return j}let X={interactive:J.interactive??!0,participants:new Map([[Z,{clientId:Z,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(W,X),X}async function YX($,W){let Z=_h("approval_"),Q=W.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Z,{sessionId:Q,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Z,sessionId:W.sessionId,agentId:W.agentId,conversationId:W.conversationId,iteration:W.iteration,toolCallId:W.toolCallId,toolName:W.toolName,inputJson:JSON.stringify(W.input??null),policy:W.policy},Q))})}function VX($,W,Z){let Q=$.pendingApprovals.get(W);if(!Q)return;return $.pendingApprovals.delete(W),Q.resolve(Z),{sessionId:Q.sessionId}}function BX($,W,Z){let Q=0;for(let[J,j]of[...$.pendingApprovals.entries()]){if(!W({approvalId:J,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(J),j.resolve({approved:!1,reason:Z}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Z},j.sessionId)),Q+=1}return Q}async function $D($,W){let Z=typeof W.payload?.approvalId==="string"?W.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Z))return h(W,"approval_not_found",`Unknown approval: ${Z}`);let J=typeof W.payload?.reason==="string"?W.payload.reason:W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)&&typeof W.payload.payload.reason==="string"?W.payload.payload.reason:void 0,j=W.payload?.approved===!0,X=VX($,Z,{approved:j,reason:J});if(!X)return h(W,"approval_not_found",`Unknown approval: ${Z}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:j,reason:J},X.sessionId)),d(W,{approvalId:Z,approved:j})}import{createSessionId as Oh}from"@cline/shared";function fh($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var WD={debug:10,info:20,warn:30,error:40,silent:50};function Lh(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function n($,W,Z={}){if(WD[$]<WD[Lh()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:W,...Object.fromEntries(Object.entries(Z).map(([J,j])=>[J,fh(j)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function HX($,W){let Z=W instanceof Error?W.stack||W.message:String(W);n("error",$,{error:Z})}async function ZD($,W,Z,Q,J,j){let X=Oh("capreq_"),Y=performance.now();return n("info","capability.request.start",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J}),await new Promise((V,B)=>{$.pendingCapabilityRequests.set(X,{sessionId:W,targetClientId:J,capabilityName:Z,onProgress:j,resolve:(H)=>{if(n(H.ok?"info":"warn","capability.request.end",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-Y)}),!H.ok){B(Error(H.error||`Capability ${Z} was rejected by ${J}.`));return}V(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:X,targetClientId:J,capabilityName:Z,payload:Q},W)),n("info","capability.request.published",{requestId:X,sessionId:W,capabilityName:Z,targetClientId:J})})}function QD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);if((W.clientId?.trim()||"")!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{};return Q.onProgress?.(j),d(W,{requestId:Z})}function o$($,W,Z){let Q=0;for(let[J,j]of[...$.pendingCapabilityRequests.entries()]){if(!W({requestId:J,...j}))continue;$.pendingCapabilityRequests.delete(J),n("warn","capability.request.cancelled",{requestId:J,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Z}),j.resolve({ok:!1,error:Z}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Z},j.sessionId)),Q+=1}return Q}async function JD($,W){let Z=typeof W.payload?.sessionId==="string"?W.payload.sessionId.trim():W.sessionId?.trim()||"",Q=typeof W.payload?.capabilityName==="string"?W.payload.capabilityName.trim():"",J=typeof W.payload?.targetClientId==="string"?W.payload.targetClientId.trim():"";if(!Z||!Q||!J)return h(W,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:{},X=await $.requestCapability(Z,Q,j,J);return d(W,X)}catch(j){return h(W,"capability_request_failed",j instanceof Error?j.message:String(j))}}function jD($,W){let Z=typeof W.payload?.requestId==="string"?W.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(Z);if(!Q)return h(W,"capability_not_found",`Unknown capability request: ${Z}`);let J=W.clientId?.trim()||"";if(J!==Q.targetClientId)return h(W,"capability_wrong_client",`Capability request ${Z} is owned by ${Q.targetClientId}`);if(W.sessionId?.trim()&&W.sessionId.trim()!==Q.sessionId)return h(W,"capability_wrong_session",`Capability request ${Z} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(Z);let j=W.payload?.payload&&typeof W.payload.payload==="object"&&!Array.isArray(W.payload.payload)?W.payload.payload:void 0,X=typeof W.payload?.error==="string"?W.payload.error:void 0,Y=W.payload?.ok===!0;return n(Y?"info":"warn","capability.respond",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,error:X}),Q.resolve({ok:Y,payload:j,error:X}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:J,ok:Y,payload:j,error:X},Q.sessionId)),d(W,{requestId:Z,ok:Y})}import{createSessionId as Th}from"@cline/shared";function XD($,W){let Z=W.payload,Q=Z?.clientId?.trim()||W.clientId?.trim()||Th("client_");return $.clients.set(Q,{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,actorKind:Z?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Z?.transport??"native",capabilities:Z?.capabilities??[],metadata:Z?.metadata,workspaceContext:Z?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:Z?.clientType??"unknown",displayName:Z?.displayName,connectedAt:Date.now()})),d(W,{clientId:Q})}function YD($,W){let Z=W.clientId?.trim(),Q=Z?$.clients.get(Z):void 0;if(!Z||!Q)return h(W,"client_not_found","Client is not registered with this hub.");let J=d6(W.payload?.metadata);if(Q.lastSeenAt=Date.now(),J)Q.metadata=JSON.parse(JSON.stringify(J));return d(W)}function VD($,W,Z){let Q=W.clientId?.trim();if(Q)$.clients.delete(Q),Z(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return d(W)}function BD($,W){return d(W,{clients:[...$.clients.values()]})}U0();import{existsSync as KD,mkdirSync as zh,readdirSync as qh,readFileSync as Mh,rmSync as Rh,writeFileSync as Nh}from"node:fs";import{dirname as Eh,join as HD}from"node:path";import{CONNECTOR_PLATFORMS as wh,connectorChannelsFromPlatforms as Ch,listConnectorCatalog as FD,shouldIncludeConnectorField as Ph}from"@cline/shared";import{resolveConnectorDataDir as Sh,resolveConnectorSettingsPath as KX}from"@cline/shared/storage";var bh=1,GD={startedAt:($)=>typeof $.startedAt==="string"?$.startedAt:void 0,port:($)=>typeof $.port==="number"?$.port:void 0,baseUrl:($)=>typeof $.baseUrl==="string"?$.baseUrl:void 0,connectionMode:($)=>typeof $.connectionMode==="string"?$.connectionMode:void 0,userName:($)=>typeof $.userName==="string"?$.userName:void 0,botUsername:($)=>typeof $.botUsername==="string"?$.botUsername:void 0,applicationId:($)=>typeof $.applicationId==="string"?$.applicationId:void 0,phoneNumberId:($)=>typeof $.phoneNumberId==="string"?$.phoneNumberId:void 0},yh={discord:{required:["userName","applicationId"],optional:["startedAt","port","baseUrl"]},telegram:{required:["botUsername"],optional:["startedAt"]},gchat:{required:["userName"],optional:["startedAt","port","baseUrl"]},linear:{required:["userName"],optional:["startedAt","port","baseUrl"]},slack:{required:["userName"],optional:["startedAt","connectionMode","port","baseUrl"]},whatsapp:{required:["userName"],optional:["startedAt","phoneNumberId","port","baseUrl"]}};function s$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function OW($){return typeof $==="string"?$.trim():void 0}function AD($){if(!KD($))return;try{let W=JSON.parse(Mh($,"utf8"));return s$(W)?W:void 0}catch{return}}function FX(){let $=AD(KX()),W=s$($?.connectors)?$.connectors:{},Z={};for(let[Q,J]of Object.entries(W)){if(!s$(J))continue;let j=OW(J.type),X=OW(J.configuredAt),Y=OW(J.updatedAt);if(!j||!X||!Y)continue;let V=kQ(J.values),B=s$(J.security)?{enabled:J.security.enabled===!0,values:kQ(J.security.values)}:void 0;Z[Q]={type:j,values:V,security:B,configuredAt:X,updatedAt:Y}}return{version:bh,connectors:Z}}function UD($){let W=KX();zh(Eh(W),{recursive:!0}),Nh(W,`${JSON.stringify($,null,2)}
589
+ `,"utf8")}function kQ($){if(!s$($))return{};let W={};for(let[Z,Q]of Object.entries($))if(typeof Q==="string")W[Z]=Q.trim();return W}function hh($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function kh($){let W=HD(Sh(),$);if(!KD(W))return[];return qh(W).filter((Z)=>Z.endsWith(".json")&&!Z.endsWith(".threads.json")).map((Z)=>HD(W,Z))}function Ih($,W,Z){let Q=W.botUsername??W.userName??W.applicationId??W.phoneNumberId??String(Z);return`${$}:${Q}`}function xh($,W){let Z=AD(W);if(!Z)return;let Q=typeof Z.pid==="number"?Z.pid:void 0,J=typeof Z.hubUrl==="string"?Z.hubUrl:typeof Z.rpcAddress==="string"?Z.rpcAddress:void 0;if(!Q||!J||!hh(Q))return;let j=yh[$];if(!j)return;let X={};for(let Y of j.required){let V=GD[Y](Z);if(!V||typeof V==="string"&&!V.trim())return;X[Y]=V}for(let Y of j.optional){let V=GD[Y](Z);if(V!==void 0)X[Y]=V}return{id:Ih($,X,Q),type:$,pid:Q,hubUrl:J,...X}}function gh(){let $=[];for(let{name:W}of FD())for(let Z of kh(W)){let Q=xh(W,Z);if(Q)$.push(Q)}return $.sort((W,Z)=>{if(W.type!==Z.type)return W.type.localeCompare(Z.type);let Q=W.botUsername??W.userName??"",J=Z.botUsername??Z.userName??"";return Q.localeCompare(J)})}function mh(){let $=FX();return Object.entries($.connectors).map(([W,Z])=>({id:W,type:Z.type,configuredAt:Z.configuredAt,updatedAt:Z.updatedAt})).sort((W,Z)=>W.type.localeCompare(Z.type))}function AX(){return{available:Ch(),active:gh(),configured:mh()}}function vh($,W){if($.required&&!W[$.flag]?.trim())throw Error(`${$.label} is required`)}function ch($,W){let Z={};for(let J of $.fields)Z[J.flag]=W[J.flag]??J.initialValue??"";let Q={};for(let J of $.fields){if(!Ph(J,Z))continue;vh(J,Z),Q[J.flag]=Z[J.flag]}return Q}function uh($){if(!s$($))throw Error("connector.configure payload must be an object.");let W=OW($.channel);if(!W)throw Error("channel is required");let Z=wh.find((K)=>K.id===W);if(!Z)throw Error(`unknown connector channel: ${W}`);if(!new Set(FD().map((K)=>K.name)).has(Z.id))throw Error(`connector channel is not available: ${W}`);let J=kQ($.values),j=ch(Z,J),X=s$($.security)?$.security:{},Y=X.enabled===!0,V=kQ(X.values);if(Y&&Z.security)for(let K of Z.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let B=FX(),H=new Date().toISOString(),G=B.connectors[W];return B.connectors[W]={type:W,values:j,security:Y?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??H,updatedAt:H},UD(B),AX()}function dh($){if(!s$($))throw Error("connector.delete_config payload must be an object.");let W=OW($.channel);if(!W)throw Error("channel is required");let Z=FX();if(delete Z.connectors[W],Object.keys(Z.connectors).length>0)UD(Z);else Rh(KX(),{force:!0});return AX()}function lh($){return $==="connector.configure"||$==="connector.delete_config"}function GX($,W,Z){if(!lh(W.command))return;f8($.telemetry,{ulid:W.sessionId??W.requestId??"hub",tool:W.command,success:Z})}async function DD($,W){try{if(W.command==="connector.channels")return d(W,AX());if(W.command==="connector.configure"){let Z=uh(W.payload);return GX($,W,!0),d(W,Z)}if(W.command==="connector.delete_config"){let Z=dh(W.payload);return GX($,W,!0),d(W,Z)}return h(W,"unsupported_connector_command",`unsupported connector command: ${W.command}`)}catch(Z){return GX($,W,!1),h(W,"connector_command_failed",Z instanceof Error?Z.message:String(Z))}}var ph=30000;function rh($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function ih($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function nh($,W,Z){let Q=Z instanceof Error&&Z.message.trim()?Z.message:`Unknown session: ${W}`;return h($,l2,Q)}function ah($){return $?$:void 0}function oh($){let W=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(W&&Number.isFinite(W)&&W>0)return Math.floor(W);let Z=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z*1000);return}async function sh($,W,Z,Q){let J=performance.now(),j=!1,X={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z.sessionId,timeoutMs:Q},Y=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-J);n("warn","run.heartbeat",{...X,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:W.requestId,elapsedMs:H,...Q?{timeoutMs:Q}:{}},Z.sessionId))},ph),V=$.sessionHost.runTurn(Z);V.then((H)=>{if(!j)return;n("warn","run.late_end",{...X,elapsedMs:Math.round(performance.now()-J),finishReason:H?.finishReason})},(H)=>{if(!j)return;n("error","run.late_error",{...X,elapsedMs:Math.round(performance.now()-J),error:H})});let B;try{if(!Q)return await V;return await Promise.race([V,new Promise((H,G)=>{B=setTimeout(()=>{let K=`Hub run ${W.command} timed out after ${Q}ms.`;j=!0,clearInterval(Y),G(Error(K)),n("error","run.timeout",{...X,elapsedMs:Math.round(performance.now()-J)}),BX($,(F)=>F.sessionId===Z.sessionId,K),o$($,(F)=>F.sessionId===Z.sessionId,K),$.sessionHost.abort(Z.sessionId,K).catch((F)=>{n("error","run.timeout_abort_failed",{...X,error:F})})},Q)})])}finally{if(j=!0,clearInterval(Y),B)clearTimeout(B)}}async function _D($,W){let Z=P0(W),Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!J.trim())return h(W,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Z));let j=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,X=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,Y=oh(Q);$.suppressNextTerminalEventBySession.set(Z,"run.start.reply");let V;try{V=await sh($,W,{sessionId:Z,prompt:J,mode:ah(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:X,timeoutMs:Y},Y)}catch(H){if($.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z);if(J$(H))return nh(W,Z,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Z)),H}if(V){let H=await l0($,Z),G=ih(V);if($.publish($.buildEvent(rh(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...H?{snapshot:H}:{}},Z)),$.suppressNextTerminalEventBySession.get(Z)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Z)}else $.suppressNextTerminalEventBySession.delete(Z);let B=await l0($,Z);return d(W,V||B?{...V?{result:V}:{},...B?{snapshot:B}:{}}:void 0)}async function fD($,W){let Z=P0(W),Q=typeof W.payload?.reason==="string"?W.payload.reason:"Run was aborted before pending approval or capability request was resolved.";BX($,(J)=>J.sessionId===Z,Q);try{await $.sessionHost.abort(Z,W.payload?.reason)}catch(J){n("warn","run.abort_failed",{command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:Z,error:J})}finally{o$($,(J)=>J.sessionId===Z,Q)}return d(W,{applied:!0})}async function LD($,W){let Z=x6(W.payload?.payload);if(!Z)return h(W,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Z),d(W,{applied:!0})}async function OD($,W){switch(W.type){case"chunk":return;case"agent_event":await th($,W);return;case"hook":if(W.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:W.payload.toolName},W.payload.sessionId));else if(W.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:W.payload.toolName},W.payload.sessionId));return;case"team_progress":{let Z={type:"team_progress_projection",version:1,sessionId:W.payload.sessionId,summary:W.payload.summary,lastEvent:W.payload.lifecycle};$.publish($.buildEvent("team.progress",Z,W.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:W.payload.sessionId,prompts:W.payload.prompts},W.payload.sessionId));return;case"pending_prompt_submitted":{let Z={id:W.payload.id,prompt:W.payload.prompt,delivery:W.payload.delivery,attachmentCount:W.payload.attachmentCount,userImages:W.payload.userImages,userFiles:W.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:W.payload.sessionId,prompt:Z},W.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:W.payload.sessionId,snapshot:W.payload.snapshot},W.payload.sessionId));return;case"status":{let[Z,Q]=await Promise.all([b0($,W.payload.sessionId),l0($,W.payload.sessionId)]);if(Z)$.publish($.buildEvent("session.updated",{session:Z,...Q?{snapshot:Q}:{}},W.payload.sessionId));return}case"ended":await eh($,W);return;default:return}}async function th($,W){let{sessionId:Z,event:Q}=W.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},Z));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},Z));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},Z));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Z));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},Z));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},Z));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},Z));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},Z));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},Z));break}return}if(Q.type==="notice"){$.publish($.buildEvent("session.notice",{sessionId:Z,message:Q.message,noticeType:Q.noticeType,...Q.displayRole?{displayRole:Q.displayRole}:{},...Q.reason?{reason:Q.reason}:{},...Q.metadata?{metadata:Q.metadata}:{},agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Z)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Z,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:W.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:W.payload.teamAgentId,teamRole:W.payload.teamRole}},Z));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},Z))}async function eh($,W){let Z=$.suppressNextTerminalEventBySession.get(W.payload.sessionId),Q=Z===W.payload.reason||Z==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(W.payload.sessionId);let[J,j]=await Promise.all([b0($,W.payload.sessionId),l0($,W.payload.sessionId)]);if(W.payload.reason==="completed"){let X=await tU(J);$.publish($.buildEvent("ui.notify",X,W.payload.sessionId))}if(Q)return;$.publish($.buildEvent(W.payload.reason==="aborted"?"run.aborted":W.payload.reason==="error"||W.payload.reason==="failed"?"run.failed":"run.completed",{reason:W.payload.reason,...j?{snapshot:j}:{}},W.payload.sessionId))}import{createSessionId as RD,parseRuntimeConfigExtensions as ND}from"@cline/shared";var TD={};w(TD,{SessionVersioningService:()=>t$,SessionVersioningError:()=>p0});class p0 extends Error{code;constructor($,W){super(W);this.code=$;this.name="SessionVersioningError"}}function $k($){let W=$.sessionId.trim();if(!W)throw new p0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new p0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new p0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new p0("invalid_restore","checkpointRunCount must be a positive integer");return W}class t${async restoreCheckpoint($){let W=$.restore?.messages!==!1,Z=$.restore?.workspace!==!1,Q=$k({sessionId:$.sessionId,restoreMessages:W,restoreWorkspace:Z,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(Q);if(!J)throw new p0("session_not_found",`Session ${Q} not found`);let j=W?await $.readMessages(Q):void 0;if(W&&j?.length===0)throw new p0("session_messages_not_found",`No messages found for session ${Q}`);let X=aj({session:J,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:W});if(Z)await($.applyWorkspaceCheckpoint??oj)(X.cwd,X.checkpoint);let Y=P1({session:J,messages:j});if(!W)return{checkpoint:X.checkpoint,sourceSnapshot:Y};let V=ij(J,$.checkpointRunCount),B=$.restore?.omitCheckpointMessageFromSession?nj(j??[],$.checkpointRunCount):X.messages??[],H={sourceSession:J,sourceMessages:j,sourceSnapshot:Y,plan:X,restoredCheckpointMetadata:V,initialMessages:B,restoreMessages:W,restoreWorkspace:Z,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new p0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??pG)(X.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:X.messages,checkpoint:X.checkpoint,sourceSnapshot:Y,...A?{restoredSnapshot:P1({session:A,messages:B})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as de,HUB_COMPACTION_CAPABILITY as le,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as pe,HUB_HOOK_CAPABILITY_PREFIX as re,HUB_MISTAKE_LIMIT_CAPABILITY as ie,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ne,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as ae,isHubToolExecutorName as Wk}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as W00,HUB_COMPACTION_CAPABILITY as Z00,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Q00,HUB_HOOK_CAPABILITY_PREFIX as J00,HUB_MISTAKE_LIMIT_CAPABILITY as j00,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as X00,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Y00}from"@cline/shared";var Zk=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Y8($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function Qk($,W){let Z=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=Y8($.inputSchema);if(!Z||!Q||!j||!J||W.has(J))return;return W.add(J),{kind:"tool",capabilityName:J,name:Z,description:Q,inputSchema:j,...Y8($.lifecycle)?{lifecycle:Y8($.lifecycle)}:{}}}function DX($){if(!Array.isArray($))return[];let W=[],Z=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let J=Q,j=J.kind,X=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!X||Z.has(X))continue;if(j==="tool"){let Y=Qk(J,Z);if(Y)W.push(Y);continue}if(j==="toolExecutor"){let Y=J.executor;if(!Wk(Y))continue;Z.add(X),W.push({kind:"toolExecutor",capabilityName:X,executor:Y});continue}if(j==="hook"){let Y=typeof J.name==="string"?J.name.trim():"";if(!Y)continue;Z.add(X),W.push({kind:"hook",capabilityName:X,name:Y});continue}if(j==="compaction"){Z.add(X),W.push({kind:"compaction",capabilityName:X,...Y8(J.config)?{config:Y8(J.config)}:{}});continue}if(j==="checkpoint"){Z.add(X),W.push({kind:"checkpoint",capabilityName:X,...Y8(J.config)?{config:Y8(J.config)}:{}});continue}if(j==="mistakeLimit"){Z.add(X),W.push({kind:"mistakeLimit",capabilityName:X});continue}if(j==="userInstructionService")Z.add(X),W.push({kind:"userInstructionService",capabilityName:X})}return W}function qD($){let W=$.metadata?{...$.metadata}:void 0;if(W)delete W[R9];return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:W&&Object.keys(W).length>0?W:void 0}}function Jk($){return Object.hasOwn($,"update")?$.update:$}function TW($){return $.trim().replace(/^\/+/,"").toLowerCase()}function jk($){let W=($??[]).map(TW).filter(Boolean);return W.length>0?new Set(W):void 0}function Xk($,W,Z){if(!Z)return!0;let Q=TW($),J=TW(W),j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=J.includes(":")?J.split(":").at(-1)??J:J;return Z.has(Q)||Z.has(J)||Z.has(j)||Z.has(X)}function UX($,W){let Z=jk(W);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Xk(Q.id,Q.name,Z))}function zD($,W){let Z=async(Q,J)=>{let j=TW(Q),Y=UX($,W).filter((K)=>K.id===j||TW(K.name)===j||K.id.endsWith(`:${j}`)).filter((K)=>!K.disabled);if(Y.length!==1)return Y.length>1?`Skill "${Q}" is ambiguous. Use one of: ${Y.map((K)=>K.id).join(", ")}`:`Skill "${Q}" not found.`;let V=Y[0].skill,B=J?.trim(),H=B?`
590
590
  <command-args>${B}</command-args>`:"",G=V.description?.trim()?`Description: ${V.description.trim()}
591
591
 
592
592
  `:"";return`<command-name>${V.name}</command-name>${H}
593
593
  <command-instructions>
594
594
  ${G}${V.instructions}
595
- </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>UX($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function Wk($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>UX(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>TD(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>H6(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(F2(TD(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
595
+ </command-instructions>`};return Object.defineProperty(Z,"configuredSkills",{get:()=>UX($,W).map(({skill:Q,...J})=>J),enumerable:!0}),Z}function Yk($,W,Z,Q){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let X=await Q($,Z.capabilityName,{},W);if(X?.snapshot)J=X.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(X)=>[...J.records[X]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(X)=>{if(!X.startsWith("/")||X.length<2)return X;let V=X.match(/^\/(\S+)/)?.[1];if(!V)return X;let B=J.runtimeCommands.find((H)=>H.name===V);return B?`${B.instructions}${X.slice(V.length+1)}`:X},hasConfiguredSkills:(X)=>UX(J,X).some((Y)=>!Y.disabled),createSkillsExecutor:(X)=>zD(J,X),createExtension:(X)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[X.includeRules?"rules":void 0,X.registerSkillsTool?"tools":void 0,X.includeSkills||X.includeWorkflows?"commands":void 0].filter((Y)=>Boolean(Y))},setup(Y){if(X.includeRules)Y.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>G6(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(X.registerSkillsTool)Y.registerTool(F2(zD(J,X.allowedSkillNames)));for(let V of J.runtimeCommands.filter((B)=>B.kind==="skill"&&X.includeSkills||B.kind==="workflow"&&X.includeWorkflows))Y.registerCommand({name:V.name,description:V.description,handler:(B)=>{let H=B.trim();return H?`${V.instructions}
596
596
 
597
- ${H}`:V.instructions}})}})}}function Zk($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:zD(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function Qk($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:zD(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.(th(V))}:void 0))?.result}}))}function Jk($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of oh){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function _X($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Zk($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:Jk($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:Qk($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:Wk($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var qD="hubCapabilityOwnerClientId";function IQ($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function jk($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function Xk($){let W=u6($)??{},Z={},Q=IQ(W.providerId);if(Q)Z.providerId=Q;let J=IQ(W.modelId);if(J)Z.modelId=J;let j=IQ(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=IQ(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=jk(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return T2(Z)}function Yk($,W){return $.sessionState.get(W)?.createdByClientId}function Vk($){if(!$||!(qD in $))return $;let W={...$};return delete W[qD],W}function ND($){let W=Yk($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function ED($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};i("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=K1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return i("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=DX(V.clientContributions);i("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let D=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||MD(),U=RD(V.configExtensions);i("info","session.create.runtime_build.begin",{...J,sessionId:D,configExtensionCount:U?.length??0});let f=_X({sessionId:D,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});i("info","session.create.start_session.begin",{...J,sessionId:D,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let _=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:D,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});i("info","session.create.start_session.end",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!_.result}),XX($,_.sessionId,K,"creator",{interactive:X.interactive!==!1}),i("info","session.create.read_records.begin",{...J,sessionId:_.sessionId});let[R,T]=await Promise.all([b0($,_.sessionId),u0($,_.sessionId)]);if(i("info","session.create.read_records.end",{...J,sessionId:_.sessionId,hasSession:!!R,hasSnapshot:!!T,elapsedMs:Math.round(performance.now()-Q)}),R)$.publish($.buildEvent("session.created",{session:R,...T?{snapshot:T}:{}},_.sessionId));return i("info","session.create.reply",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q)}),u(W,{session:R,...T?{snapshot:T}:{}})}async function wD($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=K1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=DX(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||MD(),f=RD(B.configExtensions),_=_X({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),T=await new s$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)G.checkpoint=N.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:N.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:N.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:N.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??N.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!Y)return u(W,{checkpoint:T.checkpoint});let O=T.startResult;if(!O)return h(W,"restore_failed","Checkpoint restore did not start a session");XX($,O.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([b0($,O.sessionId),u0($,O.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},O.sessionId));return u(W,{session:L,...C?{snapshot:C}:{},messages:T.messages??[],checkpoint:T.checkpoint})}catch(V){if(V instanceof d0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function CD($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await b0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);tU($,Z,W.clientId?.trim()||"hub-client","participant");let J=await b0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),u(W,{session:J??Q})}async function PD($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}a$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([b0($,Z),u0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),u(W)}async function SD($,W){let Z=S0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([b0($,Z),Q?u0($,Z):Promise.resolve(void 0)]);return J?u(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function bD($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return u(W,{sessionId:Z,messages:J})}async function yD($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=ND({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return u(W,{sessionId:Z,state:X})}async function hD($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>hQ(j,$.sessionState.get(j.sessionId)));return u(W,{sessions:J})}async function kD($,W){let Z=S0(W),Q=Vk(u6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([b0($,Z),u0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function ID($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=u6(W.payload),j=Xk(J?.updates);return await Q.call($.sessionHost,Z,j),u(W,{sessionId:Z,updated:!0})}async function xD($,W){let Z=S0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await b0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=ND({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=K1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([b0($,Z),u0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function gD($,W){let Z=S0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),u(W,{deleted:Q})}async function mD($,W){let Z=S0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return u(W,{sessionId:Z,prompts:J})}async function vD($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return u(W,Y)}async function cD($,W){let Z=S0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return u(W,j)}function uD($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var Hk=new Set(["skills","workflows","rules","tools","mcp"]);function fX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function TW($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function Gk($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function dD($){if($===void 0)return{};if(!fX($))throw Error("settings.list payload must be an object.");return{cwd:TW($,"cwd"),workspaceRoot:TW($,"workspaceRoot"),availabilityContext:fX($.availabilityContext)?$.availabilityContext:void 0}}function Kk($){if(!fX($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Hk.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...dD($),type:W,id:TW($,"id"),path:TW($,"path"),name:TW($,"name"),enabled:Gk($,"enabled")}}class d6{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=Bk("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new h1({sessionService:new y1(new S1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(W)=>this.publish(W),buildEvent:X8,requestCapability:(W,Z,Q,J,j)=>WD(this.ctx,W,Z,Q,J,j)},this.schedules=new m6({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(X8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new g6(this.schedules),this.settings=$.settingsService??new v$,$.cronOptions)this.cronService=new o5({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{LD(this.ctx,W).catch((Z)=>{HX("session event handling failed",Z),xQ(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())VX(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(a$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw xQ(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return jD(this.ctx,$);case"client.update":return XD(this.ctx,$);case"client.unregister":return YD(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return VD(this.ctx,$);case"session.create":return await ED(this.ctx,$,(W)=>YX(this.ctx,W));case"session.restore":return await wD(this.ctx,$,(W)=>YX(this.ctx,W));case"session.attach":return await CD(this.ctx,$);case"session.detach":return await PD(this.ctx,$);case"session.get":return await SD(this.ctx,$);case"session.messages":return await bD(this.ctx,$);case"session.compaction.get":return await yD(this.ctx,$);case"session.list":return await hD(this.ctx,$);case"session.update":return await kD(this.ctx,$);case"session.update_connection":return await ID(this.ctx,$);case"session.compaction.update":return await xD(this.ctx,$);case"session.pending_prompts":return await mD(this.ctx,$);case"session.update_pending_prompt":return await vD(this.ctx,$);case"session.remove_pending_prompt":return await cD(this.ctx,$);case"session.delete":return await gD(this.ctx,$);case"session.hook":return await fD(this.ctx,$);case"run.start":case"session.send_input":return await DD(this.ctx,$);case"run.abort":return await _D(this.ctx,$);case"capability.request":return await QD(this.ctx,$);case"approval.respond":return await eU(this.ctx,$);case"capability.respond":return JD(this.ctx,$);case"capability.progress":return ZD(this.ctx,$);case"ui.notify":return this.publish(X8("ui.notify",$.payload??{})),u($);case"ui.show_window":return this.publish(X8("ui.show_window",$.payload??{})),u($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await UD(this.ctx,$);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=uD($.command);if(Z)this.publish(X8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Fk(W.error.code))return;xQ(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(dD($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(Kk($.payload));return this.publish(X8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}a$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){HX(`listener threw while publishing ${$.event}`,Q),xQ(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Fk($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as _k}from"node:crypto";import fk from"node:http";import Lk from"node:net";import{URL as zX}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as rD,HUB_CAPABILITIES as Ok,isHubProtocolCompatible as Tk,MAX_CLIENT_HUB_PROTOCOL_VERSION as iD,MIN_CLIENT_HUB_PROTOCOL_VERSION as nD}from"@cline/shared";import{WebSocketServer as zk}from"ws";import{captureSdkError as lD,HUB_COMMAND_SLOW_LOG_MS as Ak,resolveHubCommandTimeoutMs as Uk,safeJsonParse as Dk}from"@cline/shared";function LX($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function pD($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class zW{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=LX(B);i("info","command.start",K);let F=setTimeout(()=>{if(G)return;i("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},Ak),A=this.transport.command(B.envelope);A.then((T)=>{if(!G)return;i(T.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!G)return;i("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:T})});let D=!1,U,f,_=Uk(B.envelope.command,B.envelope.timeoutMs);try{f=_===null?await A:await Promise.race([A,new Promise((T)=>{U=setTimeout(()=>{D=!0,lD(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${_}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:_}}),T(pD(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${_}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},_)})])}catch(T){if(clearTimeout(F),U)clearTimeout(U);throw T}if(G=D,clearTimeout(F),U)clearTimeout(U);let R=Math.round(performance.now()-H);if(D)i("error","command.timeout",{...K,durationMs:R,timeoutMs:_});else i(f.ok?"info":"warn","command.end",{...K,durationMs:R,ok:f.ok,errorCode:f.error?.code,errorMessage:f.error?.message});if(B.envelope.command==="client.register"&&f.ok){let O=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(O)Z.add(O)}else if(B.envelope.command==="client.unregister"&&f.ok){let T=B.envelope.clientId?.trim();if(T)Z.delete(T)}J({kind:"reply",envelope:f});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?Dk(V.data):void 0;if(!H||H.kind!=="command"){i("error","rejected malformed websocket frame",{error:B});return}i("error","command.error",{...LX(H),error:B}),lD(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:LX(H)}),J({kind:"reply",envelope:pD(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class qW{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function qk($){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((W)=>Buffer.from(W))).toString();return String($)}function Mk($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:qk(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function Rk($){try{$.write(`HTTP/1.1 400 Bad Request\r
597
+ ${H}`:V.instructions}})}})}}function Vk($,W,Z,Q){let J=Z.map((j)=>[j.executor,async(...X)=>{let Y=X.at(-1),V=X.slice(0,-1);return(await Q($,j.capabilityName,{executor:j.executor,args:V,context:qD(Y)},W))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function Bk($,W,Z,Q){if(Z.length===0)return;return Z.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(j,X){return(await Q($,J.capabilityName,{toolName:J.name,input:j,context:qD(X)},W,X.emitUpdate?(V)=>{X.emitUpdate?.(Jk(V))}:void 0))?.result}}))}function Hk($,W,Z,Q){let J=new Map(Z.map((X)=>[X.name,X])),j={};for(let X of Zk){let Y=J.get(X);if(!Y)continue;j[X]=async(V)=>{return(await Q($,Y.capabilityName,{context:V},W))?.control}}return Object.keys(j).length>0?j:void 0}function _X($){let W=$.contributions.filter((V)=>V.kind==="toolExecutor"),Z=$.contributions.filter((V)=>V.kind==="tool"),Q=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),j=$.contributions.find((V)=>V.kind==="checkpoint"),X=$.contributions.find((V)=>V.kind==="mistakeLimit"),Y=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Vk($.sessionId,$.targetClientId,W,$.requestCapability),localRuntime:{...Q.length>0?{hooks:Hk($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...Z.length>0?{extraTools:Bk($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}:{},...Y?{userInstructionService:Yk($.sessionId,$.targetClientId,Y,$.requestCapability)}:{}}}}var MD="hubCapabilityOwnerClientId";function IQ($){return typeof $==="string"&&$.trim().length>0?$.trim():void 0}function Gk($){if($==="low"||$==="medium"||$==="high"||$==="xhigh"||$===null)return $;return}function Kk($){let W=d6($)??{},Z={},Q=IQ(W.providerId);if(Q)Z.providerId=Q;let J=IQ(W.modelId);if(J)Z.modelId=J;let j=IQ(W.apiKey);if(j!==void 0)Z.apiKey=j;let X=IQ(W.baseUrl);if(X!==void 0)Z.baseUrl=X;if(W.headers&&typeof W.headers==="object")Z.headers=W.headers;if(W.providerConfig&&typeof W.providerConfig==="object")Z.providerConfig=W.providerConfig;if(Object.hasOwn(W,"thinking")){if(typeof W.thinking==="boolean"||W.thinking===null)Z.thinking=W.thinking}if(Object.hasOwn(W,"reasoningEffort")){let Y=Gk(W.reasoningEffort);if(Y!==void 0)Z.reasoningEffort=Y}if(Object.hasOwn(W,"thinkingBudgetTokens")){if(typeof W.thinkingBudgetTokens==="number"&&Number.isFinite(W.thinkingBudgetTokens)&&W.thinkingBudgetTokens>0)Z.thinkingBudgetTokens=Math.trunc(W.thinkingBudgetTokens);else if(W.thinkingBudgetTokens===null)Z.thinkingBudgetTokens=null}return T2(Z)}function Fk($,W){return $.sessionState.get(W)?.createdByClientId}function Ak($){if(!$||!(MD in $))return $;let W={...$};return delete W[MD],W}function ED($){let W=Fk($.ctx,$.sessionId);if(!W)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} has no owner`);if(W!==$.clientId)return h($.envelope,"session_wrong_client",`Session ${$.sessionId} is owned by ${W}`);return}async function wD($,W,Z){let Q=performance.now(),J={command:W.command,requestId:W.requestId,clientId:W.clientId,sessionId:W.sessionId};n("info","session.create.begin",J);let j=W.payload&&typeof W.payload==="object"?W.payload:{},X=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},Y=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,V=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{},B=A1(j.initialCompactionState);if(typeof Y?.mode==="string")X.mode=Y.mode;else if(typeof V.mode==="string")X.mode=V.mode;if(typeof Y?.systemPrompt==="string")X.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")X.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)X.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)X.checkpointEnabled=!0;let H=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},G=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!G)return n("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(W,"invalid_session_create","session.create requires workspaceRoot or cwd");let K=W.clientId?.trim()||"hub-client",F=DX(V.clientContributions);n("info","session.create.contributions_parsed",{...J,clientId:K,workspaceRoot:G,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:F.length});let D=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||RD(),U=ND(V.configExtensions);n("info","session.create.runtime_build.begin",{...J,sessionId:D,configExtensionCount:U?.length??0});let f=_X({sessionId:D,targetClientId:K,contributions:F,sessionConfig:Y,requestCapability:$.requestCapability});n("info","session.create.start_session.begin",{...J,sessionId:D,provider:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),model:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub")});let _=await $.sessionHost.startSession({source:typeof X.source==="string"?X.source:void 0,interactive:X.interactive!==!1,sessionMetadata:Object.keys(X).length>0?X:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,initialCompactionState:B,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:U,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Z},config:{...Y??{},sessionId:D,providerId:Y?.providerId??(typeof H.provider==="string"?H.provider:typeof X.provider==="string"?X.provider:"hub"),modelId:Y?.modelId??(typeof H.model==="string"?H.model:typeof X.model==="string"?X.model:"hub"),apiKey:Y?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:Y?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():G),workspaceRoot:Y?.workspaceRoot??G,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof X.teamName==="string"?X.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});n("info","session.create.start_session.end",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!_.result}),XX($,_.sessionId,K,"creator",{interactive:X.interactive!==!1}),n("info","session.create.read_records.begin",{...J,sessionId:_.sessionId});let[R,T]=await Promise.all([b0($,_.sessionId),l0($,_.sessionId)]);if(n("info","session.create.read_records.end",{...J,sessionId:_.sessionId,hasSession:!!R,hasSnapshot:!!T,elapsedMs:Math.round(performance.now()-Q)}),R)$.publish($.buildEvent("session.created",{session:R,...T?{snapshot:T}:{}},_.sessionId));return n("info","session.create.reply",{...J,sessionId:_.sessionId,elapsedMs:Math.round(performance.now()-Q)}),d(W,{session:R,...T?{snapshot:T}:{}})}async function CD($,W,Z){let Q=W.payload&&typeof W.payload==="object"?W.payload:{},J=typeof Q.sessionId==="string"?Q.sessionId.trim():W.sessionId?.trim()||"",j=Q.checkpointRunCount;if(!J)return h(W,"invalid_restore","session.restore requires a session id");let X=Q.restore&&typeof Q.restore==="object"?Q.restore:{},Y=X.messages!==!1;if(typeof j!=="number")return h(W,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(Y&&!V)return h(W,"invalid_restore","sessionConfig is required when restore.messages is true");let B=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},H=A1(Q.initialCompactionState),G=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof V?.mode==="string")G.mode=V.mode;else if(typeof B.mode==="string")G.mode=B.mode;if(typeof V?.systemPrompt==="string")G.systemPrompt=V.systemPrompt;else if(typeof B.systemPrompt==="string")G.systemPrompt=B.systemPrompt;if(V?.checkpoint?.enabled===!0)G.checkpointEnabled=!0;else if(B.checkpointEnabled===!0)G.checkpointEnabled=!0;let K=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},F=W.clientId?.trim()||"hub-client",A=DX(B.clientContributions),U=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||RD(),f=ND(B.configExtensions),_=_X({sessionId:U,targetClientId:F,contributions:A,sessionConfig:V,requestCapability:$.requestCapability}),T=await new t$().restoreCheckpoint({sessionId:J,checkpointRunCount:j,restore:{messages:X.messages,workspace:X.workspace,omitCheckpointMessageFromSession:X.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)G.checkpoint=N.restoredCheckpointMetadata;let p=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof G.source==="string"?G.source:void 0,interactive:G.interactive!==!1,sessionMetadata:{...G,restoredFromSessionId:J,restoredCheckpointRunCount:j},initialMessages:N.initialMessages,initialCompactionState:H,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,..._.localRuntime},capabilities:{toolExecutors:_.toolExecutors,requestToolApproval:Z},config:{...V??{},sessionId:U,providerId:V?.providerId??(typeof K.provider==="string"?K.provider:N.sourceSession.provider),modelId:V?.modelId??(typeof K.model==="string"?K.model:N.sourceSession.model),apiKey:V?.apiKey??(typeof K.apiKey==="string"?K.apiKey:""),cwd:V?.cwd??N.plan.cwd,workspaceRoot:V?.workspaceRoot??p,systemPrompt:V?.systemPrompt??(typeof B.systemPrompt==="string"?B.systemPrompt:""),mode:V?.mode??(B.mode==="plan"||B.mode==="yolo"?B.mode:"act"),maxIterations:V?.maxIterations??(typeof B.maxIterations==="number"?B.maxIterations:void 0),enableTools:V?.enableTools??B.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??B.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??B.enableTeams!==!1,checkpoint:V?.checkpoint??(B.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof G.teamName==="string"?G.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):B.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!Y)return d(W,{checkpoint:T.checkpoint});let O=T.startResult;if(!O)return h(W,"restore_failed","Checkpoint restore did not start a session");XX($,O.sessionId,F,"creator",{interactive:G.interactive!==!1});let[L,C]=await Promise.all([b0($,O.sessionId),l0($,O.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...C?{snapshot:C}:{}},O.sessionId));return d(W,{session:L,...C?{snapshot:C}:{},messages:T.messages??[],checkpoint:T.checkpoint})}catch(V){if(V instanceof p0)return h(W,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(W,"restore_failed",V instanceof Error?V.message:String(V))}}async function PD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_attach","session.attach requires a session id");let Q=await b0($,Z);if(!Q)return h(W,"session_not_found",`Unknown session: ${Z}`);eU($,Z,W.clientId?.trim()||"hub-client","participant");let J=await b0($,Z);return $.publish($.buildEvent("session.attached",{session:J??Q},Z)),d(W,{session:J??Q})}async function SD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_detach","session.detach requires a session id");let Q=W.clientId?.trim()||"hub-client",J=$.sessionState.get(Z);if(J){if(J.participants.delete(Q),J.createdByClientId===Q)J.createdByClientId=void 0;if(J.participants.size===0)$.sessionState.delete(Z)}o$($,(Y)=>Y.sessionId===Z&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[j,X]=await Promise.all([b0($,Z),l0($,Z)]);return $.publish($.buildEvent("session.detached",j?{session:j,...X?{snapshot:X}:{},clientId:Q}:{clientId:Q},Z)),d(W)}async function bD($,W){let Z=P0(W),Q=W.payload?.includeSnapshot===!0,[J,j]=await Promise.all([b0($,Z),Q?l0($,Z):Promise.resolve(void 0)]);return J?d(W,{session:J,...j?{snapshot:j}:{}}):h(W,"session_not_found",`Unknown session: ${Z}`)}async function yD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.messages requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=await $.sessionHost.readSessionMessages(Z);return d(W,{sessionId:Z,messages:J})}async function hD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.get requires a session id");if(!await b0($,Z))return h(W,"session_not_found",`Unknown session: ${Z}`);let J=W.clientId?.trim()||"hub-client",j=ED({sessionId:Z,ctx:$,clientId:J,envelope:W});if(j)return j;let X=await $.sessionHost.readSessionCompactionState(Z);return d(W,{sessionId:Z,state:X})}async function kD($,W){let Z=typeof W.payload?.limit==="number"?W.payload.limit:200,J=(await $.sessionHost.listSessions(Z)).map((j)=>hQ(j,$.sessionState.get(j.sessionId)));return d(W,{sessions:J})}async function ID($,W){let Z=P0(W),Q=Ak(d6(W.payload?.metadata)),J=await $.sessionHost.updateSession(Z,{metadata:Q}),[j,X]=await Promise.all([b0($,Z),l0($,Z)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...X?{snapshot:X}:{}},Z));return{version:W.version,requestId:W.requestId,ok:J.updated,payload:{updated:J.updated,session:j,...X?{snapshot:X}:{}}}}async function xD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_update_connection","session.update_connection requires a session id");let Q=$.sessionHost.updateSessionConnection;if(!Q)return h(W,"unsupported_session_update_connection","runtime host does not support session connection updates");let J=d6(W.payload),j=Kk(J?.updates);return await Q.call($.sessionHost,Z,j),d(W,{sessionId:Z,updated:!0})}async function gD($,W){let Z=P0(W);if(!Z)return h(W,"invalid_session_id","session.compaction.update requires a session id");let Q=W.clientId?.trim()||"hub-client",J=await b0($,Z);if(!J)return h(W,"session_not_found",`Unknown session: ${Z}`);let j=ED({sessionId:Z,ctx:$,clientId:Q,envelope:W});if(j)return j;let X=W.payload&&typeof W.payload==="object"?W.payload:{},Y=A1(X.state);if(!Y)return h(W,"invalid_compaction_state","session.compaction.update requires a valid compaction state");let V=await $.sessionHost.updateSessionCompactionState(Z,Y),[B,H]=V.updated?await Promise.all([b0($,Z),l0($,Z)]):[J,void 0];if(V.updated)$.publish($.buildEvent("session.updated",{session:B??J,...H?{snapshot:H}:{}},Z));return{version:W.version,requestId:W.requestId,ok:!0,payload:{updated:V.updated,session:B??J,...H?{snapshot:H}:{}}}}async function mD($,W){let Z=P0(W),Q=await $.sessionHost.deleteSession(Z);return $.sessionState.delete(Z),d(W,{deleted:Q})}async function vD($,W){let Z=P0(W),Q=$.sessionHost.pendingPrompts;if(!Q)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await Q.list({sessionId:Z});return d(W,{sessionId:Z,prompts:J})}async function cD($,W){let Z=P0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=typeof W.payload?.prompt==="string"?W.payload.prompt:void 0,j=W.payload?.delivery==="queue"||W.payload?.delivery==="steer"?W.payload.delivery:void 0,X=$.sessionHost.pendingPrompts;if(!X)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let Y=await X.update({sessionId:Z,promptId:Q,prompt:J,delivery:j});return d(W,Y)}async function uD($,W){let Z=P0(W),Q=typeof W.payload?.promptId==="string"?W.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(W,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await J.delete({sessionId:Z,promptId:Q});return d(W,j)}function dD($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var Dk=new Set(["skills","workflows","rules","tools","mcp"]);function fX($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function zW($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="string")throw Error(`settings payload '${W}' must be a string.`);return Z}function _k($,W){let Z=$[W];if(Z===void 0)return;if(typeof Z!=="boolean")throw Error(`settings payload '${W}' must be a boolean.`);return Z}function lD($){if($===void 0)return{};if(!fX($))throw Error("settings.list payload must be an object.");return{cwd:zW($,"cwd"),workspaceRoot:zW($,"workspaceRoot"),availabilityContext:fX($.availabilityContext)?$.availabilityContext:void 0}}function fk($){if(!fX($))throw Error("settings.toggle payload must be an object.");let{type:W}=$;if(typeof W!=="string"||!Dk.has(W))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...lD($),type:W,id:zW($,"id"),path:zW($,"path"),name:zW($,"name"),enabled:_k($,"enabled")}}class l6{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=Uk("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new k1({sessionService:new h1(new b1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(W)=>this.publish(W),buildEvent:X8,requestCapability:(W,Z,Q,J,j)=>ZD(this.ctx,W,Z,Q,J,j)},this.schedules=new v6({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(W,Z)=>{let Q=W==="schedule.execution.completed"?"schedule.execution_completed":W==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(X8(Q,Z&&typeof Z==="object"?Z:void 0))}}),this.scheduleCommands=new m6(this.schedules),this.settings=$.settingsService??new c$,$.cronOptions)this.cronService=new s5({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((W)=>{OD(this.ctx,W).catch((Z)=>{HX("session event handling failed",Z),xQ(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Z,severity:"error",handled:!0,context:{eventType:W.type,sessionId:W.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())VX(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(o$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let W=await this.dispatchCommand($);return this.captureFailedReply($,W),W}catch(W){throw xQ(this.options.telemetry,{component:"core",operation:"hub.command",error:W,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),W}}async dispatchCommand($){switch($.command){case"client.register":return XD(this.ctx,$);case"client.update":return YD(this.ctx,$);case"client.unregister":return VD(this.ctx,$,(W)=>{this.listeners.delete(W),this.detachClientFromSessions(W)});case"client.list":return BD(this.ctx,$);case"session.create":return await wD(this.ctx,$,(W)=>YX(this.ctx,W));case"session.restore":return await CD(this.ctx,$,(W)=>YX(this.ctx,W));case"session.attach":return await PD(this.ctx,$);case"session.detach":return await SD(this.ctx,$);case"session.get":return await bD(this.ctx,$);case"session.messages":return await yD(this.ctx,$);case"session.compaction.get":return await hD(this.ctx,$);case"session.list":return await kD(this.ctx,$);case"session.update":return await ID(this.ctx,$);case"session.update_connection":return await xD(this.ctx,$);case"session.compaction.update":return await gD(this.ctx,$);case"session.pending_prompts":return await vD(this.ctx,$);case"session.update_pending_prompt":return await cD(this.ctx,$);case"session.remove_pending_prompt":return await uD(this.ctx,$);case"session.delete":return await mD(this.ctx,$);case"session.hook":return await LD(this.ctx,$);case"run.start":case"session.send_input":return await _D(this.ctx,$);case"run.abort":return await fD(this.ctx,$);case"capability.request":return await JD(this.ctx,$);case"approval.respond":return await $D(this.ctx,$);case"capability.respond":return jD(this.ctx,$);case"capability.progress":return QD(this.ctx,$);case"ui.notify":return this.publish(X8("ui.notify",$.payload??{})),d($);case"ui.show_window":return this.publish(X8("ui.show_window",$.payload??{})),d($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"connector.channels":case"connector.configure":case"connector.delete_config":return await DD(this.ctx,$);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let W=await this.scheduleCommands.handleCommand($);if(W.ok){let Z=dD($.command);if(Z)this.publish(X8(Z,W.payload))}return W}}}captureFailedReply($,W){if(W.ok||!W.error||!Lk(W.error.code))return;xQ(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(W.error.message),severity:W.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:W.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let W=await this.settings.list(lD($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:W instanceof Error?W.message:String(W)}}}}async handleSettingsToggle($){try{let W=await this.settings.toggle(fk($.payload));return this.publish(X8("settings.changed",{types:W.changedTypes,snapshot:W.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:W.snapshot,changedTypes:W.changedTypes}}}catch(W){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:W instanceof Error?W.message:String(W)}}}}subscribe($,W,Z){let Q=this.listeners.get($)??new Set,J={sessionId:Z?.sessionId,listener:W};return Q.add(J),this.listeners.set($,Q),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(J),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[W,Z]of this.sessionState.entries()){if(Z.participants.delete($),Z.createdByClientId===$)Z.createdByClientId=void 0;if(Z.participants.size===0)this.sessionState.delete(W)}o$(this.ctx,(W)=>W.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let W of this.listeners.values())for(let Z of W){if(Z.sessionId&&Z.sessionId!==$.sessionId)continue;try{Z.listener($)}catch(Q){HX(`listener threw while publishing ${$.event}`,Q),xQ(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function Lk($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as qk}from"node:crypto";import Mk from"node:http";import Rk from"node:net";import{URL as zX}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as iD,HUB_CAPABILITIES as Nk,isHubProtocolCompatible as Ek,MAX_CLIENT_HUB_PROTOCOL_VERSION as nD,MIN_CLIENT_HUB_PROTOCOL_VERSION as aD}from"@cline/shared";import{WebSocketServer as wk}from"ws";import{captureSdkError as pD,HUB_COMMAND_SLOW_LOG_MS as Ok,resolveHubCommandTimeoutMs as Tk,safeJsonParse as zk}from"@cline/shared";function LX($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function rD($,W,Z){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:W,message:Z}}}class qW{transport;telemetry;constructor($,W){this.transport=$;this.telemetry=W}attach($){let W=new Map,Z=new Set,Q=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(B){console.error(`[hub] failed to send websocket frame: ${B instanceof Error?B.stack||B.message:String(B)}`)}},j=(V)=>{J({kind:"event",envelope:V})},X=async(V)=>{try{let B=JSON.parse(V.data);switch(B.kind){case"command":{let H=performance.now(),G=!1,K=LX(B);n("info","command.start",K);let F=setTimeout(()=>{if(G)return;n("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-H)})},Ok),A=this.transport.command(B.envelope);A.then((T)=>{if(!G)return;n(T.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!G)return;n("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-H),error:T})});let D=!1,U,f,_=Tk(B.envelope.command,B.envelope.timeoutMs);try{f=_===null?await A:await Promise.race([A,new Promise((T)=>{U=setTimeout(()=>{D=!0,pD(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${B.envelope.command} did not complete within ${_}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:_}}),T(rD(B,"hub_command_timeout",`Hub command ${B.envelope.command} did not complete within ${_}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${B.envelope.requestId}.`))},_)})])}catch(T){if(clearTimeout(F),U)clearTimeout(U);throw T}if(G=D,clearTimeout(F),U)clearTimeout(U);let R=Math.round(performance.now()-H);if(D)n("error","command.timeout",{...K,durationMs:R,timeoutMs:_});else n(f.ok?"info":"warn","command.end",{...K,durationMs:R,ok:f.ok,errorCode:f.error?.code,errorMessage:f.error?.message});if(B.envelope.command==="client.register"&&f.ok){let O=(B.envelope.payload??{}).clientId?.trim()||B.envelope.clientId?.trim();if(O)Z.add(O)}else if(B.envelope.command==="client.unregister"&&f.ok){let T=B.envelope.clientId?.trim();if(T)Z.delete(T)}J({kind:"reply",envelope:f});break}case"stream.subscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;if(W.has(H))break;let G=await this.transport.subscribe(B.clientId,j,{sessionId:B.sessionId});W.set(H,G);break}case"stream.unsubscribe":{let H=`${B.clientId}:${B.sessionId??"*"}`;W.get(H)?.(),W.delete(H);break}case"reply":case"event":break}}catch(B){let H=typeof V.data==="string"?zk(V.data):void 0;if(!H||H.kind!=="command"){n("error","rejected malformed websocket frame",{error:B});return}n("error","command.error",{...LX(H),error:B}),pD(this.telemetry,{component:"core",operation:"hub.websocket_command",error:B,severity:"error",handled:!0,context:LX(H)}),J({kind:"reply",envelope:rD(H,"command_failed",B instanceof Error?B.message:"Unknown hub error")})}},Y=()=>{if(Q)return;Q=!0;for(let V of W.values())V();W.clear();for(let V of Z)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Z.clear(),$.removeEventListener("message",X),$.removeEventListener("close",Y)};return $.addEventListener("message",X),$.addEventListener("close",Y),Y}}class MW{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,W,Z){return this.transport.subscribe($,W,Z)}}function Ck($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((W)=>Buffer.from(W))).toString();return String($)}function Pk($){return{send(W){$.send(W)},addEventListener(W,Z){if(W==="message"){$.on("message",(Q)=>{Z({data:Ck(Q)})});return}$.on("close",Z)},removeEventListener(){}}}function Sk($){try{$.write(`HTTP/1.1 400 Bad Request\r
598
598
  Connection: close\r
599
599
  Content-Length: 0\r
600
600
  \r
601
- `),$.end()}catch{$.destroy()}}function Nk($){try{$.write(`HTTP/1.1 401 Unauthorized\r
601
+ `),$.end()}catch{$.destroy()}}function bk($){try{$.write(`HTTP/1.1 401 Unauthorized\r
602
602
  Connection: close\r
603
603
  Content-Length: 0\r
604
604
  \r
605
- `),$.end()}catch{$.destroy()}}function OX($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&_k(Z,Q)}function aD($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
606
- Caused by: ${$.stack}`;return j}async function Ek($){return await new Promise((W,Z)=>{let Q=Lk.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function wk($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var TX=new Map,oD="cline-hub-auth.",Ck=30000;function qX($){return Array.isArray($)?$.join(","):$??""}function sD($){return $===32||$===9}function gQ($){let W=qX($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!sD(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&sD(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function Pk($){for(let W of qX($).split(",")){let Z=W.trim();if(Z.startsWith(oD))return Z.slice(oD.length).trim()||null}return null}function mQ($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function MX($){let W=qX($).trim();if(!W)return!1;try{return mQ(new zX(W).hostname)}catch{return!1}}async function V8($){let W=$.owner??J$(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??L6(),j=J===0?await Ek(Z):J,X=j,Y=_1(Z,j,Q),V=HQ(),B=BQ(),H=new d6($);await H.start();let G=new zW(new qW(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:rD,minClientProtocolVersion:nD,maxClientProtocolVersion:iD,capabilities:Ok,coreVersion:t4.version,buildId:V,pid:process.pid,startedAt:F},D=new Set,U,f,_=async()=>{if(f)return f;return f=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{T.close((N)=>{if(N){C(N);return}L()})}),await new Promise((L,C)=>{R.close((N)=>{if(N){C(N);return}L()})}),await H.stop(),(await O0(W.discoveryPath))?.url===Y)await m0(W.discoveryPath)})(),f},R=fk.createServer((O,L)=>{if((O.url??"/")==="/health"){let N=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((O.url??"/")==="/status"){if(!OX(gQ(O.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let N=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((O.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new zX(O.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&O.method==="POST"){if(!OX(gQ(O.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{_()});return}L.statusCode=404,L.end("Not found")}),T=new zk({noServer:!0});U=setInterval(()=>{for(let O of D){if(O.isAlive===!1){try{O.terminate?.()}catch{}D.delete(O);continue}O.isAlive=!1;try{O.ping?.()}catch{try{O.terminate?.()}catch{}D.delete(O)}}},Ck),R.on("upgrade",(O,L,C)=>{if(new zX(O.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(OX(Pk(O.headers["sec-websocket-protocol"]),B)||mQ(Z)&&MX(O.headers.origin))){Nk(L);return}try{T.handleUpgrade(O,L,C,(x)=>{let P=x;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),D.add(P);let r=G.attach(Mk(x));K.add(r),x.once("close",()=>{D.delete(P),r(),K.delete(r)})})}catch{Rk(L)}});try{await new Promise((O,L)=>{R.once("error",(C)=>{L(aD(C,{host:Z,port:j,pathname:Q}))}),R.listen(j,Z,()=>{let C=R.address();if(!C||typeof C==="string"){L(aD(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=_1(Z,X,Q),O()})})}catch(O){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),O}return await GQ(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:rD,minClientProtocolVersion:nD,maxClientProtocolVersion:iD,capabilities:[...A.capabilities],coreVersion:t4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:_}}async function vQ($){let W=$.owner??J$(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??L6(),j=$.pathname??"/hub",X=_1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)l$(H.url,H.authToken);return H},B=TX.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await KQ(W.discoveryPath,async()=>{let H=await O0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await j$(H.url,{authToken:H.authToken});if(F?.url&&Tk(F).compatible&&await w1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await m0(W.discoveryPath);let K=async(F)=>{let A=V8({...F,owner:W});TX.set(Y,A);try{let D=await A;return V({server:D,url:D.url,authToken:D.authToken,action:"started"})}catch(D){throw TX.delete(Y),D}};try{return await K($)}catch(F){if(!$.allowPortFallback||!wk(F))throw F;return await K({...$,port:0})}})}function eD(){return tD()==="production"?Q1():v0()}function Sk($){return tD()!=="production"&&!$}async function $_($){let W=Z1({host:$.host,port:$.port,pathname:$.pathname});return await V8({...$,...W,owner:eD()})}async function W_($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=Z1({host:$.host,port:$.port,pathname:$.pathname});return await vQ({...$,...Z,allowPortFallback:$.allowPortFallback??Sk(W),owner:eD()})}uQ();var J_={};w(J_,{registerRemoteConfigSessionBlobUpload:()=>pQ,readRemoteConfigSessionBlobUploadMetadata:()=>RX,prepareRemoteConfigCoreIntegration:()=>EX,createRemoteConfigSessionMessagesArtifactUploader:()=>NX,buildRemoteConfigSessionBlobUploadMetadata:()=>dQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>lQ});import{buildRemoteConfigSessionBlobUploadMetadata as dQ,clearRemoteConfigSessionBlobUpload as bk,createClineTelemetryServiceConfig as yk,createSessionId as hk,createRemoteConfigSessionMessagesArtifactUploader as kk,prepareRemoteConfigRuntime as Ik,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as lQ,readRemoteConfigSessionBlobUploadMetadata as RX,registerRemoteConfigSessionBlobUpload as pQ}from"@cline/shared";function xk($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return H$(yk(Z)).telemetry}function NX(){let $=kk();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function EX($){let W=await Ik($),Z=xk(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=dQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||hk():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?pQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[lQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)bk(X)}}}var G_={};w(G_,{createTeamName:()=>nQ,DefaultRuntimeBuilder:()=>r6});import{hasRuntimeConfigExtension as sk}from"@cline/shared";import{nanoid as tk}from"nanoid";U1();var H_={};w(H_,{createLocalTeamStore:()=>SX,SqliteTeamStore:()=>B8,FileTeamStore:()=>MW});import{appendFileSync as gk,existsSync as l6,mkdirSync as j_,readdirSync as mk,readFileSync as X_,renameSync as vk,writeFileSync as ck}from"node:fs";import{join as wX}from"node:path";import{resolveTeamDataDir as uk}from"@cline/shared/storage";function Y_(){return new Date().toISOString()}function CX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function V_($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class MW{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??uk()}init(){this.ensureTeamDir()}listTeamNames(){if(!l6(this.teamDirPath))return[];return mk(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>l6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?V_(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!l6(Z))return[];return X_(Z,"utf8").split(`
607
- `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?V_(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),gk(this.historyPath($),`${JSON.stringify({ts:Y_(),eventType:W.type,payload:W})}
608
- `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:Y_(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;ck(j,`${JSON.stringify(Q,null,2)}
609
- `,"utf8"),vk(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!l6(this.teamDirPath))j_(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=wX(this.ensureTeamDir(),CX($));if(!l6(W))j_(W,{recursive:!0});return W}statePath($){return wX(this.ensureTeamDir(),CX($),"state.json")}historyPath($){return wX(this.ensureTeamDir(),CX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!l6(W))return;try{let Z=JSON.parse(X_(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as dk,mkdirSync as lk}from"node:fs";import{join as pk}from"node:path";import{safeJsonParse as B_}from"@cline/shared";import{loadSqliteDb as rk,nowIso as PX}from"@cline/shared/db";import{resolveDbDataDir as ik}from"@cline/shared/storage";function nk(){return ik()}function p6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function ak($){let W=B_($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function ok($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class B8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??nk()}init(){this.getRawDb()}ensureTeamDir(){if(!dk(this.teamDirPath))lk(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return pk(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=rk(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
605
+ `),$.end()}catch{$.destroy()}}function OX($,W){if(!$||!W)return!1;let Z=Buffer.from($,"utf8"),Q=Buffer.from(W,"utf8");return Z.length===Q.length&&qk(Z,Q)}function oD($,W){let Z=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${W.host}:${W.port}${W.pathname}: ${Q}`,j=Error(Z?`${J} (${Z})`:J);if(Z)$.code=Z,j.code=Z;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
606
+ Caused by: ${$.stack}`;return j}async function yk($){return await new Promise((W,Z)=>{let Q=Rk.createServer();Q.once("error",Z),Q.listen(0,$,()=>{let J=Q.address();if(!J||typeof J==="string"){Q.close(()=>Z(Error("Failed to resolve free port")));return}let j=J.port;Q.close((X)=>{if(X){Z(X);return}W(j)})})})}function hk($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var TX=new Map,sD="cline-hub-auth.",kk=30000;function qX($){return Array.isArray($)?$.join(","):$??""}function tD($){return $===32||$===9}function gQ($){let W=qX($).trim(),Z="bearer";if(W.length<=6||W.slice(0,6).toLowerCase()!=="bearer"||!tD(W.charCodeAt(6)))return null;let Q=7;while(Q<W.length&&tD(W.charCodeAt(Q)))Q+=1;return W.slice(Q).trim()||null}function Ik($){for(let W of qX($).split(",")){let Z=W.trim();if(Z.startsWith(sD))return Z.slice(sD.length).trim()||null}return null}function mQ($){let W=$.trim().toLowerCase();return W==="localhost"||W==="127.0.0.1"||W==="::1"||W==="[::1]"}function MX($){let W=qX($).trim();if(!W)return!1;try{return mQ(new zX(W).hostname)}catch{return!1}}async function V8($){let W=$.owner??j$(),Z=$.host??"127.0.0.1",Q=$.pathname??"/hub",J=$.port??O6(),j=J===0?await yk(Z):J,X=j,Y=L1(Z,j,Q),V=HQ(),B=BQ(),H=new l6($);await H.start();let G=new qW(new MW(H),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:iD,minClientProtocolVersion:aD,maxClientProtocolVersion:nD,capabilities:Nk,coreVersion:e4.version,buildId:V,pid:process.pid,startedAt:F},D=new Set,U,f,_=async()=>{if(f)return f;return f=(async()=>{if(U)clearInterval(U),U=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of K)L();if(K.clear(),await new Promise((L,C)=>{T.close((N)=>{if(N){C(N);return}L()})}),await new Promise((L,C)=>{R.close((N)=>{if(N){C(N);return}L()})}),await H.stop(),(await L0(W.discoveryPath))?.url===Y)await c0(W.discoveryPath)})(),f},R=Mk.createServer((O,L)=>{if((O.url??"/")==="/health"){let N=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Z,port:X,url:Y});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((O.url??"/")==="/status"){if(!OX(gQ(O.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}let N=JSON.stringify({hubId:H.getHubId(),...A,authToken:B,host:Z,port:X,url:Y,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(N);return}if((O.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(A));return}if(new zX(O.url??"/",`http://${Z}:${X}`).pathname==="/shutdown"&&O.method==="POST"){if(!OX(gQ(O.headers.authorization),B)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{_()});return}L.statusCode=404,L.end("Not found")}),T=new wk({noServer:!0});U=setInterval(()=>{for(let O of D){if(O.isAlive===!1){try{O.terminate?.()}catch{}D.delete(O);continue}O.isAlive=!1;try{O.ping?.()}catch{try{O.terminate?.()}catch{}D.delete(O)}}},kk),R.on("upgrade",(O,L,C)=>{if(new zX(O.url??"/",`http://${Z}:${X}`).pathname!==Q){L.destroy();return}if(!(OX(Ik(O.headers["sec-websocket-protocol"]),B)||mQ(Z)&&MX(O.headers.origin))){bk(L);return}try{T.handleUpgrade(O,L,C,(k)=>{let P=k;P.isAlive=!0,P.on("pong",()=>{P.isAlive=!0}),D.add(P);let r=G.attach(Pk(k));K.add(r),k.once("close",()=>{D.delete(P),r(),K.delete(r)})})}catch{Sk(L)}});try{await new Promise((O,L)=>{R.once("error",(C)=>{L(oD(C,{host:Z,port:j,pathname:Q}))}),R.listen(j,Z,()=>{let C=R.address();if(!C||typeof C==="string"){L(oD(Error("Failed to resolve hub port"),{host:Z,port:j,pathname:Q}));return}X=C.port,Y=L1(Z,X,Q),O()})})}catch(O){if(U)clearInterval(U),U=void 0;throw await H.stop().catch(()=>{return}),O}return await GQ(W.discoveryPath,{hubId:H.getHubId(),protocolVersion:iD,minClientProtocolVersion:aD,maxClientProtocolVersion:nD,capabilities:[...A.capabilities],coreVersion:e4.version,buildId:V,authToken:B,host:Z,port:X,url:Y,pid:process.pid,startedAt:F,updatedAt:F}),{host:Z,port:X,url:Y,authToken:B,close:_}}async function vQ($){let W=$.owner??j$(),Z=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",J=$.port??O6(),j=$.pathname??"/hub",X=L1(Q,J,j),Y=W.discoveryPath,V=(H)=>{if(!Z)p$(H.url,H.authToken);return H},B=TX.get(Y);if(B){let H=await B;if(H.url===X)return V({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await KQ(W.discoveryPath,async()=>{let H=await L0(W.discoveryPath);if(H?.url&&(H.url===X||$.allowPortFallback===!0)){let F=await X$(H.url,{authToken:H.authToken});if(F?.url&&Ek(F).compatible&&await C1(F.url,{authToken:H.authToken}))return V({url:F.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await c0(W.discoveryPath);let K=async(F)=>{let A=V8({...F,owner:W});TX.set(Y,A);try{let D=await A;return V({server:D,url:D.url,authToken:D.authToken,action:"started"})}catch(D){throw TX.delete(Y),D}};try{return await K($)}catch(F){if(!$.allowPortFallback||!hk(F))throw F;return await K({...$,port:0})}})}function $_(){return eD()==="production"?X1():u0()}function xk($){return eD()!=="production"&&!$}async function W_($){let W=j1({host:$.host,port:$.port,pathname:$.pathname});return await V8({...$,...W,owner:$_()})}async function Z_($){let W=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=j1({host:$.host,port:$.port,pathname:$.pathname});return await vQ({...$,...Z,allowPortFallback:$.allowPortFallback??xk(W),owner:$_()})}uQ();var j_={};w(j_,{registerRemoteConfigSessionBlobUpload:()=>pQ,readRemoteConfigSessionBlobUploadMetadata:()=>RX,prepareRemoteConfigCoreIntegration:()=>EX,createRemoteConfigSessionMessagesArtifactUploader:()=>NX,buildRemoteConfigSessionBlobUploadMetadata:()=>dQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>lQ});import{buildRemoteConfigSessionBlobUploadMetadata as dQ,clearRemoteConfigSessionBlobUpload as gk,createClineTelemetryServiceConfig as mk,createSessionId as vk,createRemoteConfigSessionMessagesArtifactUploader as ck,prepareRemoteConfigRuntime as uk,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as lQ,readRemoteConfigSessionBlobUploadMetadata as RX,registerRemoteConfigSessionBlobUpload as pQ}from"@cline/shared";function dk($,W){let Z=$.telemetry||W.telemetryService?{...W.telemetryService??{},...$.telemetry??{}}:void 0;if(!Z)return;return G$(mk(Z)).telemetry}function NX(){let $=ck();return{async uploadMessagesFile(W){await $.uploadMessagesFile(W)}}}async function EX($){let W=await uk($),Z=dk(W,$),Q=[W.pluginDefinition],J=W.claims?.subject,j=dQ(W.bundle?.remoteConfig,J),X;return{prepared:W,extensions:Q,telemetry:Z,applyToStartSessionInput(Y){let V=Y.config.extensions??[],B=Y.config.telemetry,H=j?Y.config.sessionId?.trim()||vk():Y.config.sessionId;if(H&&j)X=H;let G=H&&j?pQ(H,W.bundle?.remoteConfig,J):void 0,K=G?{...Y.sessionMetadata??{},[lQ]:G}:Y.sessionMetadata;return{...Y,...K?{sessionMetadata:K}:{},config:{...Y.config,...H?{sessionId:H}:{},extensions:[...V,...Q],telemetry:Z??B}}},async dispose(){if(X)gk(X)}}}var K_={};w(K_,{createTeamName:()=>nQ,DefaultRuntimeBuilder:()=>i6});import{hasRuntimeConfigExtension as QI}from"@cline/shared";import{nanoid as JI}from"nanoid";_1();var G_={};w(G_,{createLocalTeamStore:()=>SX,SqliteTeamStore:()=>B8,FileTeamStore:()=>RW});import{appendFileSync as lk,existsSync as p6,mkdirSync as X_,readdirSync as pk,readFileSync as Y_,renameSync as rk,writeFileSync as ik}from"node:fs";import{join as wX}from"node:path";import{resolveTeamDataDir as nk}from"@cline/shared/storage";function V_(){return new Date().toISOString()}function CX($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function B_($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class RW{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??nk()}init(){this.ensureTeamDir()}listTeamNames(){if(!p6(this.teamDirPath))return[];return pk(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>p6(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let W=this.readEnvelope($);return W?.teamState?B_(W.teamState):void 0}readHistory($,W=200){let Z=this.historyPath($);if(!p6(Z))return[];return Y_(Z,"utf8").split(`
607
+ `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,W)}loadRuntime($){let W=this.readEnvelope($);return{state:W?.teamState?B_(W.teamState):void 0,teammates:W?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,W){this.ensureTeamSubdir($),lk(this.historyPath($),`${JSON.stringify({ts:V_(),eventType:W.type,payload:W})}
608
+ `,"utf8")}persistRuntime($,W,Z){this.ensureTeamSubdir($);let Q={version:1,updatedAt:V_(),teamState:W,teammates:Z},J=this.statePath($),j=`${J}.tmp`;ik(j,`${JSON.stringify(Q,null,2)}
609
+ `,"utf8"),rk(j,J)}markInProgressRunsInterrupted($,W){let Z=this.readEnvelope($);if(!Z?.teamState?.runs?.length)return[];let Q=Z.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Q.length===0)return[];let J=new Date;return Z.teamState={...Z.teamState,runs:Z.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:W,endedAt:J}:j)},this.persistRuntime($,Z.teamState,Z.teammates),Q}ensureTeamDir(){if(!p6(this.teamDirPath))X_(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let W=wX(this.ensureTeamDir(),CX($));if(!p6(W))X_(W,{recursive:!0});return W}statePath($){return wX(this.ensureTeamDir(),CX($),"state.json")}historyPath($){return wX(this.ensureTeamDir(),CX($),"task-history.jsonl")}readEnvelope($){let W=this.statePath($);if(!p6(W))return;try{let Z=JSON.parse(Y_(W,"utf8"));if(Z?.version===1&&Z.teamState)return Z}catch{}return}}import{existsSync as ak,mkdirSync as ok}from"node:fs";import{join as sk}from"node:path";import{safeJsonParse as H_}from"@cline/shared";import{loadSqliteDb as tk,nowIso as PX}from"@cline/shared/db";import{resolveDbDataDir as ek}from"@cline/shared/storage";function $I(){return ek()}function r6($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function WI($){let W=H_($);if(!Array.isArray(W))return[];let Z=[];for(let Q of W){if(!Q||typeof Q!=="object")continue;let J=Q,j=J.agentId,X=J.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof X!=="string"||!X.trim())continue;let Y={agentId:j.trim(),rolePrompt:X};if(typeof J.modelId==="string"&&J.modelId.trim())Y.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))Y.maxIterations=Math.max(1,Math.floor(J.maxIterations));Z.push(Y)}return Z}function ZI($){return{...$,tasks:$.tasks.map((W)=>({...W,createdAt:new Date(W.createdAt),updatedAt:new Date(W.updatedAt)})),mailbox:$.mailbox.map((W)=>({...W,sentAt:new Date(W.sentAt),readAt:W.readAt?new Date(W.readAt):void 0})),missionLog:$.missionLog.map((W)=>({...W,ts:new Date(W.ts)})),runs:($.runs??[]).map((W)=>({...W,startedAt:new Date(W.startedAt),endedAt:W.endedAt?new Date(W.endedAt):void 0,nextAttemptAt:W.nextAttemptAt?new Date(W.nextAttemptAt):void 0,heartbeatAt:W.heartbeatAt?new Date(W.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),finalizedAt:W.finalizedAt?new Date(W.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((W)=>({...W,createdAt:new Date(W.createdAt),reviewedAt:W.reviewedAt?new Date(W.reviewedAt):void 0}))}}class B8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??$I()}init(){this.getRawDb()}ensureTeamDir(){if(!ak(this.teamDirPath))ok(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return sk(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=tk(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
610
610
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
611
611
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
612
612
  version INTEGER NOT NULL
@@ -690,8 +690,8 @@ Caused by: ${$.stack}`;return j}async function Ek($){return await new Promise((W
690
690
  version INTEGER NOT NULL DEFAULT 1,
691
691
  PRIMARY KEY(team_name, fragment_id)
692
692
  );
693
- `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[p6($)]);if(!W)return;let Z=B_(W.state_json);if(!Z)return;try{return ok(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[p6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=p6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?ak(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
694
- VALUES (?, ?, ?, ?, NULL, ?)`,[p6($),PX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=p6($),J=PX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
693
+ `)}run($,W=[]){return this.getRawDb().prepare($).run(...W)}queryOne($,W=[]){return this.getRawDb().prepare($).get(...W)??void 0}queryAll($,W=[]){return this.getRawDb().prepare($).all(...W)}withTransaction($){let W=this.getRawDb();W.exec("BEGIN IMMEDIATE;");try{$(),W.exec("COMMIT;")}catch(Z){try{W.exec("ROLLBACK;")}catch{}throw Z}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[r6($)]);if(!W)return;let Z=H_(W.state_json);if(!Z)return;try{return ZI(Z)}catch{return}}readHistory($,W=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[r6($),W]).flatMap((Z)=>{try{return[{eventType:Z.event_type,payload:JSON.parse(Z.payload_json),ts:Z.ts}]}catch{return[]}})}loadRuntime($){let W=r6($),Z=this.readState(W),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[W]),J=Q?WI(Q.teammates_json):[];return{state:Z,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,W,Z,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
694
+ VALUES (?, ?, ?, ?, NULL, ?)`,[r6($),PX(),W,JSON.stringify(Z),Q??null])}persistRuntime($,W,Z){let Q=r6($),J=PX();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
695
695
  VALUES (?, ?, ?, ?)
696
696
  ON CONFLICT(team_name) DO UPDATE SET
697
697
  state_json = excluded.state_json,
@@ -736,29 +736,29 @@ Caused by: ${$.stack}`;return j}async function Ek($){return await new Promise((W
736
736
  status = excluded.status,
737
737
  reviewed_by = excluded.reviewed_by,
738
738
  reviewed_at = excluded.reviewed_at,
739
- version = team_outcome_fragments.version + 1`,[Q,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,W){let Z=p6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=PX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
740
- WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function SX($={}){try{let W=new B8($);return W.init(),W}catch{let W=new MW({teamDir:$.teamDir});return W.init(),W}}function rQ($,W){return sk($,W)}function ek($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function $I($,W){return $.filter((Z)=>ek(Z.name,W))}function bX($,W){return n1($I($,W))}var WI={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function ZI($){let W=$.trim().toLowerCase();return WI[W]??W}function QI($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(ZI));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function nQ(){return`team-${tk(5)}`}function iQ($,W,Z,Q,J,j,X,Y){let V=a0[i1({mode:Z})],B=k8(W,Q,Z,J??h8);return bX(N2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function JI($){return iQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,jI,$.toolExecutors).some((W)=>W.name==="skills")}var jI=async()=>"";async function XI($){let W=Q0();if(!W$({filePath:W}))return{tools:[]};let Z=new u2({clientFactory:U6({settingsPath:W})}),Q;try{Q=await c2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>_6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function YI($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function VI($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function BI($){let W=a0[i1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class r6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=BI(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,D=R1(),U=[],f=W.teamName?.trim()||nQ(),_=W.sessionId?.trim()||f,R=K.enableSpawnAgent?R6({workspaceRoot:F}):{configs:[],errors:[]},T=R.configs.some((l)=>l.skills!==void 0),O=rQ(B,"rules"),L=rQ(B,"skills"),C=L||T,N=rQ(B,"workflows"),p=rQ(B,"plugins"),x=O||L||N,P=!1,r=Boolean(V),d=V,x1;for(let l of R.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!d&&(x||T))d=x$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(d)await d.start().catch(()=>{});let W2=K.enableTools&&L&&Boolean(d)&&d?.hasConfiguredSkills(W.skills)===!0&&JI({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),A$=d&&x?d.createExtension({includeRules:O,includeSkills:L,includeWorkflows:N,registerSkillsTool:W2,allowedSkillNames:W.skills}):void 0,I0=A$?[...Q??W.extensions??[],A$]:Q??W.extensions;if(K.enableTools){if(U.push(...iQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await XI(W.logger);U.push(...l.tools),x1=l.shutdown}}let U0,O1=K.enableAgentTeams?SX():void 0,A8=O1?.loadRuntime(_),V0=A8?.state,l0=A8?.teammates??[],V1=new Map(l0.map((l)=>[l.agentId,l])),y=W.sessionId||f,B1,k=[],W0=!1,T0=E$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature,maxIterations:W.maxIterations,hooks:Z,extensions:I0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(R.configs.length>0)U.push(...bX(N6({configProvider:T0,agents:R.configs,createSubAgentTools:(l)=>K.enableTools?QI(iQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&d?.createSkillsExecutor?d.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(y))this.teamRuntimeEntries.set(y,{delegatedAgentConfigProvider:T0});let M0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(y)??{delegatedAgentConfigProvider:T0};if(this.teamRuntimeEntries.set(y,l),U0=l.runtime,!U0){if(U0=new $8({teamName:f,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(B0)=>{if(G(B0),U0&&O1){if(B0.type==="teammate_spawned"&&B0.teammate?.rolePrompt){let g1={agentId:B0.agentId,rolePrompt:B0.teammate.rolePrompt,modelId:B0.teammate.modelId,maxIterations:B0.teammate.maxIterations};V1.set(g1.agentId,g1)}if(B0.type==="teammate_shutdown"&&!VI(B0.reason))V1.delete(B0.agentId);O1.handleTeamEvent(_,B0),O1.persistRuntime(_,U0.exportState(),Array.from(V1.values()))}}}),V0)U0.hydrateState(V0),W0=!0;l.runtime=U0}if(!P){if(!U0)return;P=!0;let B0=m8({runtime:U0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(V0),restoredTeammates:l0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(g1)=>{k=g1,B1?.addTools(g1)},createBaseTools:K.enableTools?()=>iQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:T0});if(W0)U0.recoverActiveRuns("runtime_recovered");if(B0.restoredFromPersistence)Y?.();U.push(...B0.tools)}return U0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(B0,g1)=>{return M0(),l.execute(B0,g1)}})}if(K.enableAgentTeams)M0();let pW=bX(U,A),e6=pW.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),U8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(y)?.runtime;if(!l)return;let B0=l.listTasks(),g1=B0.some((U$)=>U$.status==="in_progress"||U$.status==="pending"),nY=l.listRuns({}),If=nY.some((U$)=>U$.status==="running"||U$.status==="queued");if(g1||If){let U$=B0.filter((p0)=>p0.status==="in_progress"||p0.status==="pending").map((p0)=>`${p0.id} (${p0.status}): ${p0.title}`).join(", "),aY=nY.filter((p0)=>p0.status==="running"||p0.status==="queued").map((p0)=>`${p0.id} (${p0.status})`).join(", "),P7=[];if(U$)P7.push(`Unfinished tasks: ${U$}`);if(aY)P7.push(`Active runs: ${aY}`);return`[SYSTEM] You still have team obligations. ${P7.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,kf=e6?{requireCompletionTool:!0,...U8?{completionGuard:U8}:{}}:U8?{completionGuard:U8}:void 0;return{tools:pW,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:U0,teamRestoredFromPersistence:Boolean(V0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(y)?.delegatedAgentConfigProvider??T0,extensions:I0,completionPolicy:kf,registerLeadAgent:(l)=>{if(B1=l,k.length>0)l.addTools(n1(k,[...D]))},shutdown:async(l)=>{if(YI(U0,l),this.teamRuntimeEntries.delete(y),await x1?.(),!r)d?.stop()}}}}var F_={};w(F_,{requestDesktopToolApproval:()=>hX});import{mkdir as HI,readFile as GI,unlink as KI,writeFile as FI}from"node:fs/promises";import{join as K_}from"node:path";function AI($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function UI($){return new Promise((W)=>setTimeout(W,$))}async function yX($){try{await KI($)}catch{}}async function hX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await HI(Z,{recursive:!0});let J=AI(`${$.toolCallId}`),j=K_(Z,`${Q}.request.${J}.json`),X=K_(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await FI(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
741
- `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await GI(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([yX(X),yX(j)]),F}catch{}await UI(B)}return await yX(j),{approved:!1,reason:"Tool approval request timed out"}}U1();var E_={};w(E_,{uninstallMarketplaceSkill:()=>Z7,uninstallMarketplacePlugin:()=>Q7,uninstallMarketplaceMcpServerFromSettings:()=>$7,uninstallMarketplaceEntry:()=>oX,resolveMarketplaceMcpServerName:()=>PW,marketplaceEntryKey:()=>aX,isMarketplaceSkillInstalled:()=>W7,getMarketplaceSkillCandidates:()=>SW,getGlobalMarketplaceSkillPaths:()=>bW,findInstalledGlobalMarketplaceSkillName:()=>yW});import{spawn as tI}from"node:child_process";import{existsSync as R_,rmSync as eI}from"node:fs";import{homedir as $x,platform as Wx}from"node:os";import{dirname as Zx,join as M_}from"node:path";import{resolveClineDir as Qx,resolveMcpSettingsPath as Jx}from"@cline/shared/storage";var U_={};w(U_,{parseMcpInstallArgs:()=>RW,installMcpServer:()=>kX,buildMcpInstallTransport:()=>aQ});function DI($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function _I($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function fI($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function LI($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function A_($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function OI($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=fI(Q);if(W[J]=j,LI(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function aQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=A_({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=DI(J),{headers:X,warnings:Y}=OI(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return _I(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function RW($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...A_({parseTransport:!0,targetArgs:Z})}}function TI($,W,Z){D1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function kX($){let{name:W,transport:Z,warnings:Q}=aQ($);return TI(W,Z,$.settingsPath??Q0()),{name:W,status:"installed",transport:Z,warnings:Q}}U1();var q_={};w(q_,{uninstallPlugin:()=>wW});import{existsSync as n6,readdirSync as PI,readFileSync as SI,rmdirSync as bI,rmSync as yI,statSync as hI}from"node:fs";import{basename as j1,dirname as t$,extname as kI,isAbsolute as II,join as G$,relative as xI,resolve as i6,sep as vX}from"node:path";import{discoverPluginModulePaths as gI,resolvePluginConfigSearchPaths as mI}from"@cline/shared/storage";var L_={};w(L_,{syncPluginMcpServersToSettings:()=>NW,removePluginMcpServersFromSettings:()=>EW,disablePluginMcpServersInSettings:()=>mX});import{existsSync as zI,mkdirSync as qI,readFileSync as MI,writeFileSync as RI}from"node:fs";import{dirname as __,isAbsolute as NI,relative as EI,resolve as D_}from"node:path";function H8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function oQ($,W){let Z=EI(D_($),D_(W));return Z===""||!Z.startsWith("..")&&!NI(Z)}function IX($){if(!zI($))return{mcpServers:{}};try{let W=JSON.parse(MI($,"utf8"));if(H8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function xX($){if(H8($.mcpServers))return{...$.mcpServers};return{}}function gX($,W,Z){qI(__($),{recursive:!0}),RI($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
742
- `,"utf8")}function f_($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function tQ($){if(!H8($))return;let W=$.metadata;return H8(W)?W:void 0}function sQ($,W){let Z=tQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||oQ(W.pluginPath,J)||oQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||oQ(j,J)||oQ(J,j)))return!0;return!1}function wI($){let W=H8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:__($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function CI($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await a8({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function NW($){let W=$.settingsPath??Q0(),Z={mutations:[],failures:[]},Q;try{Q=await CI($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=IX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=xX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=$Q(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!sQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=wI({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:H8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=tQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&sQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{gX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function mX($){let W=$.settingsPath??Q0(),Z;try{Z=IX(W)}catch{return[]}let Q=xX(Z),J=f_($),j=[];for(let[X,Y]of Object.entries(Q)){if(!H8(Y)||!sQ(Y,J))continue;let V=tQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)gX(W,Z,Q);return j}function EW($){let W=$.settingsPath??Q0(),Z;try{Z=IX(W)}catch{return[]}let Q=xX(Z),J=f_($),j=[];for(let[X,Y]of Object.entries(Q)){if(!sQ(Y,J))continue;let V=tQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)gX(W,Z,Q);return j}var pX="_installed",vI="package",cI=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function cX($){return $.trim().toLowerCase()}function L1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function uI($){return $.replace(/-[0-9a-f]{12}$/i,"")}function uX($){let W=kI($);return W?$.slice(0,-W.length):$}function dX($){if(!n6($))return;try{let W=JSON.parse(SI($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function rX($,W){let Z=xI(W,$);return Z===""||!Z.startsWith("..")&&!II(Z)}function O_($){let Z=i6($).split(vX),Q=Z.lastIndexOf(pX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=cI.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(vX)||vX;return n6(Y)?Y:void 0}function eQ($){try{return PI($,{withFileTypes:!0})}catch{return[]}}function dI($){let W=G$($,pX);if(!n6(W))return[];let Z=[];for(let Q of eQ(W)){if(!Q.isDirectory())continue;let J=G$(W,Q.name);if(Q.name==="git"){for(let j of eQ(J)){if(!j.isDirectory())continue;let X=G$(J,j.name);for(let Y of eQ(X))if(Y.isDirectory())Z.push(G$(X,Y.name))}continue}for(let j of eQ(J))if(j.isDirectory())Z.push(G$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function T_($){try{return gI($)}catch{return[]}}function lX($){let W=T_($),Z=new Set;L1(Z,j1($)),L1(Z,uI(j1($))),L1(Z,dX(G$($,"package.json"))),L1(Z,dX(G$($,vI,"package.json")));for(let Q of W)L1(Z,j1(Q)),L1(Z,uX(j1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function lI($,W){let Z=i6($),Q=W.find((X)=>rX(Z,X));if(!Q)return;let J=t$(Z);while(J!==Q&&J!==t$(J)){if(n6(G$(J,"package.json")))return J;J=t$(J)}let j=j1(Z);if((j==="index.ts"||j==="index.js")&&t$(Z)!==Q)return t$(Z);return Z}function z_($,W){let Z=lI($,W);if(!Z)return;let Q=new Set;return L1(Q,j1($)),L1(Q,uX(j1($))),L1(Q,j1(Z)),L1(Q,uX(j1(Z))),L1(Q,dX(G$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function pI($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return mI(W).filter((Z)=>n6(Z))}function rI($){let W=new Map;for(let Z of $){for(let Q of dI(Z))W.set(Q,lX(Q));for(let Q of T_(Z)){let J=O_(Q);if(J){if(!W.has(J))W.set(J,lX(J));continue}let j=z_(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function iI($,W){let Z=cX(W);if(!Z)return!1;if(cX($.installPath)===Z)return!0;return $.names.some((Q)=>cX(Q)===Z)}function nI($,W,Z){let Q=i6($);for(let j of W){if(rX(Q,j.installPath))return j;if(j.entryPaths.some((X)=>i6(X)===Q))return j}let J=O_(Q);if(J)return lX(J);if(n6(Q))return z_(Q,Z);return}function aI($){let W=N0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=i6(J);if(rX(j,$.installPath))return!1;return!$.entryPaths.some((X)=>i6(X)===j)});if(Q.length===Z.length)return;M1({...W,disabledPlugins:Q})}function oI($){let W=t$($);while(W!==t$(W)&&j1(W)!==pX){try{bI(W)}catch{return}W=t$(W)}}function sI($){return`${$.names[0]??j1($.installPath)} at ${$.installPath}`}async function wW($){let W=pI($),Z=rI(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=nI(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>iI(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(sI).join(", ")}`);j=Y[0]}let X=hI(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(EW({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),yI(j.installPath,{recursive:X.isDirectory(),force:!0}),aI(j),j.installed)oI(j.installPath);return{name:J||j.names[0]||j1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var iX=120000,CW=12000,jx=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Xx=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Yx=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,Vx=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function nX($){return $.install?.args??[]}function Bx(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||$x()}function Hx($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function Gx($){return Hx($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function N_($){return $.split(/\r?\n/).map((W)=>{if(!jx.test(W))return W;return W.replace(Xx,"$1[redacted]").replace(Yx,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(Vx,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
743
- `).slice(-CW)}function Kx($){let W=N_([$.stdout,$.stderr].filter(Boolean).join(`
744
- `)).trim();return W.length>0?W:void 0}function Fx($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function Ax($,W){return[$,...W].map((Z)=>Fx(N_(Z).trim())).join(" ")}var Ux=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=tI($,W,{env:process.env,shell:Wx()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},iX+5000),H=setTimeout(()=>{j=!0,V+=`
745
- Timed out after ${iX/1000}s.`,X.kill("SIGTERM")},iX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>CW*2)Y=Y.slice(-CW)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>CW*2)V=V.slice(-CW)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function aX($){return`${$.type}:${$.id}`}function PW($){let W=nX($);if(W.length===0)throw Error("Marketplace install args are required.");return RW(W).name}function $7($,W={}){let Z=PW($),Q=W.mcpSettingsPath??Jx(),J=D1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function SW($){let W=new Set,Z=(J)=>{let j=Gx(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=nX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function bW($){return[M_(Qx(),"skills",$,"SKILL.md"),M_(Bx(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function yW($){if($.type!=="skill")return;return SW($).find((W)=>bW(W).some((Z)=>R_(Z)))}function W7($){return yW($)!==void 0}function Dx($){let W=[];if($.type!=="skill")return W;for(let Z of SW($))for(let Q of bW(Z)){if(!R_(Q))continue;let J=Zx(Q);eI(J,{recursive:!0,force:!0}),W.push(J)}return W}async function Z7($,W={}){let Z=yW($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=Ax(Q,J),X=W.spawnCommand??Ux,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
739
+ version = team_outcome_fragments.version + 1`,[Q,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,W){let Z=r6($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Z]);if(Q.length===0)return[];let J=PX();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
740
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[W,J,Z]),Q.map((j)=>j.run_id)}handleTeamEvent($,W){this.appendTeamEvent($,W.type,W)}}function SX($={}){try{let W=new B8($);return W.init(),W}catch{let W=new RW({teamDir:$.teamDir});return W.init(),W}}function rQ($,W){return QI($,W)}function jI($,W){let Z=W?.["*"]??{},Q=W?.[$]??{};return{...Z,...Q}.enabled!==!1}function XI($,W){return $.filter((Z)=>jI(Z.name,W))}function bX($,W){return a1(XI($,W))}var YI={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function VI($){let W=$.trim().toLowerCase();return YI[W]??W}function BI($,W){if(W.tools===void 0)return $;let Z=new Set(W.tools.map(VI));if(W.skills!==void 0)Z.add("skills");return $.filter((Q)=>Z.has(Q.name))}function nQ(){return`team-${JI(5)}`}function iQ($,W,Z,Q,J,j,X,Y){let V=t0[n1({mode:Z})],B=I8(W,Q,Z,J??k8);return bX(N2({cwd:$,...V,enableSkills:!!X,...B,executors:{...X?{skills:X}:{},...Y??{}}}),j)}function HI($){return iQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,GI,$.toolExecutors).some((W)=>W.name==="skills")}var GI=async()=>"";async function KI($){let W=Q0();if(!Z$({filePath:W}))return{tools:[]};let Z=new u2({clientFactory:D6({settingsPath:W})}),Q;try{Q=await c2(Z,{filePath:W})}catch(Y){await Z.dispose().catch(()=>{});let V=Y instanceof Error?Y.message:String(Y);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=Q.filter((Y)=>Y.disabled!==!0),j=await Promise.allSettled(J.map((Y)=>f6({serverName:Y.name,provider:Z}))),X=[];for(let[Y,V]of j.entries())if(V.status==="fulfilled")X.push(...V.value);else{let B=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[Y].name}", skipping: ${B}`)}return{tools:X,shutdown:async()=>{await Z.dispose()}}}function FI($,W){if(!$)return;for(let Z of $.getTeammateIds())try{$.shutdownTeammate(Z,W)}catch{}}function AI($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function UI($){let W=t0[n1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??W.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??W.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class i6{teamRuntimeEntries=new Map;async build($){let{config:W,hooks:Z,extensions:Q,logger:J,telemetry:j,createSpawnTool:X,onTeamRestored:Y,userInstructionService:V,configExtensions:B,toolExecutors:H}=$,G=$.onTeamEvent??(()=>{}),K=UI(W),F=W.workspaceRoot??W.cwd,A=$.toolPolicies??W.toolPolicies,D=N1(),U=[],f=W.teamName?.trim()||nQ(),_=W.sessionId?.trim()||f,R=K.enableSpawnAgent?N6({workspaceRoot:F}):{configs:[],errors:[]},T=R.configs.some((l)=>l.skills!==void 0),O=rQ(B,"rules"),L=rQ(B,"skills"),C=L||T,N=rQ(B,"workflows"),p=rQ(B,"plugins"),k=O||L||N,P=!1,r=Boolean(V),c=V,g1;for(let l of R.errors)(J??W.logger)?.log?.(`[agents] Failed to load agent config at ${l.path}: ${l.error.message}`);if(!c&&(k||T))c=g$({skills:C?{workspacePath:F,includePluginSkills:p,pluginSkillDirectories:p?$.pluginSkillDirectories:void 0,pluginPaths:W.pluginPaths,cwd:W.cwd}:{workspacePath:F},rules:{workspacePath:W.cwd},workflows:{workspacePath:W.cwd}});if(c)await c.start().catch(()=>{});let Z2=K.enableTools&&L&&Boolean(c)&&c?.hasConfiguredSkills(W.skills)===!0&&HI({cwd:W.cwd,providerId:W.providerId,mode:K.mode,modelId:W.modelId,toolRoutingRules:W.toolRoutingRules,toolPolicies:A,toolExecutors:H}),A8=c&&k?c.createExtension({includeRules:O,includeSkills:L,includeWorkflows:N,registerSkillsTool:Z2,allowedSkillNames:W.skills}):void 0,g0=A8?[...Q??W.extensions??[],A8]:Q??W.extensions;if(K.enableTools){if(U.push(...iQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H)),!K.disableMcpSettingsTools){let l=await KI(W.logger);U.push(...l.tools),g1=l.shutdown}}let A0,r0=K.enableAgentTeams?SX():void 0,U8=r0?.loadRuntime(_),S0=U8?.state,G1=U8?.teammates??[],y0=new Map(G1.map((l)=>[l.agentId,l])),O0=W.sessionId||f,v,i0=[],b=!1,$0=w$({providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey??"",baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,reasoningEffort:W.reasoningEffort,thinkingBudgetTokens:W.thinkingBudgetTokens,maxTokensPerTurn:W.maxTokensPerTurn,temperature:W.temperature,maxIterations:W.maxIterations,hooks:Z,extensions:g0,logger:J??W.logger,telemetry:$.telemetry??W.telemetry,workspaceMetadata:W.workspaceMetadata});if(K.enableSpawnAgent){if(R.configs.length>0)U.push(...bX(E6({configProvider:$0,agents:R.configs,createSubAgentTools:(l)=>K.enableTools?BI(iQ(W.cwd,l.providerId??W.providerId,K.mode,l.modelId??W.modelId,W.toolRoutingRules,A,l.skills!==void 0&&c?.createSkillsExecutor?c.createSkillsExecutor(l.skills):void 0,H),l):[],hookErrorMode:W.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(O0))this.teamRuntimeEntries.set(O0,{delegatedAgentConfigProvider:$0});let q0=()=>{if(!K.enableAgentTeams)return;let l=this.teamRuntimeEntries.get(O0)??{delegatedAgentConfigProvider:$0};if(this.teamRuntimeEntries.set(O0,l),A0=l.runtime,!A0){if(A0=new $8({teamName:f,leadAgentId:W.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(V0)=>{if(G(V0),A0&&r0){if(V0.type==="teammate_spawned"&&V0.teammate?.rolePrompt){let m1={agentId:V0.agentId,rolePrompt:V0.teammate.rolePrompt,modelId:V0.teammate.modelId,maxIterations:V0.teammate.maxIterations};y0.set(m1.agentId,m1)}if(V0.type==="teammate_shutdown"&&!AI(V0.reason))y0.delete(V0.agentId);r0.handleTeamEvent(_,V0),r0.persistRuntime(_,A0.exportState(),Array.from(y0.values()))}}}),S0)A0.hydrateState(S0),b=!0;l.runtime=A0}if(!P){if(!A0)return;P=!0;let V0=v8({runtime:A0,leadAgentId:W.sessionId||"lead",restoredFromPersistence:Boolean(S0),restoredTeammates:G1,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(m1)=>{i0=m1,v?.addTools(m1)},createBaseTools:K.enableTools?()=>iQ(W.cwd,W.providerId,K.mode,W.modelId,W.toolRoutingRules,A,void 0,H):void 0,teammateConfigProvider:$0});if(b)A0.recoverActiveRuns("runtime_recovered");if(V0.restoredFromPersistence)Y?.();U.push(...V0.tools)}return A0};if(K.enableSpawnAgent&&X){let l=X();U.push({...l,execute:async(V0,m1)=>{return q0(),l.execute(V0,m1)}})}if(K.enableAgentTeams)q0();let h0=bX(U,A),$4=h0.some((l)=>l.name==="submit_and_exit"&&l.lifecycle?.completesRun===!0),D8=K.enableAgentTeams?()=>{let l=this.teamRuntimeEntries.get(O0)?.runtime;if(!l)return;let V0=l.listTasks(),m1=V0.some((U$)=>U$.status==="in_progress"||U$.status==="pending"),nY=l.listRuns({}),xf=nY.some((U$)=>U$.status==="running"||U$.status==="queued");if(m1||xf){let U$=V0.filter((n0)=>n0.status==="in_progress"||n0.status==="pending").map((n0)=>`${n0.id} (${n0.status}): ${n0.title}`).join(", "),aY=nY.filter((n0)=>n0.status==="running"||n0.status==="queued").map((n0)=>`${n0.id} (${n0.status})`).join(", "),P7=[];if(U$)P7.push(`Unfinished tasks: ${U$}`);if(aY)P7.push(`Active runs: ${aY}`);return`[SYSTEM] You still have team obligations. ${P7.join(". ")}. Use team_run_task to delegate work, or team_task with action=complete to mark tasks done, or team_await_runs to wait for active runs. Do NOT stop until all tasks are completed.`}return}:void 0,If=$4?{requireCompletionTool:!0,...D8?{completionGuard:D8}:{}}:D8?{completionGuard:D8}:void 0;return{tools:h0,logger:J??W.logger,telemetry:j??W.telemetry,teamRuntime:A0,teamRestoredFromPersistence:Boolean(S0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(O0)?.delegatedAgentConfigProvider??$0,extensions:g0,completionPolicy:If,registerLeadAgent:(l)=>{if(v=l,i0.length>0)l.addTools(a1(i0,[...D]))},shutdown:async(l)=>{if(FI(A0,l),this.teamRuntimeEntries.delete(O0),await g1?.(),!r)c?.stop()}}}}var A_={};w(A_,{requestDesktopToolApproval:()=>hX});import{mkdir as DI,readFile as _I,unlink as fI,writeFile as LI}from"node:fs/promises";import{join as F_}from"node:path";function OI($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function TI($){return new Promise((W)=>setTimeout(W,$))}async function yX($){try{await fI($)}catch{}}async function hX($,W={}){let Z=W.approvalDir?.trim(),Q=W.sessionId?.trim();if(!Z||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await DI(Z,{recursive:!0});let J=OI(`${$.toolCallId}`),j=F_(Z,`${Q}.request.${J}.json`),X=F_(Z,`${Q}.decision.${J}.json`),Y=W.nowIso??(()=>new Date().toISOString());await LI(j,`${JSON.stringify({requestId:J,sessionId:Q,createdAt:Y(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
741
+ `,"utf8");let V=W.timeoutMs??300000,B=W.pollIntervalMs??200,H=Date.now();while(Date.now()-H<V){try{let G=await _I(X,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([yX(X),yX(j)]),F}catch{}await TI(B)}return await yX(j),{approved:!1,reason:"Tool approval request timed out"}}_1();var w_={};w(w_,{uninstallMarketplaceSkill:()=>Z7,uninstallMarketplacePlugin:()=>Q7,uninstallMarketplaceMcpServerFromSettings:()=>$7,uninstallMarketplaceEntry:()=>oX,resolveMarketplaceMcpServerName:()=>SW,marketplaceEntryKey:()=>aX,isMarketplaceSkillInstalled:()=>W7,getMarketplaceSkillCandidates:()=>bW,getGlobalMarketplaceSkillPaths:()=>yW,findInstalledGlobalMarketplaceSkillName:()=>hW});import{spawn as Jx}from"node:child_process";import{existsSync as N_,rmSync as jx}from"node:fs";import{homedir as Xx,platform as Yx}from"node:os";import{dirname as Vx,join as R_}from"node:path";import{resolveClineDir as Bx,resolveMcpSettingsPath as Hx}from"@cline/shared/storage";var D_={};w(D_,{parseMcpInstallArgs:()=>NW,installMcpServer:()=>kX,buildMcpInstallTransport:()=>aQ});function zI($){let W=($??"stdio").trim();if(W==="http"||W==="streamable-http")return"streamableHttp";if(W==="stdio"||W==="sse"||W==="streamableHttp")return W;throw Error(`Unsupported MCP transport "${W}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function qI($){let W;try{W=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(W.protocol!=="http:"&&W.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function MI($){let W=$.indexOf(":");if(W<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Z=$.slice(0,W).trim(),Q=$.slice(W+1).trim();if(!Z||!Q)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Z))throw Error(`Invalid MCP header name "${Z}".`);return[Z,Q]}function RI($){let W=$.indexOf("<");return W>=0&&$.indexOf(">",W+1)>W+1}function U_($){let W=[...$.headers??[]],Z=[],Q=$.transport,J=$.targetArgs??[];for(let j=0;j<J.length;j++){let X=J[j];if($.parseTransport&&X==="--transport"){let Y=J[j+1];if(!Y)throw Error("--transport requires a value");Q=Y,j++;continue}if($.parseTransport&&X?.startsWith("--transport=")){Q=X.slice(12);continue}if(X==="--header"){let Y=J[j+1];if(!Y)throw Error("--header requires a value");W.push(Y),j++;continue}if(X?.startsWith("--header=")){W.push(X.slice(9));continue}Z.push(X)}return{headers:W,targetArgs:Z,transport:Q}}function NI($){if($.length===0)return{warnings:[]};let W={},Z=[];for(let Q of $){let[J,j]=MI(Q);if(W[J]=j,RI(j))Z.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:W,warnings:Z}}function aQ($){let W=$.name.trim();if(!W)throw Error("MCP server name is required");let{headers:Z,targetArgs:Q,transport:J}=U_({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),j=zI(J),{headers:X,warnings:Y}=NI(Z);if(j==="stdio"){if(Z.length>0)throw Error("Stdio MCP installs do not support request headers.");let[B,...H]=Q;if(!B?.trim())throw Error("Stdio MCP install requires a command after the server name, for example: cline mcp install fs --yes -- npx -y @modelcontextprotocol/server-filesystem /tmp");return{name:W,transport:{type:j,command:B,args:H.length>0?H:void 0},warnings:Y}}if(Q.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=Q[0]?.trim()??"";return qI(V),{name:W,transport:X?{type:j,url:V,headers:X}:{type:j,url:V},warnings:Y}}function NW($){let[W,...Z]=$;if(!W)throw Error("Marketplace MCP install args must start with a server name.");return{name:W,...U_({parseTransport:!0,targetArgs:Z})}}function EI($,W,Z){f1(Z,(Q)=>{let J=Q.mcpServers,j=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};j[$]={transport:W},Q.mcpServers=j})}function kX($){let{name:W,transport:Z,warnings:Q}=aQ($);return EI(W,Z,$.settingsPath??Q0()),{name:W,status:"installed",transport:Z,warnings:Q}}_1();var M_={};w(M_,{uninstallPlugin:()=>CW});import{existsSync as a6,readdirSync as II,readFileSync as xI,rmdirSync as gI,rmSync as mI,statSync as vI}from"node:fs";import{basename as V1,dirname as e$,extname as cI,isAbsolute as uI,join as K$,relative as dI,resolve as n6,sep as vX}from"node:path";import{discoverPluginModulePaths as lI,resolvePluginConfigSearchPaths as pI}from"@cline/shared/storage";var O_={};w(O_,{syncPluginMcpServersToSettings:()=>EW,removePluginMcpServersFromSettings:()=>wW,disablePluginMcpServersInSettings:()=>mX});import{existsSync as wI,mkdirSync as CI,readFileSync as PI,writeFileSync as SI}from"node:fs";import{dirname as f_,isAbsolute as bI,relative as yI,resolve as __}from"node:path";function H8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function oQ($,W){let Z=yI(__($),__(W));return Z===""||!Z.startsWith("..")&&!bI(Z)}function IX($){if(!wI($))return{mcpServers:{}};try{let W=JSON.parse(PI($,"utf8"));if(H8(W))return W}catch(W){throw Error(`Invalid MCP settings at "${$}": ${W instanceof Error?W.message:String(W)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function xX($){if(H8($.mcpServers))return{...$.mcpServers};return{}}function gX($,W,Z){CI(f_($),{recursive:!0}),SI($,`${JSON.stringify({...W,mcpServers:Z},null,2)}
742
+ `,"utf8")}function L_($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((W)=>W.trim()).filter((W)=>W.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((W)=>W.trim()).filter((W)=>W.length>0))]}}function tQ($){if(!H8($))return;let W=$.metadata;return H8(W)?W:void 0}function sQ($,W){let Z=tQ($);if(!Z||Z.source!=="plugin")return!1;let Q=typeof Z.pluginName==="string"?Z.pluginName:typeof Z.plugin==="string"?Z.plugin:void 0,J=typeof Z.pluginPath==="string"?Z.pluginPath:void 0;if(W.pluginName&&Q===W.pluginName){if(!W.pluginPath||J===W.pluginPath)return!0}if(J&&W.pluginPath&&(J===W.pluginPath||oQ(W.pluginPath,J)||oQ(J,W.pluginPath)))return!0;if(Q&&W.pluginNames?.some((j)=>j===Q))return!0;if(J&&W.pluginPaths?.some((j)=>J===j||oQ(j,J)||oQ(J,j)))return!0;return!1}function hI($){let W=H8($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:f_($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...W,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function kI($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let W=await o8({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Z=[],Q=[],J=(W.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of W.extensions??[]){let X=j.__clinePluginPath;if(!X)continue;if(!j.setup){Z.push({pluginName:j.name,pluginPath:X});continue}let Y=[],V={registerTool:(B)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(B)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');Y.push(B)}};try{await j.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(B){J.push({pluginPath:X,pluginName:j.name,message:B instanceof Error?B.message:String(B)});continue}Z.push({pluginName:j.name,pluginPath:X});for(let B of Y)Q.push({pluginName:j.name,pluginPath:X,server:{...B,metadata:{...B.metadata??{},source:"plugin",pluginName:j.name,pluginPath:X}}})}return{plugins:Z,servers:Q,failures:J}}finally{await W.shutdown().catch(()=>{})}}async function EW($){let W=$.settingsPath??Q0(),Z={mutations:[],failures:[]},Q;try{Q=await kI($)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}Z.failures.push(...Q.failures);let J;try{J=IX(W)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)});return Z}let j=xX(J),X=new Map,Y=new Map;for(let B of Q.plugins)X.set(B.pluginPath,new Set),Y.set(B.pluginPath,B.pluginName);let V=$Q(Q.servers.map((B)=>({server:B.server,owner:B,ownerLabel:B.pluginName})));for(let B of V){let H=B.owner;if(!X.has(H.pluginPath))X.set(H.pluginPath,new Set);if(B.name)X.get(H.pluginPath)?.add(B.name);if(!B.registration){Z.mutations.push({name:B.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:B.loadError??"invalid MCP server registration"});continue}let G=j[B.registration.name];if(G!==void 0){if(!sQ(G,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[B.registration.name]=hI({registration:B.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:H8(G)?G:void 0}),Z.mutations.push({name:B.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:G===void 0?"created":"updated"})}for(let[B,H]of Object.entries(j)){let G=tQ(H),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=X.get(K);if(F&&sQ(H,{pluginPath:K})&&!F.has(B))delete j[B],Z.mutations.push({name:B,pluginName:typeof G?.pluginName==="string"?G.pluginName:Y.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Z.mutations.some((B)=>B.action!=="skipped"))try{gX(W,J,j)}catch(B){for(let H of $.pluginPaths)Z.failures.push({pluginPath:H,message:B instanceof Error?B.message:String(B)})}return Z}function mX($){let W=$.settingsPath??Q0(),Z;try{Z=IX(W)}catch{return[]}let Q=xX(Z),J=L_($),j=[];for(let[X,Y]of Object.entries(Q)){if(!H8(Y)||!sQ(Y,J))continue;let V=tQ(Y);Q[X]={...Y,disabled:!0},j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(j.length>0)gX(W,Z,Q);return j}function wW($){let W=$.settingsPath??Q0(),Z;try{Z=IX(W)}catch{return[]}let Q=xX(Z),J=L_($),j=[];for(let[X,Y]of Object.entries(Q)){if(!sQ(Y,J))continue;let V=tQ(Y);delete Q[X],j.push({name:X,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(j.length>0)gX(W,Z,Q);return j}var pX="_installed",rI="package",iI=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function cX($){return $.trim().toLowerCase()}function T1($,W){let Z=W?.trim();if(!Z)return;$.add(Z)}function nI($){return $.replace(/-[0-9a-f]{12}$/i,"")}function uX($){let W=cI($);return W?$.slice(0,-W.length):$}function dX($){if(!a6($))return;try{let W=JSON.parse(xI($,"utf8"));return typeof W.name==="string"?W.name.trim():void 0}catch{return}}function rX($,W){let Z=dI(W,$);return Z===""||!Z.startsWith("..")&&!uI(Z)}function T_($){let Z=n6($).split(vX),Q=Z.lastIndexOf(pX);if(Q<0)return;let J=Z[Q+1];if(!J)return;let j=iI.get(J)??1,X=Q+2+j;if(Z.length<X)return;let Y=Z.slice(0,X).join(vX)||vX;return a6(Y)?Y:void 0}function eQ($){try{return II($,{withFileTypes:!0})}catch{return[]}}function aI($){let W=K$($,pX);if(!a6(W))return[];let Z=[];for(let Q of eQ(W)){if(!Q.isDirectory())continue;let J=K$(W,Q.name);if(Q.name==="git"){for(let j of eQ(J)){if(!j.isDirectory())continue;let X=K$(J,j.name);for(let Y of eQ(X))if(Y.isDirectory())Z.push(K$(X,Y.name))}continue}for(let j of eQ(J))if(j.isDirectory())Z.push(K$(J,j.name))}return Z.sort((Q,J)=>Q.localeCompare(J))}function z_($){try{return lI($)}catch{return[]}}function lX($){let W=z_($),Z=new Set;T1(Z,V1($)),T1(Z,nI(V1($))),T1(Z,dX(K$($,"package.json"))),T1(Z,dX(K$($,rI,"package.json")));for(let Q of W)T1(Z,V1(Q)),T1(Z,uX(V1(Q)));return{installPath:$,entryPaths:W,names:[...Z].sort((Q,J)=>Q.localeCompare(J)),installed:!0}}function oI($,W){let Z=n6($),Q=W.find((X)=>rX(Z,X));if(!Q)return;let J=e$(Z);while(J!==Q&&J!==e$(J)){if(a6(K$(J,"package.json")))return J;J=e$(J)}let j=V1(Z);if((j==="index.ts"||j==="index.js")&&e$(Z)!==Q)return e$(Z);return Z}function q_($,W){let Z=oI($,W);if(!Z)return;let Q=new Set;return T1(Q,V1($)),T1(Q,uX(V1($))),T1(Q,V1(Z)),T1(Q,uX(V1(Z))),T1(Q,dX(K$(Z,"package.json"))),{installPath:Z,entryPaths:[$],names:[...Q].sort((J,j)=>J.localeCompare(j)),installed:!1}}function sI($){let W=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return pI(W).filter((Z)=>a6(Z))}function tI($){let W=new Map;for(let Z of $){for(let Q of aI(Z))W.set(Q,lX(Q));for(let Q of z_(Z)){let J=T_(Q);if(J){if(!W.has(J))W.set(J,lX(J));continue}let j=q_(Q,$);if(j)W.set(j.installPath,j)}}return[...W.values()].sort((Z,Q)=>Z.installPath.localeCompare(Q.installPath))}function eI($,W){let Z=cX(W);if(!Z)return!1;if(cX($.installPath)===Z)return!0;return $.names.some((Q)=>cX(Q)===Z)}function $x($,W,Z){let Q=n6($);for(let j of W){if(rX(Q,j.installPath))return j;if(j.entryPaths.some((X)=>n6(X)===Q))return j}let J=T_(Q);if(J)return lX(J);if(a6(Q))return q_(Q,Z);return}function Wx($){let W=R0(),Z=W.disabledPlugins;if(!Z?.length)return;let Q=Z.filter((J)=>{let j=n6(J);if(rX(j,$.installPath))return!1;return!$.entryPaths.some((X)=>n6(X)===j)});if(Q.length===Z.length)return;R1({...W,disabledPlugins:Q})}function Zx($){let W=e$($);while(W!==e$(W)&&V1(W)!==pX){try{gI(W)}catch{return}W=e$(W)}}function Qx($){return`${$.names[0]??V1($.installPath)} at ${$.installPath}`}async function CW($){let W=sI($),Z=tI(W),Q=$.path?.trim(),J=$.name?.trim(),j;if(Q){if(j=$x(Q,Z,W),!j)throw Error(`No plugin found at ${Q}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let Y=Z.filter((V)=>eI(V,J));if(Y.length===0)throw Error(`No plugin found matching "${J}"`);if(Y.length>1)throw Error(`Multiple plugins match "${J}": ${Y.map(Qx).join(", ")}`);j=Y[0]}let X=vI(j.installPath,{throwIfNoEntry:!1});if(!X)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(wW({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),mI(j.installPath,{recursive:X.isDirectory(),force:!0}),Wx(j),j.installed)Zx(j.installPath);return{name:J||j.names[0]||V1(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var iX=120000,PW=12000,Gx=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Kx=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Fx=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,Ax=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function nX($){return $.install?.args??[]}function Ux(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||Xx()}function Dx($){let W=0,Z=$.length;while(W<Z&&($[W]==="."||$[W]==="-"))W++;while(Z>W&&($[Z-1]==="."||$[Z-1]==="-"))Z--;return $.slice(W,Z)}function _x($){return Dx($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function E_($){return $.split(/\r?\n/).map((W)=>{if(!Gx.test(W))return W;return W.replace(Kx,"$1[redacted]").replace(Fx,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(Ax,"$1 [redacted]").replace(/((?:^|[^\w])(?:api\s+key|access\s+token|refresh\s+token|auth(?:orization)?\s+token|secret|password|credential)\s+(?:is\s+)?)(\S+)/gi,"$1[redacted]")}).join(`
743
+ `).slice(-PW)}function fx($){let W=E_([$.stdout,$.stderr].filter(Boolean).join(`
744
+ `)).trim();return W.length>0?W:void 0}function Lx($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function Ox($,W){return[$,...W].map((Z)=>Lx(E_(Z).trim())).join(" ")}var Tx=async($,W)=>new Promise((Z,Q)=>{let J=!1,j=!1,X=Jx($,W,{env:process.env,shell:Yx()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V="",B=setTimeout(()=>{if(!J)X.kill("SIGKILL")},iX+5000),H=setTimeout(()=>{j=!0,V+=`
745
+ Timed out after ${iX/1000}s.`,X.kill("SIGTERM")},iX);B.unref?.(),H.unref?.(),X.stdout?.on("data",(G)=>{if(Y+=String(G),Y.length>PW*2)Y=Y.slice(-PW)}),X.stderr?.on("data",(G)=>{if(V+=String(G),V.length>PW*2)V=V.slice(-PW)}),X.once("error",(G)=>{clearTimeout(H),clearTimeout(B),Q(G)}),X.once("close",(G,K)=>{J=!0,clearTimeout(H),clearTimeout(B),Z({exitCode:j?124:G??(K==="SIGINT"?130:1),stdout:Y,stderr:V})})});function aX($){return`${$.type}:${$.id}`}function SW($){let W=nX($);if(W.length===0)throw Error("Marketplace install args are required.");return NW(W).name}function $7($,W={}){let Z=SW($),Q=W.mcpSettingsPath??Hx(),J=f1(Q,(j)=>{let X=j.mcpServers&&typeof j.mcpServers==="object"&&!Array.isArray(j.mcpServers)?j.mcpServers:{},Y=Object.hasOwn(X,Z);if(Y)delete X[Z];return j.mcpServers=X,Y});return{name:Z,deleted:J}}function bW($){let W=new Set,Z=(J)=>{let j=_x(J??"");if(j&&j!=="skill")W.add(j)};Z($.id),Z($.name);let Q=nX($);for(let J=0;J<Q.length;J++){let j=Q[J];if((j==="--skill"||j==="-s")&&Q[J+1]){Z(Q[J+1]),J++;continue}let X=j.split("@").at(1);if(X)Z(X)}return[...W]}function yW($){return[R_(Bx(),"skills",$,"SKILL.md"),R_(Ux(),".agents","skills",$,"SKILL.md")].filter((W,Z,Q)=>Q.indexOf(W)===Z)}function hW($){if($.type!=="skill")return;return bW($).find((W)=>yW(W).some((Z)=>N_(Z)))}function W7($){return hW($)!==void 0}function zx($){let W=[];if($.type!=="skill")return W;for(let Z of bW($))for(let Q of yW(Z)){if(!N_(Q))continue;let J=Vx(Q);jx(J,{recursive:!0,force:!0}),W.push(J)}return W}async function Z7($,W={}){let Z=hW($);if(!Z)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let Q="npx",J=["-y","skills@latest","remove",Z,"-g","-y"],j=Ox(Q,J),X=W.spawnCommand??Tx,Y;try{Y=await X(Q,J)}catch(H){throw Error(`Failed to start ${$.name??$.id} uninstall command:
746
746
  ${j}
747
- ${H instanceof Error?H.message:String(H)}`)}let V=Kx(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
747
+ ${H instanceof Error?H.message:String(H)}`)}let V=fx(Y);if(Y.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${Y.exitCode}.
748
748
  Command:
749
749
  ${j}${V?`
750
750
 
751
- ${V}`:""}`);let B=Dx($);if(W7($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
752
- `)||void 0}}async function Q7($,W={}){let[Z]=nX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await wW({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
753
- `)}}async function oX($,W={}){if($.type==="mcp"){let Z=PW($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else $7($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return Z7($,W);if($.type==="plugin")return Q7($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var c_={};w(c_,{parsePluginSource:()=>K7,isOfficialPluginSlug:()=>G7,installPlugin:()=>ZY,collectPluginMcpOAuthCandidates:()=>F7});import{spawn as _x}from"node:child_process";import{createHash as fx}from"node:crypto";import{existsSync as k1,mkdirSync as eX,readdirSync as Lx,readFileSync as Ox,renameSync as J7,rmSync as Y7,statSync as $Y}from"node:fs";import{cp as tX,mkdir as k_,writeFile as V7}from"node:fs/promises";import{homedir as w_}from"node:os";import{basename as F$,dirname as C_,extname as Tx,join as t,relative as I_,resolve as e$,sep as zx}from"node:path";import{isPluginModulePath as X7,resolveClineDir as qx,resolvePluginModuleEntries as Mx}from"@cline/shared/storage";var a6="_installed",B7="package",Rx="https://github.com/cline/plugins.git",P_=30000,j7=10485760,S_="@cline/",Nx=["dependencies","devDependencies","optionalDependencies","peerDependencies"],Ex={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function H7($){if($==="~")return w_();if($.startsWith("~/"))return t(w_(),$.slice(2));return $}function x_($){return $.split(zx).join("/")}function G8($){return fx("sha256").update($).digest("hex").slice(0,12)}function wx($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function K$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return wx(W)||"plugin"}function G7($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function Cx($){return $?.trim()||Rx}function b_($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function Px($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function Sx($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function bx($){try{return decodeURIComponent($)}catch{return $}}function yx($){return F$(bx($))||"plugin"}function hx($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function y_($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=yx(W.pathname),J=X7(Q),j=(Z==="github.com"||Z==="www.github.com")&&hx(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function h_($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=Sx(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function K7($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=b_(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=h_(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=y_(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=b_(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=y_(Z);if(J)return J;let j=h_(Z);if(j)return j;if(G7(Z))return{type:"official",slug:Z};if(Px(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function kx($){return $?t($,".cline","plugins"):t(qx(),"plugins")}function Ix($,W,Z){if(W.type==="npm")return t($,a6,"npm",`${K$(W.name)}-${G8(Z)}`);if(W.type==="git")return t($,a6,"git",K$(W.host),`${K$(W.path)}-${G8(Z)}`);if(W.type==="remote")return t($,a6,"remote",`${K$(W.filename)}-${G8(Z)}`);if(W.type==="official")return t($,a6,"official",`${K$(W.slug)}-${G8(Z)}`);return t($,a6,"local",`${K$(F$(H7(W.path)))}-${G8(Z)}`)}function xx($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${e$(W,H7($.path))}`}function gx($,W){if($.type==="npm")return $.name;if($.type==="git")return K$(F$($.path));if($.type==="remote")return K$(F$($.filename,Tx($.filename)));if($.type==="official")return $.slug;return K$(F$(e$(W,H7($.path))))}async function o6($,W,Z={}){await new Promise((Q,J)=>{let j=_x($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function g_($){let W=t($,"package.json");if(!k1(W))return null;try{return JSON.parse(Ox(W,"utf8"))}catch{return null}}function mx($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function vx($){let W=t($,"package.json"),Z=g_($);if(!Z)return;let Q=!1;for(let J of Nx){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(S_))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(S_))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await V7(W,`${JSON.stringify(Z,null,2)}
754
- `,"utf8")}function cx($,W){let Z=t($,"node_modules","@cline");if(!k1(Z))return;for(let Q of v_(Z)){if(`@cline/${Q.name}`===W)continue;Y7(t(Z,Q.name),{recursive:!0,force:!0})}}function m_($){let W=mx(g_($)).map((j)=>e$($,j)).filter((j)=>k1(j)&&$Y(j).isFile()&&X7(j));if(W.length>0)return W;let Z=Mx($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of v_(j)){let Y=t(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&X7(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function v_($){try{return Lx($,{withFileTypes:!0})}catch{return[]}}function ux($,W){let Z=m_(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${x_(I_($,Q))}`)}async function dx($,W,Z){let Q=ux($,W);return await V7(t($,"package.json"),JSON.stringify({...Ex,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function lx($,W,Z){let Q=t(W,B7);return await k_(Q,{recursive:!0}),await V7(t(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await o6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),cx(Q,$.name),t(Q,"node_modules",$.name)}async function WY($,W){if(!k1(t($,"package.json")))return;await vx($),await o6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function px($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=t(W,B7),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await o6("git",J)}catch(j){if(!$.ref)throw j;await o6("git",["clone","--filter=blob:none","--",$.repo,Q]),await o6("git",["checkout","--detach",$.ref],{cwd:Q})}return await WY(Q,Z),Q}async function rx($,W,Z,Q){let J=t(W,"repo");await o6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=t(J,"plugins",$.slug);if(!k1(j)||!$Y(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=t(W,B7);return await tX(j,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),Y7(J,{recursive:!0,force:!0}),await WY(X,Z),X}function sX($){return Error(`Remote plugin file from ${$} exceeds the ${j7} byte limit`)}function ix($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function nx($,W){let Z=ix($);if(Z!==void 0&&Z>j7)throw sX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>j7)throw sX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>j7)throw await Q.cancel().catch(()=>{return}),sX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function ax($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},P_);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await nx(J,$.url);return eX(W,{recursive:!0}),await V7(t(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${P_}ms`);throw J}finally{clearTimeout(Q)}}async function ox($,W,Z,Q){let J=e$(Z,H7($.path));if(!k1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=$Y(J);if(j.isFile()){if(!X7(J))throw Error(`Plugin file must be .js or .ts: ${J}`);eX(W,{recursive:!0});let Y=t(W,F$(J));return await tX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=t(W,B7);return await tX(J,X,{recursive:!0,filter:(Y)=>{let V=F$(Y);return V!==".git"&&V!=="node_modules"}}),await WY(X,Q),X}function sx($,W){if(k1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function tx($,W,Z){if(eX(C_(W),{recursive:!0}),!k1(W)){J7($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=t(C_(W),`.replace-${F$(W)}-${Date.now()}-${process.pid}-${G8(`${W}:${Math.random()}`)}`);J7(W,Q);try{J7($,W)}catch(J){if(!k1(W)&&k1(Q))J7(Q,W);throw J}try{Y7(Q,{recursive:!0,force:!0})}catch{}}function ex($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function $g($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function Wg($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function F7($){let W=new Set($.pluginPaths.map((J)=>e$(J)));if(W.size===0)return[];let Z;try{Z=t0({filePath:$.settingsPath??Q0()})}catch{return[]}let Q=[];for(let J of Z){let j=Wg(J);if(!j||!W.has(e$(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(ex(J)||$g(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function ZY($){let W=$.source.trim(),Z=K7(W,$.sourceType),Q=$.cwd?.trim(),J=Q?e$(Q):process.cwd(),j=kx(Q?J:void 0),X=Cx($.officialPluginsRepo),Y=xx(Z,J,X),V=Ix(j,Z,Y),B=gx(Z,J),H=t(j,a6,".tmp"),G=t(H,`${Date.now()}-${process.pid}-${G8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;sx(V,F),await k_(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await lx(Z,G,K);else if(Z.type==="git")A=await px(Z,G,K);else if(Z.type==="official")A=await rx(Z,G,K,X);else if(Z.type==="remote")A=await ax(Z,G);else A=await ox(Z,G,J,K);let D=(Z.type==="local"||Z.type==="remote")&&A===G?m_(G).map((_)=>`./${x_(I_(G,_))}`):await dx(G,A,B);if(D.length===0)throw Error(`No plugin entry files found for ${W}`);tx(G,V,F);let U={source:W,installPath:V,entryPaths:D.map((_)=>e$(V,_)),mcpSyncFailures:[],mcpOAuthCandidates:[]},f=await NW({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=f.failures,U.mcpOAuthCandidates=F7({pluginPaths:U.entryPaths}),U}catch(D){throw Y7(G,{recursive:!0,force:!0}),D}}var s_={};w(s_,{writeModelsFileSync:()=>IW,writeModelsFile:()=>xW,toProviderModel:()=>VY,syncStoredProviderRegistration:()=>BY,resolveModelsRegistryPath:()=>I1,registerProviderSettingsProvider:()=>o_,registerCustomProvider:()=>F8,registerConfiguredProvidersFromSettings:()=>gW,readModelsFileSync:()=>s6,readModelsFile:()=>K8,parseModelsFile:()=>YY,ensureCustomProvidersLoadedSync:()=>mW,ensureCustomProvidersLoaded:()=>vW,emptyModelsFile:()=>kW,StoredProviderMetadataSchema:()=>d_,StoredProviderEntrySchema:()=>jY,StoredModelsFileSchema:()=>XY,StoredModelEntrySchema:()=>u_});import{existsSync as Zg,mkdirSync as Qg,readFileSync as Jg,renameSync as jg,rmSync as Xg,writeFileSync as Yg}from"node:fs";import{mkdir as Vg,readFile as Bg,rename as Hg,rm as Gg,writeFile as Kg}from"node:fs/promises";import{dirname as JY,join as Fg}from"node:path";import*as A0 from"@cline/llms";import{ApiFormatSchema as Ag,ModelCapabilitySchema as Ug,ProviderCapabilitySchema as Dg,ProviderClientSchema as _g,ProviderProtocolSchema as fg}from"@cline/shared";import{z as e}from"zod";var QY=e.number().finite().positive().optional().catch(void 0),hW=e.number().finite().nonnegative().optional().catch(void 0),u_=e.object({id:e.string().optional(),name:e.string().optional(),maxTokens:QY,contextWindow:QY,maxInputTokens:QY,capabilities:e.array(Ug).optional(),supportsVision:e.boolean().optional(),supportsAttachments:e.boolean().optional(),supportsReasoning:e.boolean().optional(),inputPrice:hW,outputPrice:hW,cacheReadsPrice:hW,cacheWritesPrice:hW,temperature:hW,apiFormat:Ag.optional(),isR1FormatRequired:e.boolean().optional()}).passthrough(),d_=e.object({name:e.string(),baseUrl:e.string(),defaultModelId:e.string().optional(),protocol:fg.optional(),client:_g.optional(),capabilities:e.array(Dg).optional(),modelsSourceUrl:e.string().optional()}).passthrough(),jY=e.object({provider:d_.optional(),models:e.record(e.string(),u_).optional()}).passthrough(),XY=e.object({version:e.literal(1),providers:e.record(e.string(),jY)}),Lg=e.object({version:e.literal(1),providers:e.record(e.string(),e.unknown())}),A7=new Set;function l_($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function I1($){return Fg(JY($.getFilePath()),"models.json")}function kW(){return{version:1,providers:{}}}function YY($){let W=Lg.safeParse($);if(!W.success)return s("models.json content is not a valid models file envelope; starting from an empty registry"),kW();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=jY.safeParse(J);if(j.success)Z[Q]=j.data;else s(`models.json: dropping invalid entry for provider=${Q}`)}return{version:1,providers:Z}}function s6($){if(!Zg($))return kW();try{let W=Jg($,"utf8");return YY(JSON.parse(W))}catch{s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return kW()}async function K8($){try{let W=await Bg($,"utf8");return YY(JSON.parse(W))}catch(W){if(W?.code!=="ENOENT")s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return kW()}function IW($,W){Qg(JY($),{recursive:!0});let Z=XY.parse(W),Q=`${$}.${process.pid}.tmp`;try{Yg(Q,`${JSON.stringify(Z,null,2)}
755
- `,"utf8"),jg(Q,$)}catch(J){throw Xg(Q,{force:!0}),J}}async function xW($,W){await Vg(JY($),{recursive:!0});let Z=XY.parse(W),Q=`${$}.${process.pid}.tmp`;try{await Kg(Q,`${JSON.stringify(Z,null,2)}
756
- `,"utf8"),await Hg(Q,$)}catch(J){throw await Gg(Q,{force:!0}).catch(()=>{}),J}}function VY($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function p_($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function r_($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function Og($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function i_($,W){return $??W??"openai-chat"}function n_($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function a_($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision!==void 0)if(W.supportsVision)Q.add("images");else Q.delete("images");if(W?.supportsAttachments!==void 0)if(W.supportsAttachments)Q.add("files");else Q.delete("files");if(W?.supportsReasoning!==void 0)if(W.supportsReasoning)Q.add("reasoning");else Q.delete("reasoning");let J=W?.isR1FormatRequired?"r1":W?.apiFormat,j=W?.inputPrice!==void 0||W?.outputPrice!==void 0||W?.cacheReadsPrice!==void 0||W?.cacheWritesPrice!==void 0;return{id:$,name:W?.name??$,...W?.maxTokens!==void 0?{maxTokens:W.maxTokens}:{},...W?.contextWindow!==void 0?{contextWindow:W.contextWindow}:{},...W?.maxInputTokens!==void 0?{maxInputTokens:W.maxInputTokens}:{},...Q.size>0?{capabilities:[...Q]}:{},...W?.temperature!==void 0?{temperature:W.temperature}:{},...J!==void 0?{apiFormat:J}:{},...j?{pricing:{...W?.inputPrice!==void 0?{input:W.inputPrice}:{},...W?.outputPrice!==void 0?{output:W.outputPrice}:{},...W?.cacheReadsPrice!==void 0?{cacheRead:W.cacheReadsPrice}:{},...W?.cacheWritesPrice!==void 0?{cacheWrite:W.cacheWritesPrice}:{}}}:{}}}function Tg($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;A0.registerModel($,J,a_(J,Q))}}function zg($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function qg($){return Object.assign({},...A0.resolveProviderModelCatalogKeys($).map((Z)=>A0.getGeneratedModelsForProvider(Z)))}function o_($){let W=$.provider.trim();if(!W||A0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=A0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=qg(W),j=r_($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=zg(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=i_($.protocol,Q?.provider.protocol),K=n_($.client,G,Q?.provider.client);A0.registerProvider({provider:{id:W,name:Q?.provider.name??l_(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:p_($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function gW($){for(let W of Object.values($.providers))o_(W.settings)}function F8($,W){let Z=W.models??{};if(!Og(W.provider)){Tg($,Z);return}let Q=r_(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=i_(W.provider.protocol,void 0),Y=n_(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...a_(B,H,Q.length>0?Q:void 0),status:"active"}]));A0.registerProvider({provider:{id:$,name:W.provider.name.trim()||l_($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:p_(W.provider.capabilities),source:"file"},models:V})}function BY($,W,Z){let Q=Z?.models??{},J=new Set;for(let[Y,V]of Object.entries(W?.models??{})){if(Object.hasOwn(Q,Y))continue;let B=V.id?.trim()||Y.trim();if(B)J.add(B),A0.unregisterModel($,B)}if(!Z)return;let j=A0.getProviderCollectionSync($);F8($,Z);let X=A0.getProviderCollectionSync($);if(j&&X&&X!==j){let Y=Object.fromEntries(Object.entries(j.models).filter(([V])=>!J.has(V)));A0.registerProvider({...X,models:{...Y,...X.models}})}}function mW($){let W=I1($);if(A7.has(W))return;let Z=s6(W);for(let[Q,J]of Object.entries(Z.providers))F8(Q,J);A7.add(W)}async function vW($){let W=I1($);if(A7.has(W))return;let Z=await K8(W);for(let[Q,J]of Object.entries(Z.providers))F8(Q,J);A7.add(W)}var Xf={};w(Xf,{updateLocalProvider:()=>_7,saveLocalProviderSettings:()=>DY,saveLocalProviderOAuthCredentials:()=>OY,resolveLocalClineAuthToken:()=>zY,refreshProviderModelsFromSource:()=>_Y,normalizeOAuthProvider:()=>fY,markLocalProviderEnabled:()=>FY,loginLocalProvider:()=>LY,loginAndSaveLocalProviderOAuthCredentials:()=>TY,listLocalProviders:()=>AY,getLocalProviderModels:()=>UY,ensureCustomProvidersLoaded:()=>vW,deleteLocalProvider:()=>f7,addLocalProvider:()=>KY});import*as k0 from"@cline/llms";var e_="cline-pass";function Mg($){return $.apiKey??$.auth?.apiKey}function Rg($){return($.auth?.accessToken?.trim()??"").length>0}function $f($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function Ng($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function Eg($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function Wf($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>VY(W,Z))}async function wg($,W){let Z=await k0.getModelsForProvider($),Q=$===e_;if(!W&&!Q)return Z;let J=await G5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function HY($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function Cg($){if(!$?.length)return;return[...new Set($)]}function Pg($,W){return Cg([...$??[],...W??[]])}function Sg($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function bg($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function yg($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(bg)}var U7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},t_={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function hg($){if(!$)return[U7];if($.source!=="system")return $.baseUrl?[U7,t_]:[U7];let W=[];if($.env?.length)W.push(U7);if($.baseUrl)W.push(t_);return W}function kg($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function Ig($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function xg($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=Ig(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:kg(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function Zf($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function GY($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function Qf($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await GZ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function Jf($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);k0.unregisterProvider(W)}async function KY($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=I1($);if((await K8(A)).providers[Z]){let U=await f7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return Jf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(k0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=HY(W.models),Y=W.modelsSourceUrl?.trim(),V=await Qf({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=Zf(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=I1($),F=await K8(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:GY(V,H)},await xW(K,F),F8(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function _7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=I1($),J=await K8(Q),j=J.providers[Z];if(!j){let T=$.getProviderSettings(Z);if(!T)throw Error(`provider "${Z}" does not exist`);let O=W.modelsSourceUrl?.trim(),L=HY(W.models)[0]??T.model?.trim();if(!L&&!O)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||$f(Z),baseUrl:W.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:L,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:L?GY([L],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=HY(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),D=await Qf({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),f=U&&D.includes(U)?U:D[0],R={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:f};if(B)R.protocol=B;else delete R.protocol;if(H)R.client=H;else delete R.client;if(W.apiKey!==void 0){let T=W.apiKey?.trim()??"";if(T)R.apiKey=T;else delete R.apiKey}if(W.headers!==void 0){let T=Zf(W.headers);if(T)R.headers=T;else delete R.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")R.timeout=W.timeoutMs;else delete R.timeout;return $.saveProviderSettings(R,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:f,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:GY(D,V)},await xW(Q,J),F8(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function f7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=I1($),J=await K8(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await xW(Q,J),k0.unregisterProvider(Z),Jf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function FY($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function AY($,W={}){let Z=$.read(),Q=k0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([k0.getProvider(X),k0.getModelsForProvider(X)]),B=Wf(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??$f(X),F=Pg(Y?.capabilities,G?.capabilities),A=yg(Y?.metadata)??hg(Y);return{provider:{id:X,name:K,models:B.length,color:Eg(X),letter:Ng(K),enabled:Boolean(H),apiKey:G?Mg(G):void 0,oauthAccessTokenPresent:G?Rg(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:xg(A,G,Y),modelList:B},rank:Sg(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==e_);return{providers:j,settingsPath:$.getFilePath()}}async function UY($,W){let Z=$.trim(),Q=await wg(Z,W),J=Wf(Q);return{providerId:Z,models:J}}function D7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function jf($,W){if(!D7(W))return D7($)?{...$}:void 0;let Z=D7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(D7(J)){let j=jf(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function DY($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=jf(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function _Y($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=k0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=KZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await _7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function fY($){let W=$.trim().toLowerCase(),Z=H0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function LY($,W,Z,Q){let J=H0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=Y6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function OY($,W,Z,Q,J){return j2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function TY($,W,Z,Q){let J=Y6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return G4($,W,{callbacks:J,telemetry:Q})}function zY($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var Yf={};w(Yf,{getProviderConfigFields:()=>qY});import*as L7 from"@cline/llms";var gg=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],mg={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function vg($,W){let Z={};for(let Q of gg){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function cg($){let W=mg[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:vg($.fields,W.fields)}}var ug=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function dg($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return ug.has($)}function qY($){let W=L7.normalizeProviderId($);if(J2(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=L7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(dg(W,Z))J.baseUrl={defaultValue:Q};return cg({providerId:W,authMethod:"api-key",fields:J})}var Gf={};w(Gf,{resolveLegacyClineAuth:()=>NY,migrateLegacyProviderSettings:()=>cW});import{existsSync as lg,readFileSync as pg}from"node:fs";import{dirname as rg,join as MY}from"node:path";import*as t6 from"@cline/llms";import{resolveClineDataDir as ig}from"@cline/shared/storage";var O7="openai",Hf=t6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,Vf=128000;function NY($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function b($){let W=$?.trim();return W?W:void 0}function ng($){return $==="credentials"?"iam":$}function Bf($){if(!lg($))return;try{let W=pg($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function ag($){let W=$.dataDir??ig(),Z=$.globalStatePath??MY(W,"globalState.json"),Q=$.secretsPath??MY(W,"secrets.json"),J=Bf(Z),j=Bf(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function RY($){if($===O7)return Hf;return $}function og($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?b(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?b(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function sg($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(b).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function tg($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=b(Z.access_token),J=b(Z.refresh_token),j=b(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function eg($){let W=t6.getGeneratedModelsForProvider($),Q=t6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function $m($,W,Z,Q){let J=RY($),j=b(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=og(W,$,Q,j)??eg(J),Y=sg(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,tg(Z));if($==="cline")try{let f=b(Z["cline:clineAccountId"]);if(f)H.auth={...H.auth??{},...NY(f)}}catch{}if($===O7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let f=ng(W.awsAuthentication),_=f==="profile"||W.awsUseProfile===!0;H.aws={accessKey:b(Z.awsAccessKey),secretKey:b(Z.awsSecretKey),sessionToken:b(Z.awsSessionToken),region:b(W.awsRegion),authentication:f,profile:_?b(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:b(W.awsBedrockEndpoint),customModelBaseId:b(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:b(W.vertexProjectId),region:b(W.vertexRegion)};if($===O7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:b(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let f=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:b(Z.sapAiCoreClientId),clientSecret:b(Z.sapAiCoreClientSecret),tokenUrl:b(W.sapAiCoreTokenUrl),resourceGroup:b(W.sapAiResourceGroup),deploymentId:f?void 0:b(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:f}}if($==="oca"){H.oca={mode:W.ocaMode};let f=b(Z.ocaRefreshToken);if(f)H.auth={...H.auth??{},refreshToken:f}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=b(B[$]),F=b(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},D=Q6.safeParse(A);if(!D.success)return;return Object.keys(A).filter((f)=>f!=="provider").length>0?D.data:void 0}function Wm($,W){if($!==Hf)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:Vf,maxInputTokens:Vf,capabilities:["streaming","tools","images"]}}}}function Zm($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=b(J);if(j)Z.add(j)}if(b(W.apiKey))Z.add("anthropic");if(b(W.openRouterApiKey))Z.add("openrouter");if(b(W.openAiApiKey))Z.add(O7);if(b(W.openAiNativeApiKey))Z.add("openai-native");if(b(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(b(W.geminiApiKey))Z.add("gemini");if(b(W.ollamaApiKey))Z.add("ollama");if(b(W.awsAccessKey)||b(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||b($.awsProfile))Z.add("bedrock");if(b($.vertexProjectId)||b($.vertexRegion))Z.add("vertex");if(b(W.clineApiKey))Z.add("cline");let Q=NY(b(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(b(W.ocaApiKey))Z.add("oca");if(b(W.sapAiCoreClientId)||b(W.sapAiCoreClientSecret)||b($.sapAiCoreTokenUrl)||b($.sapAiCoreBaseUrl)||b($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function cW($){let W=$.providerSettingsManager.read(),Z=ag($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=Zm(Q,J),Y=I$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=MY(rg($.providerSettingsManager.getFilePath()),"models.json"),G=s6(H),K=0;for(let D of X){let U=RY(D);if(Y.providers[U])continue;let f=$m(D,Q,J,j);if(!f)continue;Y.providers[U]={settings:f,updatedAt:V,tokenSource:"migration"},B+=1;let _=Wm(U,f);if(_&&!G.providers[U])G.providers[U]=_,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=b(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?RY(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)IW(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}uQ();D0();_W();var Kf={};w(Kf,{FileTeamPersistenceStore:()=>T7});import{appendFileSync as Qm,existsSync as EY,mkdirSync as Jm,readFileSync as jm,renameSync as Xm,unlinkSync as Ym,writeFileSync as Vm}from"node:fs";import{join as wY}from"node:path";import{resolveTeamDataDir as Bm}from"@cline/shared/storage";function Hm($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class T7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=Hm($.teamName),Z=$.baseDir?.trim()||Bm();this.dirPath=wY(Z,W),this.statePath=wY(this.dirPath,"state.json"),this.taskHistoryPath=wY(this.dirPath,"task-history.jsonl")}loadState(){if(!EY(this.statePath))return;try{let $=jm(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return OU(W.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;Vm(Z,`${JSON.stringify(W,null,2)}
757
- `,"utf8"),Xm(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Qm(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
758
- `,"utf8")}ensureDir(){if(!EY(this.dirPath))Jm(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(EY(this.statePath))Ym(this.statePath)}}var Ff={};w(Ff,{ChatViewStateSchema:()=>CY,ChatSummarySchema:()=>N7,ChatSessionStatusSchema:()=>q7,ChatSessionConfigSchema:()=>z7,ChatMessageSchema:()=>R7,ChatMessageRoleSchema:()=>M7});import{z as I}from"zod";var z7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),q7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),M7=I.enum(["user","assistant","tool","system","status","error"]),R7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:M7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),N7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),CY=I.object({sessionId:I.string().nullable(),status:q7,config:z7,messages:I.array(R7),rawTranscript:I.string(),error:I.string().nullable(),summary:N7});var Af={};w(Af,{CORE_BUILD_VERSION:()=>uW});var uW=l8;import{Agent as Vv,createAgentRuntime as Bv}from"@cline/agents";var Uf={};w(Uf,{fetchClineRecommendedModels:()=>SY,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>E7});import{getClineEnvironmentConfig as Gm}from"@cline/shared";var Km=5000,E7={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}],clinePass:[]};function Fm($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function PY($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function Am($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(PY).filter((V)=>V!==null),X=Q.map(PY).filter((V)=>V!==null),Y=J.map(PY).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function Um($){let W=$.baseUrl?.trim();if(W)return W;let Z=Gm().apiBaseUrl;try{return($.providerSettingsManager??new X1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function Dm($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function SY($={}){try{let W=Um($),Z=$.fetchImpl??fetch,Q=await Dm(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??Km);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=Am(J);if(j)return j}catch{}return Fm(E7)}var Df={};w(Df,{loadLlmsConfigFromFile:()=>yY,defineLlmsConfig:()=>bY});import{readFile as _m}from"node:fs/promises";import fm from"node:path";function bY($){return $}async function yY($){let W=fm.resolve($),Z=await _m(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return Lm(Q,W)}function Lm($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var zf={};w(zf,{createLlmsSdk:()=>kY,DefaultLlmsSdk:()=>dW});import{BUILT_IN_PROVIDER_IDS as Lf,createHandler as zm,createHandlerAsync as qm,getProviderCollection as Mm,hasProvider as Of,registerAsyncHandler as Rm,registerHandler as Nm,registerModel as Em,registerProvider as Tf}from"@cline/llms";function _f($){return $?{...$}:{}}function Om($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function Tm($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function ff($){let W=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class hY{providers=new Map;register($){Tm($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},..._f($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Om($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,..._f($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class dW{configuredProviders=new hY;constructor($){this.applyConfig($)}createHandler($){return zm(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return qm(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(Tf($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)Nm($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)Rm($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);Tf({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){Em($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...Lf]}async getBuiltInProviders(){return(await Promise.all(Lf.map((W)=>Mm(W)))).filter((W)=>W!==void 0).map((W)=>ff({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=Of(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&Of(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function kY($){return new dW($)}tj();async function wm(){return Promise.resolve().then(() => (uQ(),Q_))}function Dv(){return new Date().toISOString()}var _v="cline",fv="cline-pass";function Lv($){if(Nf($)!=="providers.json")return;let W=xY($);if(Nf(W)!=="settings")return;return xY(W)}class X1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Uv(),this.dataDir=$.dataDir??Lv(this.filePath),this.dataDir||!$.filePath)cW({providerSettingsManager:this,dataDir:this.dataDir});if(mW(this),gW(this.read()),IY(this.filePath))try{Rf(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!IY(this.filePath))return I$();try{let $=Gv(this.filePath,"utf8"),W=JSON.parse($),Z=J6.safeParse(W);if(Z.success){gW(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return s(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${R0(Q?.accessToken)} clineRefreshTokenHash=${R0(Q?.refreshToken)}`),Z.data}}catch{}return I$()}write($){let W=J6.parse($),Z=xY(this.filePath);if(!IY(Z))Hv(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{Av(Q,`${JSON.stringify(W,null,2)}
759
- `,{encoding:"utf8",mode:384}),Kv(Q,this.filePath)}catch(J){throw Fv(Q,{force:!0}),J}try{Rf(this.filePath,384)}catch{}gW(W)}saveProviderSettings($,W={}){let Z=Q6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:Dv(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return s(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=H0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return Q6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===fv&&W.isClinePassEnabled===!1)return _v;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return s0(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return s0(W,$)}async refreshCatalog(){try{await W6({})}catch{}}}D0();M6();function Ov($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class w7 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class gY{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new X1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=H0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=H0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=K4($,J);if(!j)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;s(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${R0(j.access)} refreshTokenHash=${R0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw s(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new w7($);let Y=j2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!Ov(J.auth,Y.auth);if(V)s(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${R0(X.access)} newRefreshTokenHash=${R0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else s(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as Tv}from"@cline/shared";import{nanoid as zv}from"nanoid";class Ef{list($){return $?Y1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Y1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:Y1($),updated:!1};let j=W.prompt===void 0?J.prompt:Tv(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),qv($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:Y1($),prompt:C7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:Y1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:Y1($),prompt:J?C7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${zv(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return Y1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:Y1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:Y1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:Y1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),Y1($)}clear($){return $.pendingPrompts.length=0,[]}}class mY{deps;service=new Ef;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:Y1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=C7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function C7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function Y1($){return $.pendingPrompts.map(C7)}function qv($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}D0();class cY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=v3(Z),X=!!Q&&(!j.agentId||j.agentId===vY(Q.agent));c3(J,Z,X?{isPrimaryAgentEvent:!0,agentId:vY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(bj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};c3(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=o1({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:vY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)_$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await yj($,W,this.deps.invokeBackendOptional),Z)hj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function vY($){return $.getAgentId()}function uY($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:s1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function dY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function wf($,W,...Z){let Q=dY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function Cf($,W,...Z){let Q=dY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function Pf($,W,...Z){let Q=dY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}U1();D0();function lY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=o1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)_$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});Z4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
760
- `).length:0;Z4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...o1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function pY($,W,Z,Q){let J=lY($,W,Z);return C$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?N2({cwd:W.cwd,...a0[i1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(pY($,W,Z,Q));return n1(X)},...J})}import{readFile as Mv,stat as Rv}from"node:fs/promises";var Nv=20480000;async function Sf($){let W=await Rv($);if(!W.isFile())throw Error("Path is not a file");if(W.size>Nv)throw Error("File is too large to read into context.");let Z=await Mv($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var bf=5000;function lW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function hv($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=lW(W.inputTokens),Q=lW(W.outputTokens),J=lW(W.cacheReadTokens),j=lW(W.cacheWriteTokens),X=lW(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function kv($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function yf($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class h1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new s5;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new s$;constructor($){let W=wv();if(W)yv(W);let Z=c0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new r6,this.createAgentInstance=$.createAgent??((Q)=>new N$(Q)),this.defaultCapabilities=C0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new X1,this.oauthTokenManager=$.oauthTokenManager??new gY({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new mY({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new cY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??F0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||Pv(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?d8(X):q0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=rY(V,J),H=rY(B,`${J}.messages.json`),G=rY(B,`${J}.json`),K=s1($.config),F=x0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,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,messages_path:H}),A,D;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",J);if(k)F=k,A={manifestPath:G,messagesPath:k.messages_path||H,compactionPath:k.compaction_path,manifest:k},D=await this.invokeOptionalValue("readSessionCompactionState",J)}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,f);let _=C0(this.defaultCapabilities,$.capabilities),R=_?.toolExecutors??this.toolExecutors,T=$.localRuntime,O=T?.extensionContext?.logger??T?.logger,L=T?.extensionContext?.automation,C,N={getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,W0,T0)=>this.eventBridge.dispatchAgentEvent(k,W0,T0),invokeBackendOptional:(k,...W0)=>this.invokeOptional(k,...W0)};C=await zK({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:_,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(J,k.payload,O);return}this.eventBridge.handlePluginEvent(J,k,L)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(J,k),C.config.onTeamEvent?.(k)},createSpawnTool:()=>pY(N,C.config,J,R),createSubAgentLifecycleCallbacks:(k)=>lY(N,k,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(J,()=>k)}});let p=kZ(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let x=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(x.teamRuntime&&!P.teamName?.trim())P.teamName=x.teamRuntime.getTeamName();let d=[...x.tools,...P.extraTools??[]],x1=x.extensions??C.extensions,W2=j.initialCompactionState,A$,I0=T4(P),U0=W2??D,O1=I0&&U0?{...U0,conversation_id:U0.conversation_id?.trim()||J}:void 0,A8=I0?z4({compact:I0,getState:()=>A$?.compactionState,saveState:async(k)=>{let W0=A$;if(!W0)return;let T0={...k,conversation_id:W0.sessionId};try{if(!(await this.persistActiveSessionCompactionState(W0,T0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:W0.sessionId,sourceMessageCount:T0.source_message_count})}catch(M0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:W0.sessionId,error:M0}),$2(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:M0,context:{sessionId:W0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,V0={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,temperature:P.temperature,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:A8,tools:d,hooks:C.hooks,extensions:x1,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:Sf,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(k)=>{let W0=C.requestToolApproval,T0=this.sessions.get(J);if(T0)await this.markTurnPending(T0);try{if(!W0)return{approved:!1,reason:"Tool approval callback is not configured."};return await W0(k)}finally{let M0=this.sessions.get(J);if(M0?.status==="pending")await this.markTurnRunning(M0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:x.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(J);return k?BW(k.prompt,k.mode??P.mode):void 0},logger:x.logger??P.logger,extensionContext:P.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(J,P,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await C.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let W0=this.sessions.get(J);if(!W0)return;let T0=W0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,T0,P.systemPrompt)}catch(M0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:M0}),$2(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:M0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let l0=this.createAgentInstance(V0);if(V0.onEvent)l0.subscribeEvents(V0.onEvent);x.registerLeadAgent?.(l0);let V1=o1({agentId:l0.getAgentId(),conversationId:l0.getConversationId(),teamId:x.teamRuntime?.getTeamId(),teamName:x.teamRuntime?.getTeamName(),teamRole:x.teamRuntime?"lead":void 0});if(MK(P,J,Q.length>0,K,V1),V1)_$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...V1});if(x.teamRuntime)j9(P.telemetry,{ulid:J,teamId:x.teamRuntime.getTeamId(),teamName:x.teamRuntime.getTeamName(),leadAgentId:l0.getAgentId(),restoredFromPersistence:x.teamRestoredFromPersistence===!0});let y={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:x,agent:l0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:O1,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(A$=y,y.compactionState&&!this.isCompactionStateForSession(y.sessionId,y.compactionState,y))y.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:y.sessionId,conversationId:y.compactionState.conversation_id}),y.compactionState=void 0;if(this.sessions.set(J,y),A)await this.refreshActiveSessionGitMetadata(y,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(y),await this.invoke("persistSessionMessages",y.sessionId,X,y.config.systemPrompt),y.compactionState){if(!(await this.persistActiveSessionCompactionState(y,y.compactionState)).updated)y.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(y,"completed",0)}let B1;try{if(j.prompt?.trim())if(B1=await this.executeTurn(y,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!y.interactive)await this.finalizeSingleRun(y,B1.finishReason);else await this.completeInteractiveTurn(y,B1.finishReason)}catch(k){if(y.interactive&&y.aborting)B1=await this.completeAbortedInteractiveTurn(y);else{$2(y.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:y.sessionId,providerId:y.config.providerId,modelId:y.config.modelId}});try{await this.failSession(y)}catch(W0){y.config.logger?.error?.("Session failure cleanup threw",{sessionId:y.sessionId,error:W0})}throw k}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:B1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw $2(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=jj(this.usageBySession.get($)),Z=jj(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!K0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!K0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return uY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return a4(Q);let J=await this.readManifest(Z);return J?YQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(a4),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(uY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(yf(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return X2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(yf(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return d$(Z.messagesPath);let Q=await this.readManifest(W);return d$(Q?.messages_path)}async dispatchHookEvent($){await jA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=T2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(kj($,X.finishReason)){let Y=await Ij($);if(Y.length===0)break;let V=xj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(VW($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=q0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??q0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=q0(),$.turnUsageByAgent=new Map,tW($.config.telemetry,$.sessionId,$.config.mode),D8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=$Z(B.messages,B,j);$.persistedMessages=H;let G=s4($.turnUsageByAgent?.values()??[]),K=L0(X,B.usage),F=L0(L0(q0(),B.usage),G),A=L0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw $2($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===z0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,$4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,W){let Z=s1($.config),Q=bv(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await b8(Q,Z);RK($.config.telemetry,J);let j=BW(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=s1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:W,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async refreshActiveSessionGitMetadata($,W){try{let Z=W??await fJ(s1($.config));if(!Z||!$.artifacts)return;if(_J($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>kZ({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(VW($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)$4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});qQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),$2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),$2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,K0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=K0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!J2($.config.providerId)||!Sv(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof w7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new Z$($);throw $2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Cv(Q)?Q:iY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return o1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=L0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=iY(W),J=`${Z}.messages.json`,j;try{j=Ev($)}catch{return q0()}let X=q0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=iY($,Y);if(V===Q)continue;let B=await d$(V);if(B.length===0)continue;X=L0(X,d8(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=hv(W.metadata?.aggregateUsage);if(Z)return kv($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:C1({session:W,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),bf))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(bf)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return wf(this.sessionService,$,...W)}invokeOptional($,...W){return Cf(this.sessionService,$,...W)}invokeOptionalValue($,...W){return Pf(this.sessionService,$,...W)}}function xv($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function gv($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function cQ($={}){let W=new h1({sessionService:new y1(new S1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||F0.CLI,interactive:!1,config:{providerId:Iv(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:gv(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:xv(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{release as mv}from"node:os";import{createClineTelemetryServiceConfig as vv}from"@cline/shared";D0();_W();var cv=300000,uv=5000;function hf(){let $=vv({metadata:{extension_version:uW,cline_type:"hub",platform:"cline-hub-daemon",platform_version:process.version,os_type:process.platform,os_version:mv()}}),W=n$($),Z,Q=()=>{try{return Z??=new X1,Z.getProviderSettings("cline")?.auth}catch{return}},J,j=()=>{let Y=Q(),V=Y?.accountId?.trim();if(!Y||!V)return;let B=`${V}:${Y.organizationId??""}`;if(B===J)return;J=B,H1(W.telemetry,{id:V,provider:"cline",organizationId:Y.organizationId,organizationName:Y.organizationName,memberId:Y.memberId})};j();let X=setInterval(j,cv);return X.unref?.(),{telemetry:W.telemetry,dispose:async()=>{clearInterval(X);let Y;await Promise.race([(async()=>{await W.flush(),await W.dispose()})(),new Promise((V)=>{Y=setTimeout(V,uv),Y.unref?.()})]),clearTimeout(Y)}}}lv(process.env.CLINE_VCR);function rv($){let W=process.cwd(),Z,Q,J;for(let j=0;j<$.length;j+=1){let X=$[j],Y=$[j+1];if(X==="--cwd"&&Y){W=Y,j+=1;continue}if(X==="--host"&&Y){Z=Y,j+=1;continue}if(X==="--port"&&Y){let V=Number(Y);if(Number.isFinite(V))Q=V;j+=1;continue}if(X==="--pathname"&&Y)J=Y,j+=1}return{cwd:W,host:Z,port:Q,pathname:J}}async function iv(){let $=rv(process.argv.slice(2));process.chdir($.cwd);let W=Z1({host:$.host,port:$.port,pathname:$.pathname}),Z=hf(),Q;try{Q=await V8({host:W.host,port:W.port,pathname:W.pathname,owner:pv()==="production"?Q1():v0(),telemetry:Z.telemetry,runtimeHandlers:cQ({telemetry:Z.telemetry}),cronOptions:{workspaceRoot:$.cwd}})}catch(Y){throw await Z.dispose().catch(()=>{return}),Y}let J=async()=>{await Q.close(),await Z.dispose().catch(()=>{return}),process.exit(0)},j=!1,X=(Y,V)=>{if(j)return;j=!0;let B=V instanceof Error?V.stack||V.message:String(V);process.stderr.write(`[hub-daemon] ${Y}: ${B}
751
+ ${V}`:""}`);let B=zx($);if(W7($))throw Error(`Skill uninstall completed, but ${$.name??$.id} is still present in Cline's global skills directories.`);return{id:$.id,type:"skill",status:"uninstalled",message:`Uninstalled ${$.name??$.id}.`,output:[V,...B.map((H)=>`Removed: ${H}`)].filter(Boolean).join(`
752
+ `)||void 0}}async function Q7($,W={}){let[Z]=nX($),Q=Z?.trim()||$.id;if(!Q)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await CW({name:Q,workspaceRoot:W.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((j)=>`Removed: ${j}`)].join(`
753
+ `)}}async function oX($,W={}){if($.type==="mcp"){let Z=SW($);if(W.deleteMcpServer)await W.deleteMcpServer(Z);else $7($,W);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Z??$.id}.`}}if($.type==="skill")return Z7($,W);if($.type==="plugin")return Q7($,W);throw Error(`Unsupported marketplace entry type: ${$.type}`)}var u_={};w(u_,{parsePluginSource:()=>K7,isOfficialPluginSlug:()=>G7,installPlugin:()=>ZY,collectPluginMcpOAuthCandidates:()=>F7});import{spawn as qx}from"node:child_process";import{createHash as Mx}from"node:crypto";import{existsSync as I1,mkdirSync as eX,readdirSync as Rx,readFileSync as Nx,renameSync as J7,rmSync as Y7,statSync as $Y}from"node:fs";import{cp as tX,mkdir as I_,writeFile as V7}from"node:fs/promises";import{homedir as C_}from"node:os";import{basename as A$,dirname as P_,extname as Ex,join as t,relative as x_,resolve as $2,sep as wx}from"node:path";import{isPluginModulePath as X7,resolveClineDir as Cx,resolvePluginModuleEntries as Px}from"@cline/shared/storage";var o6="_installed",B7="package",Sx="https://github.com/cline/plugins.git",S_=30000,j7=10485760,b_="@cline/",bx=["dependencies","devDependencies","optionalDependencies","peerDependencies"],yx={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function H7($){if($==="~")return C_();if($.startsWith("~/"))return t(C_(),$.slice(2));return $}function g_($){return $.split(wx).join("/")}function G8($){return Mx("sha256").update($).digest("hex").slice(0,12)}function hx($){let W=0;while(W<$.length&&$[W]==="-")W++;let Z=$.length;while(Z>W&&$[Z-1]==="-")Z--;return $.slice(W,Z)}function F$($){let W="",Z=!1,Q=$.startsWith("@")?$.slice(1):$;for(let j of Q.slice(0,256)){if(j>="a"&&j<="z"||j>="A"&&j<="Z"||j>="0"&&j<="9"||j==="."||j==="_"||j==="-")W+=j,Z=j==="-";else if(!Z)W+="-",Z=!0;if(W.length>=80)break}return hx(W)||"plugin"}function G7($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function kx($){return $?.trim()||Sx}function y_($){let Z=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Z?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Z[1]}}function Ix($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[W,...Z]=$.split("/");return!!W&&Z.length>=2&&W.includes(".")&&!W.startsWith(".")&&!W.endsWith(".")}function xx($){let W=$.match(/^git@([^:]+):(.+)$/);if(W){let X=W[2]??"",Y=X.indexOf("@");if(Y<0)return{repo:$};return{repo:`git@${W[1]}:${X.slice(0,Y)}`,ref:X.slice(Y+1)||void 0}}if($.includes("://"))try{let X=new URL($),Y=X.pathname.replace(/^\/+/,""),V=Y.indexOf("@");if(V<0)return{repo:$};return X.pathname=`/${Y.slice(0,V)}`,{repo:X.toString().replace(/\/$/,""),ref:Y.slice(V+1)||void 0}}catch{return{repo:$}}let Z=$.indexOf("/");if(Z<0)return{repo:$};let Q=$.slice(0,Z),J=$.slice(Z+1),j=J.indexOf("@");if(j<0)return{repo:$};return{repo:`${Q}/${J.slice(0,j)}`,ref:J.slice(j+1)||void 0}}function gx($){try{return decodeURIComponent($)}catch{return $}}function mx($){return A$(gx($))||"plugin"}function vx($){let W=$.split("/").filter(Boolean);return W.length>=5&&(W[2]==="blob"||W[2]==="raw")}function h_($){if(!/^https?:\/\//i.test($))return null;let W;try{W=new URL($)}catch{return null}let Z=W.hostname.toLowerCase(),Q=mx(W.pathname),J=X7(Q),j=(Z==="github.com"||Z==="www.github.com")&&vx(W.pathname);if(W.protocol!=="https:"){if(j||Z==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Z==="github.com"||Z==="www.github.com"){let X=W.pathname.split("/").filter(Boolean);if(!j)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[X[0],X[1],...X.slice(3)].join("/")}`,filename:Q}}if(Z==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:W.toString(),filename:Q}}if(!J)return null;return{type:"remote",url:W.toString(),filename:Q}}function k_($,W={}){let Z=$.trim(),Q=Z.startsWith("git:")&&!Z.startsWith("git://"),J=Q?Z.slice(4).trim():Z;if(!W.force&&!Q&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:j,ref:X}=xx(J),Y="",V="";if(j.startsWith("git@")){let G=j.match(/^git@([^:]+):(.+)$/);Y=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(j)){let G=new URL(j);Y=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=j.indexOf("/");if(G<0)return null;Y=j.slice(0,G),V=j.slice(G+1)}let B=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!Y||!B||B.split("/").length<2)return null;return{type:"git",repo:j.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(j)?j:`https://${j}`,ref:X,host:Y,path:B}}function K7($,W){let Z=$.trim();if(!Z)throw Error("plugin install requires a source");if(W==="npm"){let X=Z.startsWith("npm:")?Z.slice(4).trim():Z,{name:Y}=y_(X);return{type:"npm",spec:X,name:Y}}if(W==="git"){let X=k_(Z,{force:!0});if(!X)throw Error(`Invalid git plugin source: ${$}`);return X}if(W==="local")return{type:"local",path:$};if(W==="remote"){let X=h_(Z);if(!X)throw Error(`Invalid remote plugin source: ${$}`);return X}if(Z.startsWith("npm:")){let X=Z.slice(4).trim(),{name:Y}=y_(X);return{type:"npm",spec:X,name:Y}}if(Z.startsWith(".")||Z.startsWith("/")||Z==="~"||Z.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Z))return{type:"local",path:$};let J=h_(Z);if(J)return J;let j=k_(Z);if(j)return j;if(G7(Z))return{type:"official",slug:Z};if(Ix(Z))throw Error(`Unrecognized plugin source "${$}". Use --git for hostname-style repositories or pass an explicit local path such as ./github.com/owner/repo.`);return{type:"local",path:$}}function cx($){return $?t($,".cline","plugins"):t(Cx(),"plugins")}function ux($,W,Z){if(W.type==="npm")return t($,o6,"npm",`${F$(W.name)}-${G8(Z)}`);if(W.type==="git")return t($,o6,"git",F$(W.host),`${F$(W.path)}-${G8(Z)}`);if(W.type==="remote")return t($,o6,"remote",`${F$(W.filename)}-${G8(Z)}`);if(W.type==="official")return t($,o6,"official",`${F$(W.slug)}-${G8(Z)}`);return t($,o6,"local",`${F$(A$(H7(W.path)))}-${G8(Z)}`)}function dx($,W,Z){if($.type==="npm")return`npm:${$.spec}`;if($.type==="git")return`git:${$.repo}${$.ref?`#${$.ref}`:""}`;if($.type==="remote")return`remote:${$.url}`;if($.type==="official")return`official:${Z}#plugins/${$.slug}`;return`local:${$2(W,H7($.path))}`}function lx($,W){if($.type==="npm")return $.name;if($.type==="git")return F$(A$($.path));if($.type==="remote")return F$(A$($.filename,Ex($.filename)));if($.type==="official")return $.slug;return F$(A$($2(W,H7($.path))))}async function s6($,W,Z={}){await new Promise((Q,J)=>{let j=qx($,W,{cwd:Z.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),X="";j.stderr.on("data",(Y)=>{X+=String(Y)}),j.on("error",J),j.on("close",(Y)=>{if(Y===0){Q();return}let V=X.trim();J(Error(`${$} ${W.join(" ")} failed with exit code ${Y}${V?`: ${V}`:""}`))})})}function m_($){let W=t($,"package.json");if(!I1(W))return null;try{return JSON.parse(Nx(W,"utf8"))}catch{return null}}function px($){let W=$?.cline?.plugins;if(!Array.isArray(W))return[];return W.flatMap((Z)=>{if(typeof Z==="string")return[Z];return Z.paths??[]})}async function rx($){let W=t($,"package.json"),Z=m_($);if(!Z)return;let Q=!1;for(let J of bx){let j=Z[J];if(!j||typeof j!=="object")continue;for(let X of Object.keys(j)){if(!X.startsWith(b_))continue;delete j[X],delete Z.peerDependenciesMeta?.[X],Q=!0}if(Object.keys(j).length===0)delete Z[J]}if(Z.peerDependenciesMeta){for(let J of Object.keys(Z.peerDependenciesMeta)){if(!J.startsWith(b_))continue;delete Z.peerDependenciesMeta[J],Q=!0}if(Object.keys(Z.peerDependenciesMeta).length===0)delete Z.peerDependenciesMeta}if(!Q)return;await V7(W,`${JSON.stringify(Z,null,2)}
754
+ `,"utf8")}function ix($,W){let Z=t($,"node_modules","@cline");if(!I1(Z))return;for(let Q of c_(Z)){if(`@cline/${Q.name}`===W)continue;Y7(t(Z,Q.name),{recursive:!0,force:!0})}}function v_($){let W=px(m_($)).map((j)=>$2($,j)).filter((j)=>I1(j)&&$Y(j).isFile()&&X7(j));if(W.length>0)return W;let Z=Px($);if(Z?.length)return Z;let Q=[],J=[$];while(J.length>0){let j=J.pop();if(!j)continue;for(let X of c_(j)){let Y=t(j,X.name);if(X.name==="node_modules"||X.name===".git")continue;if(X.isDirectory()){J.push(Y);continue}if(X.isFile()&&!X.name.startsWith(".")&&X7(Y))Q.push(Y)}}return Q.sort((j,X)=>j.localeCompare(X))}function c_($){try{return Rx($,{withFileTypes:!0})}catch{return[]}}function nx($,W){let Z=v_(W);if(Z.length===0)throw Error(`No plugin entry files found in ${W}`);return Z.map((Q)=>`./${g_(x_($,Q))}`)}async function ax($,W,Z){let Q=nx($,W);return await V7(t($,"package.json"),JSON.stringify({...yx,name:Z,cline:{plugins:[{paths:Q}]}},null,2),"utf8"),Q}async function ox($,W,Z){let Q=t(W,B7);return await I_(Q,{recursive:!0}),await V7(t(Q,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await s6(Z,["install",$.spec,"--prefix",Q,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),ix(Q,$.name),t(Q,"node_modules",$.name)}async function WY($,W){if(!I1(t($,"package.json")))return;await rx($),await s6(W,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function sx($,W,Z){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let Q=t(W,B7),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,Q);try{await s6("git",J)}catch(j){if(!$.ref)throw j;await s6("git",["clone","--filter=blob:none","--",$.repo,Q]),await s6("git",["checkout","--detach",$.ref],{cwd:Q})}return await WY(Q,Z),Q}async function tx($,W,Z,Q){let J=t(W,"repo");await s6("git",["clone","--filter=blob:none","--depth","1","--",Q,J]);let j=t(J,"plugins",$.slug);if(!I1(j)||!$Y(j).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${Q}`);let X=t(W,B7);return await tX(j,X,{recursive:!0,filter:(Y)=>{let V=A$(Y);return V!==".git"&&V!=="node_modules"}}),Y7(J,{recursive:!0,force:!0}),await WY(X,Z),X}function sX($){return Error(`Remote plugin file from ${$} exceeds the ${j7} byte limit`)}function ex($){let W=$.headers.get("content-length");if(!W)return;let Z=Number(W);if(!Number.isFinite(Z)||Z<0)return;return Z}async function $g($,W){let Z=ex($);if(Z!==void 0&&Z>j7)throw sX(W);if(!$.body){let X=Buffer.from(await $.text(),"utf8");if(X.byteLength>j7)throw sX(W);return X}let Q=$.body.getReader(),J=[],j=0;try{while(!0){let{done:X,value:Y}=await Q.read();if(X)break;let V=Buffer.from(Y);if(j+=V.byteLength,j>j7)throw await Q.cancel().catch(()=>{return}),sX(W);J.push(V)}return Buffer.concat(J,j)}finally{Q.releaseLock()}}async function Wg($,W){let Z=new AbortController,Q=setTimeout(()=>{Z.abort()},S_);try{let J=await fetch($.url,{signal:Z.signal});if(!J.ok){let X=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${X}`)}let j=await $g(J,$.url);return eX(W,{recursive:!0}),await V7(t(W,$.filename),j),W}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${S_}ms`);throw J}finally{clearTimeout(Q)}}async function Zg($,W,Z,Q){let J=$2(Z,H7($.path));if(!I1(J))throw Error(`Plugin source path does not exist: ${J}`);let j=$Y(J);if(j.isFile()){if(!X7(J))throw Error(`Plugin file must be .js or .ts: ${J}`);eX(W,{recursive:!0});let Y=t(W,A$(J));return await tX(J,Y),W}if(!j.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let X=t(W,B7);return await tX(J,X,{recursive:!0,filter:(Y)=>{let V=A$(Y);return V!==".git"&&V!=="node_modules"}}),await WY(X,Q),X}function Qg($,W){if(I1($)&&!W)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function Jg($,W,Z){if(eX(P_(W),{recursive:!0}),!I1(W)){J7($,W);return}if(!Z)throw Error(`Plugin is already installed at ${W}. Use --force to replace it.`);let Q=t(P_(W),`.replace-${A$(W)}-${Date.now()}-${process.pid}-${G8(`${W}:${Math.random()}`)}`);J7(W,Q);try{J7($,W)}catch(J){if(!I1(W)&&I1(Q))J7(Q,W);throw J}try{Y7(Q,{recursive:!0,force:!0})}catch{}}function jg($){let W=$.transport;if(W.type==="stdio")return!1;return W.headers!==void 0&&Object.keys(W.headers).length>0}function Xg($){let W=$.oauth?.tokens?.access_token;return typeof W==="string"&&W.trim().length>0}function Yg($){let W=$.metadata;if(!W||W.source!=="plugin"||typeof W.pluginName!=="string"||typeof W.pluginPath!=="string")return;return{pluginName:W.pluginName,pluginPath:W.pluginPath}}function F7($){let W=new Set($.pluginPaths.map((J)=>$2(J)));if(W.size===0)return[];let Z;try{Z=W1({filePath:$.settingsPath??Q0()})}catch{return[]}let Q=[];for(let J of Z){let j=Yg(J);if(!j||!W.has($2(j.pluginPath)))continue;let X=J.transport.type;if(X==="stdio")continue;if(jg(J)||Xg(J))continue;Q.push({name:J.name,pluginName:j.pluginName,pluginPath:j.pluginPath,transportType:X,lastError:J.oauth?.lastError})}return Q.sort((J,j)=>J.name.localeCompare(j.name))}async function ZY($){let W=$.source.trim(),Z=K7(W,$.sourceType),Q=$.cwd?.trim(),J=Q?$2(Q):process.cwd(),j=cx(Q?J:void 0),X=kx($.officialPluginsRepo),Y=dx(Z,J,X),V=ux(j,Z,Y),B=lx(Z,J),H=t(j,o6,".tmp"),G=t(H,`${Date.now()}-${process.pid}-${G8(`${W}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;Qg(V,F),await I_(H,{recursive:!0});let A;try{if(Z.type==="npm")A=await ox(Z,G,K);else if(Z.type==="git")A=await sx(Z,G,K);else if(Z.type==="official")A=await tx(Z,G,K,X);else if(Z.type==="remote")A=await Wg(Z,G);else A=await Zg(Z,G,J,K);let D=(Z.type==="local"||Z.type==="remote")&&A===G?v_(G).map((_)=>`./${g_(x_(G,_))}`):await ax(G,A,B);if(D.length===0)throw Error(`No plugin entry files found for ${W}`);Jg(G,V,F);let U={source:W,installPath:V,entryPaths:D.map((_)=>$2(V,_)),mcpSyncFailures:[],mcpOAuthCandidates:[]},f=await EW({pluginPaths:U.entryPaths,cwd:J,workspacePath:J});return U.mcpSyncFailures=f.failures,U.mcpOAuthCandidates=F7({pluginPaths:U.entryPaths}),U}catch(D){throw Y7(G,{recursive:!0,force:!0}),D}}var t_={};w(t_,{writeModelsFileSync:()=>xW,writeModelsFile:()=>gW,toProviderModel:()=>VY,syncStoredProviderRegistration:()=>BY,resolveModelsRegistryPath:()=>x1,registerProviderSettingsProvider:()=>s_,registerCustomProvider:()=>F8,registerConfiguredProvidersFromSettings:()=>mW,readModelsFileSync:()=>t6,readModelsFile:()=>K8,parseModelsFile:()=>YY,ensureCustomProvidersLoadedSync:()=>vW,ensureCustomProvidersLoaded:()=>cW,emptyModelsFile:()=>IW,StoredProviderMetadataSchema:()=>l_,StoredProviderEntrySchema:()=>jY,StoredModelsFileSchema:()=>XY,StoredModelEntrySchema:()=>d_});import{existsSync as Vg,mkdirSync as Bg,readFileSync as Hg,renameSync as Gg,rmSync as Kg,writeFileSync as Fg}from"node:fs";import{mkdir as Ag,readFile as Ug,rename as Dg,rm as _g,writeFile as fg}from"node:fs/promises";import{dirname as JY,join as Lg}from"node:path";import*as F0 from"@cline/llms";import{ApiFormatSchema as Og,ModelCapabilitySchema as Tg,ProviderCapabilitySchema as zg,ProviderClientSchema as qg,ProviderProtocolSchema as Mg}from"@cline/shared";import{z as e}from"zod";var QY=e.number().finite().positive().optional().catch(void 0),kW=e.number().finite().nonnegative().optional().catch(void 0),d_=e.object({id:e.string().optional(),name:e.string().optional(),maxTokens:QY,contextWindow:QY,maxInputTokens:QY,capabilities:e.array(Tg).optional(),supportsVision:e.boolean().optional(),supportsAttachments:e.boolean().optional(),supportsReasoning:e.boolean().optional(),inputPrice:kW,outputPrice:kW,cacheReadsPrice:kW,cacheWritesPrice:kW,temperature:kW,apiFormat:Og.optional(),isR1FormatRequired:e.boolean().optional()}).passthrough(),l_=e.object({name:e.string(),baseUrl:e.string(),defaultModelId:e.string().optional(),protocol:Mg.optional(),client:qg.optional(),capabilities:e.array(zg).optional(),modelsSourceUrl:e.string().optional()}).passthrough(),jY=e.object({provider:l_.optional(),models:e.record(e.string(),d_).optional()}).passthrough(),XY=e.object({version:e.literal(1),providers:e.record(e.string(),jY)}),Rg=e.object({version:e.literal(1),providers:e.record(e.string(),e.unknown())}),A7=new Set;function p_($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function x1($){return Lg(JY($.getFilePath()),"models.json")}function IW(){return{version:1,providers:{}}}function YY($){let W=Rg.safeParse($);if(!W.success)return s("models.json content is not a valid models file envelope; starting from an empty registry"),IW();let Z={};for(let[Q,J]of Object.entries(W.data.providers)){let j=jY.safeParse(J);if(j.success)Z[Q]=j.data;else s(`models.json: dropping invalid entry for provider=${Q}`)}return{version:1,providers:Z}}function t6($){if(!Vg($))return IW();try{let W=Hg($,"utf8");return YY(JSON.parse(W))}catch{s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return IW()}async function K8($){try{let W=await Ug($,"utf8");return YY(JSON.parse(W))}catch(W){if(W?.code!=="ENOENT")s(`models.json at ${$} exists but is unreadable or invalid JSON; treating as an empty registry`)}return IW()}function xW($,W){Bg(JY($),{recursive:!0});let Z=XY.parse(W),Q=`${$}.${process.pid}.tmp`;try{Fg(Q,`${JSON.stringify(Z,null,2)}
755
+ `,"utf8"),Gg(Q,$)}catch(J){throw Kg(Q,{force:!0}),J}}async function gW($,W){await Ag(JY($),{recursive:!0});let Z=XY.parse(W),Q=`${$}.${process.pid}.tmp`;try{await fg(Q,`${JSON.stringify(Z,null,2)}
756
+ `,"utf8"),await Dg(Q,$)}catch(J){throw await _g(Q,{force:!0}).catch(()=>{}),J}}function VY($,W){return{id:$,name:W.name??$,supportsAttachments:W.capabilities?.includes("files"),supportsVision:W.capabilities?.includes("images"),supportsReasoning:W.capabilities?.includes("reasoning")||W.thinkingConfig!=null}}function r_($){if(!$||$.length===0)return;let W=new Set;if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("tools"))W.add("tools");return W.size>0?[...W]:void 0}function i_($){let W=new Set;if(!$||$.length===0)return[...W];if($.includes("streaming"))W.add("streaming");if($.includes("tools"))W.add("tools");if($.includes("reasoning"))W.add("reasoning");if($.includes("prompt-cache"))W.add("prompt-cache");if($.includes("vision"))W.add("images"),W.add("files");return[...W]}function Ng($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function n_($,W){return $??W??"openai-chat"}function a_($,W,Z){return $??Z??(W==="openai-responses"?"openai":"openai-compatible")}function o_($,W,Z){let Q=new Set(W?.capabilities??Z??[]);if(W?.supportsVision!==void 0)if(W.supportsVision)Q.add("images");else Q.delete("images");if(W?.supportsAttachments!==void 0)if(W.supportsAttachments)Q.add("files");else Q.delete("files");if(W?.supportsReasoning!==void 0)if(W.supportsReasoning)Q.add("reasoning");else Q.delete("reasoning");let J=W?.isR1FormatRequired?"r1":W?.apiFormat,j=W?.inputPrice!==void 0||W?.outputPrice!==void 0||W?.cacheReadsPrice!==void 0||W?.cacheWritesPrice!==void 0;return{id:$,name:W?.name??$,...W?.maxTokens!==void 0?{maxTokens:W.maxTokens}:{},...W?.contextWindow!==void 0?{contextWindow:W.contextWindow}:{},...W?.maxInputTokens!==void 0?{maxInputTokens:W.maxInputTokens}:{},...Q.size>0?{capabilities:[...Q]}:{},...W?.temperature!==void 0?{temperature:W.temperature}:{},...J!==void 0?{apiFormat:J}:{},...j?{pricing:{...W?.inputPrice!==void 0?{input:W.inputPrice}:{},...W?.outputPrice!==void 0?{output:W.outputPrice}:{},...W?.cacheReadsPrice!==void 0?{cacheRead:W.cacheReadsPrice}:{},...W?.cacheWritesPrice!==void 0?{cacheWrite:W.cacheWritesPrice}:{}}}:{}}}function Eg($,W){for(let[Z,Q]of Object.entries(W??{})){let J=Q.id?.trim()||Z.trim();if(!J)continue;F0.registerModel($,J,o_(J,Q))}}function wg($,W,Z){return{...W??{},id:$,name:W?.name??$,capabilities:W?.capabilities??Z}}function Cg($){return Object.assign({},...F0.resolveProviderModelCatalogKeys($).map((Z)=>F0.getGeneratedModelsForProvider(Z)))}function s_($){let W=$.provider.trim();if(!W||F0.isBuiltInProviderId(W))return;let Z=$.baseUrl?.trim();if(!Z)return;let Q=F0.MODEL_COLLECTIONS_BY_PROVIDER_ID[W],J=Cg(W),j=i_($.capabilities),X=j.length>0?j:void 0,Y=$.model?.trim(),V={...J,...Q?.models??{}};if(Y)V[Y]=wg(Y,V[Y],X);let B=Object.keys(V).filter(Boolean),H=Y||B[0];if(!H)return;let G=n_($.protocol,Q?.provider.protocol),K=a_($.client,G,Q?.provider.client);F0.registerProvider({provider:{id:W,name:Q?.provider.name??p_(W),description:Q?.provider.description,protocol:G,client:K,baseUrl:Z,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:H,capabilities:r_($.capabilities)??Q?.provider.capabilities,source:"file"},models:V})}function mW($){for(let W of Object.values($.providers))s_(W.settings)}function F8($,W){let Z=W.models??{};if(!Ng(W.provider)){Eg($,Z);return}let Q=i_(W.provider.capabilities),J=Object.entries(Z).map(([B,H])=>({id:H.id?.trim()||B.trim(),model:H})).filter(({id:B})=>B.length>0),j=W.provider.defaultModelId?.trim()||J[0]?.id||"default",X=n_(W.provider.protocol,void 0),Y=a_(W.provider.client,X,void 0),V=Object.fromEntries(J.map(({id:B,model:H})=>[B,{...o_(B,H,Q.length>0?Q:void 0),status:"active"}]));F0.registerProvider({provider:{id:$,name:W.provider.name.trim()||p_($),protocol:X,client:Y,baseUrl:W.provider.baseUrl,modelsSourceUrl:W.provider.modelsSourceUrl,defaultModelId:j,capabilities:r_(W.provider.capabilities),source:"file"},models:V})}function BY($,W,Z){let Q=Z?.models??{},J=new Set;for(let[Y,V]of Object.entries(W?.models??{})){if(Object.hasOwn(Q,Y))continue;let B=V.id?.trim()||Y.trim();if(B)J.add(B),F0.unregisterModel($,B)}if(!Z)return;let j=F0.getProviderCollectionSync($);F8($,Z);let X=F0.getProviderCollectionSync($);if(j&&X&&X!==j){let Y=Object.fromEntries(Object.entries(j.models).filter(([V])=>!J.has(V)));F0.registerProvider({...X,models:{...Y,...X.models}})}}function vW($){let W=x1($);if(A7.has(W))return;let Z=t6(W);for(let[Q,J]of Object.entries(Z.providers))F8(Q,J);A7.add(W)}async function cW($){let W=x1($);if(A7.has(W))return;let Z=await K8(W);for(let[Q,J]of Object.entries(Z.providers))F8(Q,J);A7.add(W)}var Yf={};w(Yf,{updateLocalProvider:()=>_7,saveLocalProviderSettings:()=>DY,saveLocalProviderOAuthCredentials:()=>OY,resolveLocalClineAuthToken:()=>zY,refreshProviderModelsFromSource:()=>_Y,normalizeOAuthProvider:()=>fY,markLocalProviderEnabled:()=>FY,loginLocalProvider:()=>LY,loginAndSaveLocalProviderOAuthCredentials:()=>TY,listLocalProviders:()=>AY,getLocalProviderModels:()=>UY,ensureCustomProvidersLoaded:()=>cW,deleteLocalProvider:()=>f7,addLocalProvider:()=>KY});import*as x0 from"@cline/llms";var $f="cline-pass";function Pg($){return $.apiKey??$.auth?.apiKey}function Sg($){return($.auth?.accessToken?.trim()??"").length>0}function Wf($){return $.split(/[-_]/).filter(Boolean).map((W)=>W.charAt(0).toUpperCase()+W.slice(1)).join(" ")}function bg($){let W=$.split(/\s+/).filter(Boolean);if(W.length===0)return"?";if(W.length===1)return W[0].slice(0,2).toUpperCase();return`${W[0][0]}${W[1][0]}`.toUpperCase()}function yg($){let W=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Z=0;for(let Q of $)Z=Z*31+Q.charCodeAt(0)>>>0;return W[Z%W.length]}function Zf($){return Object.entries($).sort(([W],[Z])=>W.localeCompare(Z)).map(([W,Z])=>VY(W,Z))}async function hg($,W){let Z=await x0.getModelsForProvider($),Q=$===$f;if(!W&&!Q)return Z;let J=await K5($,{loadLatestOnInit:Q,loadPrivateOnAuth:!0,failOnError:!1},W);if($==="litellm"&&J?.knownModels)return J.knownModels;if(Q&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Z,...J.knownModels}:Z}function HY($){return[...new Set(($??[]).map((W)=>W.trim()).filter(Boolean))]}function kg($){if(!$?.length)return;return[...new Set($)]}function Ig($,W){return kg([...$??[],...W??[]])}function xg($){let W=$?.popularRank;return typeof W==="number"&&Number.isFinite(W)?W:Number.MAX_SAFE_INTEGER}function gg($){if(!$||typeof $!=="object")return!1;let W=$;return typeof W.path==="string"&&W.path.trim().length>0&&typeof W.label==="string"&&W.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(W.type))}function mg($){let W=$?.configFields;if(!Array.isArray(W))return;return W.filter(gg)}var U7={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},e_={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function vg($){if(!$)return[U7];if($.source!=="system")return $.baseUrl?[U7,e_]:[U7];let W=[];if($.env?.length)W.push(U7);if($.baseUrl)W.push(e_);return W}function cg($,W){return W.split(".").reduce((Z,Q)=>{if(!Z||typeof Z!=="object")return;return Z[Q]},$)}function ug($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function dg($,W,Z){if(!$?.length)return;let Q={};for(let J of $){let X=ug(J.path==="baseUrl"&&W?.baseUrl===void 0?Z?.baseUrl:cg(W,J.path))??J.defaultValue;if(X!==void 0)Q[J.path]=X}return Q}function Qf($){let W=Object.entries($??{}).filter(([Z])=>Z.trim().length>0);return W.length>0?Object.fromEntries(W):void 0}function GY($,W){let Z=W?.includes("vision")??!1,Q=W?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Z,supportsAttachments:Z,supportsReasoning:Q}]))}async function Jf($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let W=$.modelsSourceUrl?await GZ($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...W])]}function jf($,W){let Z=$.read(),Q=!1;if(Z.providers[W])delete Z.providers[W],Q=!0;if(Z.lastUsedProvider===W)delete Z.lastUsedProvider,Q=!0;if(Q)$.write(Z);x0.unregisterProvider(W)}async function KY($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=W.baseUrl.trim(),J=W.apiKey?.trim()??"";if(!Q&&!J){let A=x1($);if((await K8(A)).providers[Z]){let U=await f7($,{providerId:Z});return{providerId:Z,settingsPath:U.settingsPath,modelsPath:U.modelsPath,modelsCount:0}}return jf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(x0.hasProvider(Z))throw Error(`provider "${Z}" already exists`);let j=W.name.trim();if(!j)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let X=HY(W.models),Y=W.modelsSourceUrl?.trim(),V=await Jf({providerId:Z,explicitModels:X,modelsSourceUrl:Y,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let B=W.defaultModelId?.trim()&&V.includes(W.defaultModelId.trim())?W.defaultModelId.trim():V[0],H=W.capabilities?.length?[...new Set(W.capabilities)]:void 0,G=Qf(W.headers);$.saveProviderSettings({provider:Z,apiKey:J||void 0,baseUrl:Q,headers:G,timeout:W.timeoutMs,model:B,protocol:W.protocol,client:W.client},{setLastUsed:!1});let K=x1($),F=await K8(K);return F.providers[Z]={provider:{name:j,baseUrl:Q,defaultModelId:B,protocol:W.protocol,client:W.client,capabilities:H,modelsSourceUrl:Y},models:GY(V,H)},await gW(K,F),F8(Z,F.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function _7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=x1($),J=await K8(Q),j=J.providers[Z];if(!j){let T=$.getProviderSettings(Z);if(!T)throw Error(`provider "${Z}" does not exist`);let O=W.modelsSourceUrl?.trim(),L=HY(W.models)[0]??T.model?.trim();if(!L&&!O)throw Error(`provider "${Z}" cannot be updated because no model is configured`);j={provider:{name:W.name?.trim()||Wf(Z),baseUrl:W.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:L,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:L?GY([L],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Z}" cannot be updated because it is a model overlay (no provider metadata)`);let X=W.name?.trim()??j.provider.name.trim();if(!X)throw Error("name is required");let Y=W.baseUrl?.trim()??j.provider.baseUrl.trim();if(!Y)throw Error("baseUrl is required");let V=W.capabilities===void 0?j.provider.capabilities:W.capabilities===null?void 0:[...new Set(W.capabilities)],B=W.protocol===void 0?j.provider.protocol:W.protocol??void 0,H=W.client===void 0?j.provider.client:W.client??void 0,G=HY(W.models),K=W.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:W.modelsSourceUrl?.trim()||void 0,F=W.models!==void 0||W.modelsSourceUrl!==void 0&&!!K,A=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),D=await Jf({providerId:Z,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let U=W.defaultModelId===void 0?j.provider.defaultModelId?.trim():W.defaultModelId?.trim(),f=U&&D.includes(U)?U:D[0],R={...$.getProviderSettings(Z)??{},provider:Z,baseUrl:Y,model:f};if(B)R.protocol=B;else delete R.protocol;if(H)R.client=H;else delete R.client;if(W.apiKey!==void 0){let T=W.apiKey?.trim()??"";if(T)R.apiKey=T;else delete R.apiKey}if(W.headers!==void 0){let T=Qf(W.headers);if(T)R.headers=T;else delete R.headers}if(W.timeoutMs!==void 0)if(typeof W.timeoutMs==="number")R.timeout=W.timeoutMs;else delete R.timeout;return $.saveProviderSettings(R,{setLastUsed:!1}),J.providers[Z]={provider:{name:X,baseUrl:Y,defaultModelId:f,protocol:B,client:H,capabilities:V,modelsSourceUrl:K},models:GY(D,V)},await gW(Q,J),F8(Z,J.providers[Z]),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function f7($,W){let Z=W.providerId.trim().toLowerCase();if(!Z)throw Error("providerId is required");let Q=x1($),J=await K8(Q);if(!J.providers[Z])throw Error(`provider "${Z}" does not exist`);return delete J.providers[Z],await gW(Q,J),x0.unregisterProvider(Z),jf($,Z),{providerId:Z,settingsPath:$.getFilePath(),modelsPath:Q}}function FY($,W,Z={}){let Q=W.trim();if(!Q)throw Error("providerId is required");let J=$.read().providers[Q]?.settings;return $.saveProviderSettings({...J??{},provider:Q},{setLastUsed:!1,tokenSource:Z.tokenSource}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function AY($,W={}){let Z=$.read(),Q=x0.getProviderIds(),J=await Promise.all(Q.map(async(X)=>{let[Y,V]=await Promise.all([x0.getProvider(X),x0.getModelsForProvider(X)]),B=Zf(V),H=Z.providers[X]?.settings,G=$.getProviderSettings(X),K=Y?.name??Wf(X),F=Ig(Y?.capabilities,G?.capabilities),A=mg(Y?.metadata)??vg(Y);return{provider:{id:X,name:K,models:B.length,color:yg(X),letter:bg(K),enabled:Boolean(H),apiKey:G?Pg(G):void 0,oauthAccessTokenPresent:G?Sg(G):void 0,baseUrl:G?.baseUrl??Y?.baseUrl,defaultModelId:Y?.defaultModelId,protocol:G?.protocol??Y?.protocol,client:G?.client??Y?.client,capabilities:F,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:A,configValues:dg(A,G,Y),modelList:B},rank:xg(Y?.metadata)}}));J.sort((X,Y)=>{if(X.rank!==Y.rank)return X.rank-Y.rank;return X.provider.name.localeCompare(Y.provider.name)||X.provider.id.localeCompare(Y.provider.id)});let j=J.map((X)=>X.provider);if(W.isClinePassEnabled!==!0)j=j.filter((X)=>X.id!==$f);return{providers:j,settingsPath:$.getFilePath()}}async function UY($,W){let Z=$.trim(),Q=await hg(Z,W),J=Zf(Q);return{providerId:Z,models:J}}function D7($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function Xf($,W){if(!D7(W))return D7($)?{...$}:void 0;let Z=D7($)?{...$}:{};for(let[Q,J]of Object.entries(W)){if(J==null||J===""){delete Z[Q];continue}if(D7(J)){let j=Xf(Z[Q],J);if(j&&Object.keys(j).length>0)Z[Q]=j;else delete Z[Q];continue}Z[Q]=J}return Object.keys(Z).length>0?Z:void 0}function DY($,W){let Z=W.providerId.trim();if(W.enabled===!1){let j=$.read();if(delete j.providers[Z],j.lastUsedProvider===Z)delete j.lastUsedProvider;return $.write(j),{providerId:Z,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Z)??{},provider:Z};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(W,j)&&typeof W[j]==="string")if(W[j].trim().length===0)delete J[j];else J[j]=W[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(W,j))J[j]=W[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(W,j)&&W[j]!=null){let X=Xf(J[j],W[j]);if(X)J[j]=X;else delete J[j]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Z,enabled:!0,settingsPath:$.getFilePath()}}async function _Y($,W){let Z=W.trim(),Q=$.getProviderSettings(Z),j=x0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z]?.provider,X=Q?.baseUrl?.trim()||j?.baseUrl?.trim(),Y=KZ(X,j?.baseUrl,j?.modelsSourceUrl);if(!Q||!j||!X||!Y)return{providerId:Z,refreshed:!1};let V=await _7($,{providerId:Z,name:j.name,baseUrl:X,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:Y,protocol:Q.protocol??j.protocol??null,client:Q.client??j.client??null,capabilities:Q.capabilities??null});return{providerId:Z,refreshed:!0,modelsCount:V.modelsCount}}function fY($){let W=$.trim().toLowerCase(),Z=B0(W);if(Z)return Z.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function LY($,W,Z,Q){let J=B0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let j=V6({onPrompt:async(X)=>X.defaultValue??"",openUrl:Z,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return J.login({settings:W,callbacks:j,telemetry:Q})}function OY($,W,Z,Q,J){return j2({manager:$,providerId:W,settings:Z,credentials:Q,setLastUsed:J?.setLastUsed})}async function TY($,W,Z,Q){let J=V6({onPrompt:async(j)=>j.defaultValue??"",openUrl:Z,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return K4($,W,{callbacks:J,telemetry:Q})}function zY($){let W=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return W&&W.length>0?W:void 0}var Vf={};w(Vf,{getProviderConfigFields:()=>qY});import*as L7 from"@cline/llms";var lg=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],pg={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function rg($,W){let Z={};for(let Q of lg){let J=$[Q],j=W[Q];if(J||j)Z[Q]={...J,...j}}return Z}function ig($){let W=pg[$.providerId];if(!W)return $;return{...$,description:W.description??$.description,fields:W.mode==="replace"?W.fields:rg($.fields,W.fields)}}var ng=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function ag($,W){if(!W?.provider.baseUrl)return!1;if(W.provider.source!=="system")return!0;return ng.has($)}function qY($){let W=L7.normalizeProviderId($);if(L$(W))return{providerId:W,authMethod:"oauth",fields:{}};let Z=L7.MODEL_COLLECTIONS_BY_PROVIDER_ID[W];if(Z?.provider.capabilities?.includes("local-auth"))return{providerId:W,authMethod:"local",fields:{}};let Q=Z?.provider.baseUrl,J={apiKey:{}};if(ag(W,Z))J.baseUrl={defaultValue:Q};return ig({providerId:W,authMethod:"api-key",fields:J})}var Kf={};w(Kf,{resolveLegacyClineAuth:()=>NY,migrateLegacyProviderSettings:()=>uW});import{existsSync as og,readFileSync as sg}from"node:fs";import{dirname as tg,join as MY}from"node:path";import*as e6 from"@cline/llms";import{resolveClineDataDir as eg}from"@cline/shared/storage";var O7="openai",Gf=e6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,Bf=128000;function NY($){let W=$?.trim();if(!W)return;try{let Z=JSON.parse(W);if(!Z)return;let Q=typeof Z.expiresAt==="number"&&Number.isFinite(Z.expiresAt)?Z.expiresAt<10000000000?Z.expiresAt*1000:Z.expiresAt:void 0;return{accessToken:Z.idToken,refreshToken:Z.refreshToken,expiresAt:Q,accountId:Z.userInfo?.id}}catch{return}}function y($){let W=$?.trim();return W?W:void 0}function $m($){return $==="credentials"?"iam":$}function Hf($){if(!og($))return;try{let W=sg($,"utf8"),Z=JSON.parse(W);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function Wm($){let W=$.dataDir??eg(),Z=$.globalStatePath??MY(W,"globalState.json"),Q=$.secretsPath??MY(W,"secrets.json"),J=Hf(Z),j=Hf(Q);if(!J&&!j)return;return{globalState:J??{},secrets:j??{}}}function RY($){if($===O7)return Gf;return $}function Zm($,W,Z,Q){let J=Z==="plan"?"planMode":"actMode",j=W===Q?y(Z==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,Y={openrouter:`${J}OpenRouterModelId`,cline:`${J}ClineModelId`,openai:`${J}OpenAiModelId`,ollama:`${J}OllamaModelId`,lmstudio:`${J}LmStudioModelId`,litellm:`${J}LiteLlmModelId`,requesty:`${J}RequestyModelId`,together:`${J}TogetherModelId`,fireworks:`${J}FireworksModelId`,sapaicore:`${J}SapAiCoreModelId`,groq:`${J}GroqModelId`,baseten:`${J}BasetenModelId`,huggingface:`${J}HuggingFaceModelId`,"huawei-cloud-maas":`${J}HuaweiCloudMaasModelId`,oca:`${J}OcaModelId`,aihubmix:`${J}AihubmixModelId`,hicap:`${J}HicapModelId`,nousResearch:`${J}NousResearchModelId`,"vercel-ai-gateway":`${J}VercelAiGatewayModelId`}[W];return(Y?y(typeof $[Y]==="string"?$[Y]:void 0):void 0)??j}function Qm($,W,Z){let Q=Z==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...W==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...W==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(y).find(Boolean),j=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,X=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!j&&X===void 0)return;return{...j?{effort:j}:{},...X!==void 0?{budgetTokens:X}:{}}}function Jm($){let W=$["openai-codex-oauth-credentials"];if(!W)return;try{let Z=JSON.parse(W),Q=y(Z.access_token),J=y(Z.refresh_token),j=y(Z.accountId);if(!Q&&!J&&!j)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...J?{refreshToken:J}:{},...j?{accountId:j}:{}}}}catch{return}}function jm($){let W=e6.getGeneratedModelsForProvider($),Q=e6.getProviderCollectionSync($)?.provider.defaultModelId;if(Q&&W[Q])return Q;return Object.keys(W)[0]??void 0}function Xm($,W,Z,Q){let J=RY($),j=y(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),X=Zm(W,$,Q,j)??jm(J),Y=Qm(W,J,Q),V=typeof W.requestTimeoutMs==="number"&&Number.isInteger(W.requestTimeoutMs)&&W.requestTimeoutMs>0?W.requestTimeoutMs:void 0,B={anthropic:Z.apiKey,cline:Z.clineApiKey,openai:Z.openAiApiKey,"openai-native":Z.openAiNativeApiKey,openrouter:Z.openRouterApiKey,bedrock:Z.awsBedrockApiKey,gemini:Z.geminiApiKey,ollama:Z.ollamaApiKey,deepseek:Z.deepSeekApiKey,requesty:Z.requestyApiKey,together:Z.togetherApiKey,fireworks:Z.fireworksApiKey,qwen:Z.qwenApiKey,doubao:Z.doubaoApiKey,mistral:Z.mistralApiKey,litellm:Z.liteLlmApiKey,asksage:Z.asksageApiKey,xai:Z.xaiApiKey,moonshot:Z.moonshotApiKey,zai:Z.zaiApiKey,huggingface:Z.huggingFaceApiKey,nebius:Z.nebiusApiKey,sambanova:Z.sambanovaApiKey,cerebras:Z.cerebrasApiKey,groq:Z.groqApiKey,"huawei-cloud-maas":Z.huaweiCloudMaasApiKey,baseten:Z.basetenApiKey,"vercel-ai-gateway":Z.vercelAiGatewayApiKey,dify:Z.difyApiKey,minimax:Z.minimaxApiKey,hicap:Z.hicapApiKey,aihubmix:Z.aihubmixApiKey,nousResearch:Z.nousResearchApiKey,oca:Z.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,Jm(Z));if($==="cline")try{let f=y(Z["cline:clineAccountId"]);if(f)H.auth={...H.auth??{},...NY(f)}}catch{}if($===O7&&W.openAiHeaders)H.headers=W.openAiHeaders;if($==="bedrock"){let f=$m(W.awsAuthentication),_=f==="profile"||W.awsUseProfile===!0;H.aws={accessKey:y(Z.awsAccessKey),secretKey:y(Z.awsSecretKey),sessionToken:y(Z.awsSessionToken),region:y(W.awsRegion),authentication:f,profile:_?y(W.awsProfile):void 0,usePromptCache:W.awsBedrockUsePromptCache,useCrossRegionInference:W.awsUseCrossRegionInference,useGlobalInference:W.awsUseGlobalInference,endpoint:y(W.awsBedrockEndpoint),customModelBaseId:y(Q==="plan"?W.planModeAwsBedrockCustomModelBaseId:W.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:y(W.vertexProjectId),region:y(W.vertexRegion)};if($===O7&&(W.azureApiVersion||W.azureIdentity!==void 0))H.azure={apiVersion:y(W.azureApiVersion),useIdentity:W.azureIdentity};if($==="sapaicore"){let f=W.sapAiCoreUseOrchestrationMode??!0;H.sap={clientId:y(Z.sapAiCoreClientId),clientSecret:y(Z.sapAiCoreClientSecret),tokenUrl:y(W.sapAiCoreTokenUrl),resourceGroup:y(W.sapAiResourceGroup),deploymentId:f?void 0:y(Q==="plan"?W.planModeSapAiCoreDeploymentId:W.actModeSapAiCoreDeploymentId),useOrchestrationMode:f}}if($==="oca"){H.oca={mode:W.ocaMode};let f=y(Z.ocaRefreshToken);if(f)H.auth={...H.auth??{},refreshToken:f}}if($==="qwen")H.apiLine=W.qwenApiLine;if($==="moonshot")H.apiLine=W.moonshotApiLine;if($==="zai")H.apiLine=W.zaiApiLine;if($==="minimax")H.apiLine=W.minimaxApiLine;let G={anthropic:W.anthropicBaseUrl,openai:W.openAiBaseUrl,ollama:W.ollamaBaseUrl,lmstudio:W.lmStudioBaseUrl,litellm:W.liteLlmBaseUrl,gemini:W.geminiBaseUrl,requesty:W.requestyBaseUrl,asksage:W.asksageApiUrl,dify:W.difyBaseUrl,oca:W.ocaBaseUrl,aihubmix:W.aihubmixBaseUrl,sapaicore:W.sapAiCoreBaseUrl},K=y(B[$]),F=y(G[$]),A={provider:J,...K?{apiKey:K}:{},...X?{model:X}:{},...F?{baseUrl:F}:{},...Y?{reasoning:Y}:{},...V?{timeout:V}:{},...H},D=J6.safeParse(A);if(!D.success)return;return Object.keys(A).filter((f)=>f!=="provider").length>0?D.data:void 0}function Ym($,W){if($!==Gf)return;if(!W.baseUrl||!W.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:W.baseUrl,defaultModelId:W.model},models:{[W.model]:{id:W.model,name:W.model,contextWindow:Bf,maxInputTokens:Bf,capabilities:["streaming","tools","images"]}}}}function Vm($,W){let Z=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let j=y(J);if(j)Z.add(j)}if(y(W.apiKey))Z.add("anthropic");if(y(W.openRouterApiKey))Z.add("openrouter");if(y(W.openAiApiKey))Z.add(O7);if(y(W.openAiNativeApiKey))Z.add("openai-native");if(y(W["openai-codex-oauth-credentials"]))Z.add("openai-codex");if(y(W.geminiApiKey))Z.add("gemini");if(y(W.ollamaApiKey))Z.add("ollama");if(y(W.awsAccessKey)||y(W.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||y($.awsProfile))Z.add("bedrock");if(y($.vertexProjectId)||y($.vertexRegion))Z.add("vertex");if(y(W.clineApiKey))Z.add("cline");let Q=NY(y(W["cline:clineAccountId"]));if(Q?.accessToken||Q?.refreshToken||Q?.accountId)Z.add("cline");if(y(W.ocaApiKey))Z.add("oca");if(y(W.sapAiCoreClientId)||y(W.sapAiCoreClientSecret)||y($.sapAiCoreTokenUrl)||y($.sapAiCoreBaseUrl)||y($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Z.add("sapaicore");return Z}function uW($){let W=$.providerSettingsManager.read(),Z=Wm($);if(!Z)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let{globalState:Q,secrets:J}=Z,j=Q.mode==="plan"?"plan":"act",X=Vm(Q,J),Y=x$();Y.providers={...W.providers},Y.lastUsedProvider=W.lastUsedProvider;let V=new Date().toISOString(),B=0,H=MY(tg($.providerSettingsManager.getFilePath()),"models.json"),G=t6(H),K=0;for(let D of X){let U=RY(D);if(Y.providers[U])continue;let f=Xm(D,Q,J,j);if(!f)continue;Y.providers[U]={settings:f,updatedAt:V,tokenSource:"migration"},B+=1;let _=Ym(U,f);if(_&&!G.providers[U])G.providers[U]=_,K+=1}if(B===0&&K===0)return{migrated:!1,providerCount:Object.keys(W.providers).length,lastUsedProvider:W.lastUsedProvider};let F=y(j==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),A=F?RY(F):void 0;if(Y.lastUsedProvider=W.lastUsedProvider??(A&&Y.providers[A]?A:Object.keys(Y.providers)[0]),$.providerSettingsManager.write(Y),K>0)xW(H,G);return{migrated:B>0||K>0,providerCount:Object.keys(Y.providers).length,lastUsedProvider:Y.lastUsedProvider}}uQ();U0();fW();var Ff={};w(Ff,{FileTeamPersistenceStore:()=>T7});import{appendFileSync as Bm,existsSync as EY,mkdirSync as Hm,readFileSync as Gm,renameSync as Km,unlinkSync as Fm,writeFileSync as Am}from"node:fs";import{join as wY}from"node:path";import{resolveTeamDataDir as Um}from"@cline/shared/storage";function Dm($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class T7{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let W=Dm($.teamName),Z=$.baseDir?.trim()||Um();this.dirPath=wY(Z,W),this.statePath=wY(this.dirPath,"state.json"),this.taskHistoryPath=wY(this.dirPath,"task-history.jsonl")}loadState(){if(!EY(this.statePath))return;try{let $=Gm(this.statePath,"utf8"),W=JSON.parse($);if(W.version!==1||!W.teamState)return;for(let Z of W.teammates??[])this.teammateSpecs.set(Z.agentId,Z);return TU(W.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let W={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Z=`${this.statePath}.tmp`;Am(Z,`${JSON.stringify(W,null,2)}
757
+ `,"utf8"),Km(Z,this.statePath)}appendTaskHistory($){let W={};switch($.type){case"team_task_updated":W=$.task;break;case"team_message":W={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":W={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":W={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":W={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":W={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Bm(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:W})}
758
+ `,"utf8")}ensureDir(){if(!EY(this.dirPath))Hm(this.dirPath,{recursive:!0})}hasPersistableState($){let W=$.exportState();if(this.teammateSpecs.size>0)return!0;if(W.members.some((Z)=>Z.role==="teammate"))return!0;return W.tasks.length>0||W.mailbox.length>0||W.missionLog.length>0}clearPersistedState(){if(EY(this.statePath))Fm(this.statePath)}}var Af={};w(Af,{ChatViewStateSchema:()=>CY,ChatSummarySchema:()=>N7,ChatSessionStatusSchema:()=>q7,ChatSessionConfigSchema:()=>z7,ChatMessageSchema:()=>R7,ChatMessageRoleSchema:()=>M7});import{z as I}from"zod";var z7=I.object({workspaceRoot:I.string().min(1),cwd:I.string().optional(),provider:I.string().min(1),model:I.string().min(1),mode:I.enum(["act","plan"]).default("act"),apiKey:I.string(),systemPrompt:I.string().optional(),rules:I.string().optional(),maxIterations:I.number().int().positive().optional(),enableTools:I.boolean(),enableSpawn:I.boolean().optional(),enableTeams:I.boolean().optional(),autoApproveTools:I.boolean().optional(),missionStepInterval:I.number().int().positive().optional(),missionTimeIntervalMs:I.number().int().positive().optional()}),q7=I.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),M7=I.enum(["user","assistant","tool","system","status","error"]),R7=I.object({id:I.string().min(1),sessionId:I.string().nullable(),role:M7,content:I.string(),createdAt:I.number().int().nonnegative(),meta:I.object({stream:I.enum(["stdout","stderr"]).optional(),toolName:I.string().optional(),iteration:I.number().int().nonnegative().optional(),agentId:I.string().optional(),conversationId:I.string().optional(),hookEventName:I.string().optional(),inputTokens:I.number().int().nonnegative().optional(),outputTokens:I.number().int().nonnegative().optional(),checkpoint:I.object({ref:I.string(),createdAt:I.number().int().nonnegative(),runCount:I.number().int().positive(),kind:I.enum(["stash","commit"]).optional()}).optional()}).optional()}),N7=I.object({toolCalls:I.number().int().nonnegative(),tokensIn:I.number().int().nonnegative(),tokensOut:I.number().int().nonnegative()}),CY=I.object({sessionId:I.string().nullable(),status:q7,config:z7,messages:I.array(R7),rawTranscript:I.string(),error:I.string().nullable(),summary:N7});var Uf={};w(Uf,{CORE_BUILD_VERSION:()=>dW});var dW=p8;import{Agent as Av,createAgentRuntime as Uv}from"@cline/agents";var Df={};w(Df,{fetchClineRecommendedModels:()=>SY,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>E7});import{getClineEnvironmentConfig as _m}from"@cline/shared";var fm=5000,E7={recommended:[{id:"anthropic/claude-opus-4.6",name:"Claude Opus 4.6",description:"Most intelligent model for agents and coding",tags:["BEST"]},{id:"anthropic/claude-sonnet-4.6",name:"Claude Sonnet 4.6",description:"Strong coding and agent performance",tags:["NEW"]},{id:"google/gemini-3.1-pro-preview",name:"Gemini 3.1 Pro Preview",description:"1M context window, strong coding performance",tags:["NEW"]},{id:"openai/gpt-5.3-codex",name:"GPT-5.3 Codex",description:"OpenAI's latest with strong coding abilities",tags:["NEW"]}],free:[{id:"kwaipilot/kat-coder-pro",name:"KwaiKAT Kat Coder Pro",description:"Advanced agentic coding model",tags:["FREE"]},{id:"arcee-ai/trinity-large-preview:free",name:"Arcee AI Trinity Large Preview",description:"Advanced large preview model",tags:["FREE"]}],clinePass:[]};function Lm($){return{recommended:$.recommended.map((W)=>({...W,tags:[...W.tags]})),free:$.free.map((W)=>({...W,tags:[...W.tags]})),clinePass:$.clinePass.map((W)=>({...W,tags:[...W.tags]}))}}function PY($){if(!$||typeof $!=="object")return null;let W=$;if(typeof W.id!=="string"||W.id.length===0)return null;return{id:W.id,name:typeof W.name==="string"&&W.name.length>0?W.name:W.id,description:typeof W.description==="string"?W.description:"",tags:Array.isArray(W.tags)?W.tags.filter((Z)=>typeof Z==="string"):[]}}function Om($){if(!$||typeof $!=="object")return null;let W=$,Z=Array.isArray(W.recommended)?W.recommended:[],Q=Array.isArray(W.free)?W.free:[],J=Array.isArray(W.clinePass)?W.clinePass:[],j=Z.map(PY).filter((V)=>V!==null),X=Q.map(PY).filter((V)=>V!==null),Y=J.map(PY).filter((V)=>V!==null);if(j.length===0&&X.length===0&&Y.length===0)return null;return{recommended:j,free:X,clinePass:Y}}function Tm($){let W=$.baseUrl?.trim();if(W)return W;let Z=_m().apiBaseUrl;try{return($.providerSettingsManager??new B1).getProviderSettings("cline")?.baseUrl?.trim()||Z}catch{return Z}}async function zm($,W,Z){let Q=new AbortController,J=setTimeout(()=>Q.abort(),Z);try{return await $(W,{signal:Q.signal})}finally{clearTimeout(J)}}async function SY($={}){try{let W=Tm($),Z=$.fetchImpl??fetch,Q=await zm(Z,`${W}/api/v1/ai/cline/recommended-models`,$.timeoutMs??fm);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let J=await Q.json(),j=Om(J);if(j)return j}catch{}return Lm(E7)}var _f={};w(_f,{loadLlmsConfigFromFile:()=>yY,defineLlmsConfig:()=>bY});import{readFile as qm}from"node:fs/promises";import Mm from"node:path";function bY($){return $}async function yY($){let W=Mm.resolve($),Z=await qm(W,"utf8"),Q;try{Q=JSON.parse(Z)}catch(J){let j=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${W}": ${j}`)}return Rm(Q,W)}function Rm($,W){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${W}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${W}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${W}": "providers" cannot be empty.`);return $}var qf={};w(qf,{createLlmsSdk:()=>kY,DefaultLlmsSdk:()=>lW});import{BUILT_IN_PROVIDER_IDS as Of,createHandler as wm,createHandlerAsync as Cm,getProviderCollection as Pm,hasProvider as Tf,registerAsyncHandler as Sm,registerHandler as bm,registerModel as ym,registerProvider as zf}from"@cline/llms";function ff($){return $?{...$}:{}}function Nm($,W){if($)return $;if(!W)return;let Z=globalThis.process;if(!Z?.env)return;return Z.env[W]}function Em($,W){if(!W.length)throw Error(`Provider "${$}" must include at least one model.`)}function Lf($){let W=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:W,defaultModel:$.collection.provider.defaultModelId,modelCount:W.length}}class hY{providers=new Map;register($){Em($.id,$.models);let W=$.defaultModel??$.models[0];if(!W)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(W))throw Error(`Default model "${W}" is not included in configured models for "${$.id}".`);let Z=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Z?.models??[],...$.models]),defaultModel:W,defaults:{...Z?.defaults??{},...ff($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Nm($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...ff($.settings)}})}registerModel($,W){let Z=this.providers.get($);if(!Z){this.providers.set($,{id:$,models:new Set([W]),defaultModel:W,defaults:{}});return}Z.models.add(W)}createHandlerConfig($){let W=this.require($.providerId),Z=$.modelId??W.defaultModel;if(!W.models.has(Z))throw Error(`Model "${Z}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Z,...W.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,W){return this.providers.get($)?.models.has(W)??!1}require($){let W=this.providers.get($);if(!W)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return W}}class lW{configuredProviders=new hY;constructor($){this.applyConfig($)}createHandler($){return wm(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return Cm(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(zf($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)bm($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)Sm($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let W=$.exposeModels??Object.keys($.models),Z=$.defaultModel??W[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);zf({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Z,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:W,defaultModel:Z,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){ym($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...Of]}async getBuiltInProviders(){return(await Promise.all(Of.map((W)=>Pm(W)))).filter((W)=>W!==void 0).map((W)=>Lf({collection:W}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,W){return this.configuredProviders.hasModel($,W)}applyConfig($){for(let W of $.providers)this.configuredProviders.registerSelectionConfig(W);for(let W of $.models??[])this.registerModel(W);for(let W of $.customProviders??[])this.registerProvider(W);for(let W of this.configuredProviders.list()){let Z=Tf(W.id),Q=this.configuredProviders.createHandlerConfig({providerId:W.id,modelId:W.defaultModel}).routingProviderId,J=typeof Q==="string"&&Tf(Q);if(!Z&&!J)throw Error(`Provider "${W.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function kY($){return new lW($)}tj();async function hm(){return Promise.resolve().then(() => (uQ(),J_))}function zv(){return new Date().toISOString()}var qv="cline",Mv="cline-pass";function Rv($){if(Ef($)!=="providers.json")return;let W=xY($);if(Ef(W)!=="settings")return;return xY(W)}class B1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Tv(),this.dataDir=$.dataDir??Rv(this.filePath),this.dataDir||!$.filePath)uW({providerSettingsManager:this,dataDir:this.dataDir});if(vW(this),mW(this.read()),IY(this.filePath))try{Nf(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!IY(this.filePath))return x$();try{let $=_v(this.filePath,"utf8"),W=JSON.parse($),Z=j6.safeParse(W);if(Z.success){mW(Z.data);let Q=Z.data.providers.cline?.settings?.auth;return s(`providers.read providers=[${Object.keys(Z.data.providers).join(",")}] lastUsed=${Z.data.lastUsedProvider??"none"} clineAuthPresent=${!!Q?.accessToken} clineAccessTokenHash=${M0(Q?.accessToken)} clineRefreshTokenHash=${M0(Q?.refreshToken)}`),Z.data}}catch{}return x$()}write($){let W=j6.parse($),Z=xY(this.filePath);if(!IY(Z))Dv(Z,{recursive:!0,mode:448});let Q=`${this.filePath}.${process.pid}.tmp`;try{Ov(Q,`${JSON.stringify(W,null,2)}
759
+ `,{encoding:"utf8",mode:384}),fv(Q,this.filePath)}catch(J){throw Lv(Q,{force:!0}),J}try{Nf(this.filePath,384)}catch{}mW(W)}saveProviderSettings($,W={}){let Z=J6.parse($),Q=this.read(),J=Z.provider,j=W.setLastUsed!==!1,X=Q.providers[J],Y=W.tokenSource??X?.tokenSource??"manual",V={...Q,providers:{...Q.providers,[J]:{settings:Z,updatedAt:zv(),tokenSource:Y}},lastUsedProvider:j?J:Q.lastUsedProvider};this.write(V);let B=Q.providers.cline?.settings?.auth,H=Z.provider==="cline"?Z.auth:V.providers.cline?.settings?.auth,G=!!B?.accessToken&&!H?.accessToken;return s(`providers.save providerId=${J} tokenSource=${Y} clineAuthWasPresent=${!!B?.accessToken} clineAuthIsPresent=${!!H?.accessToken} authDropped=${G}`),V}resolveProviderSettings($,W){let Z=$.providers[W]?.settings,J=B0(W)?.storageProviderId;if(!J||J===W)return Z;let j=$.providers[J]?.settings;if(!j)return Z;return J6.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Z??{},provider:W})}getProviderSettings($){let W=this.read();return this.resolveProviderSettings(W,$)}resolveLastUsedProviderId($,W){let Z=$.lastUsedProvider;if(Z===Mv&&W.isClinePassEnabled===!1)return qv;return Z}getLastUsedProviderSettings($={}){let W=this.read(),Z=this.resolveLastUsedProviderId(W,$);if(!Z)return;return this.resolveProviderSettings(W,Z)}getProviderConfig($,W){let Z=this.getProviderSettings($);if(!Z)return;return $1(Z,W)}getLastUsedProviderConfig($={}){let W=this.getLastUsedProviderSettings($);if(!W)return;return $1(W,$)}async refreshCatalog(){try{await Z6({})}catch{}}}U0();R6();function Nv($,W){let Z=$?.expiresAt,Q=W?.expiresAt;return $?.accessToken===W?.accessToken&&$?.refreshToken===W?.refreshToken&&$?.accountId===W?.accountId&&Z===Q}class w7 extends Error{providerId;constructor($){super(`OAuth credentials for provider "${$}" are no longer valid. Re-run authentication for this provider.`);this.name="OAuthReauthRequiredError",this.providerId=$}}class gY{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new B1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let W=B0($.providerId);if(!W)return null;return this.resolveWithSingleFlight(W.providerId,W.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,W,Z=!1){let Q=this.refreshInFlight.get(W);if(Q)return Q;let J=this.resolveProviderApiKeyInternal($,W,Z).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(W)});return this.refreshInFlight.set(W,J),J}async resolveProviderApiKeyInternal($,W,Z){let Q=B0($);if(!Q)return null;let J=this.providerSettingsManager.getProviderSettings(W);if(!J)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_settings`),null;let j=F4($,J);if(!j)return s(`oauth.resolve providerId=${$} storageProviderId=${W} outcome=no_credentials`),null;s(`oauth.resolve.start providerId=${$} storageProviderId=${W} forceRefresh=${Z} accessTokenHash=${M0(j.access)} refreshTokenHash=${M0(j.refresh)}`);let X=await Q.refresh({settings:J,credentials:j,forceRefresh:Z,telemetry:this.telemetry});if(!X)throw s(`oauth.resolve providerId=${$} outcome=refresh_returned_null`),new w7($);let Y=j2({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:X,setLastUsed:!1,save:!1}),V=!Nv(J.auth,Y.auth);if(V)s(`oauth.resolve.refreshed providerId=${$} newAccessTokenHash=${M0(X.access)} newRefreshTokenHash=${M0(X.refresh)} savingToDisk=true`),this.providerSettingsManager.saveProviderSettings(Y,{setLastUsed:!1,tokenSource:"oauth"});else s(`oauth.resolve providerId=${$} outcome=not_refreshed`);return{apiKey:Q.getApiKey(Y)??X.access,accountId:X.accountId,refreshed:V}}}import{normalizeUserInput as Ev}from"@cline/shared";import{nanoid as wv}from"nanoid";class wf{list($){return $?H1($):[]}update($,W){if(!$)return{sessionId:W.sessionId,prompts:[],updated:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((V)=>V.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:H1($),updated:!1};let J=$.pendingPrompts[Q];if(!J)return{sessionId:W.sessionId,prompts:H1($),updated:!1};let j=W.prompt===void 0?J.prompt:Ev(W.prompt).trim();if(!j)throw Error("prompt cannot be empty");let X=W.delivery??J.delivery,Y={...J,prompt:j,mode:W.mode??J.mode,delivery:X};return $.pendingPrompts.splice(Q,1),Cv($,Y,Q,J.delivery),{sessionId:W.sessionId,prompts:H1($),prompt:C7(Y),updated:!0}}delete($,W){if(!$)return{sessionId:W.sessionId,prompts:[],removed:!1};let Z=W.promptId.trim(),Q=$.pendingPrompts.findIndex((j)=>j.id===Z);if(Q<0)return{sessionId:W.sessionId,prompts:H1($),removed:!1};let[J]=$.pendingPrompts.splice(Q,1);return{sessionId:W.sessionId,prompts:H1($),prompt:J?C7(J):void 0,removed:!0}}enqueue($,W){let{prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X}=W,Y=$.pendingPrompts.findIndex((V)=>V.prompt===Z);if(Y>=0){let[V]=$.pendingPrompts.splice(Y,1),B={...V,prompt:Z,mode:Q??V.mode,userImages:j??V.userImages,userFiles:X??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...B,delivery:"steer"});else $.pendingPrompts.push(B)}else{let V={id:`pending_${Date.now()}_${wv(5)}`,prompt:Z,mode:Q,delivery:J,userImages:j,userFiles:X};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return H1($)}consumeSteer($){let W=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(W<0)return{prompts:H1($)};let[Z]=$.pendingPrompts.splice(W,1);return{entry:Z,prompts:H1($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:H1($)}}requeueFront($,W){return $.pendingPrompts.unshift(W),H1($)}clear($){return $.pendingPrompts.length=0,[]}}class mY{deps;service=new wf;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Z=this.service.update(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}delete($){let W=this.deps.getSession($.sessionId);if(!W||W.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Z=this.service.delete(W,$);return this.emitPrompts(W),this.scheduleDrain($.sessionId,W),Z}enqueue($,W){let Z=this.deps.getSession($);if(!Z||Z.aborting)return;this.service.enqueue(Z,W),this.emitPrompts(Z),this.scheduleDrain($,Z)}consumeSteer($){let W=this.deps.getSession($);if(!W)return;let{entry:Z}=this.service.consumeSteer(W);if(!Z)return;return this.emitPrompts(W),this.emitSubmitted(W,Z),Z}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:H1($)}})}scheduleDrain($,W){if(W.pendingPrompts.length===0||W.aborting||W.drainingPendingPrompts||!W.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let W=this.deps.getSession($);if(!W)return;if(W.aborting||W.drainingPendingPrompts)return;if(!W.agent.canStartRun())return;let{entry:Z}=this.service.shiftNext(W);if(!Z)return;this.emitPrompts(W),this.emitSubmitted(W,Z),W.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:Z.prompt,...Z.mode?{mode:Z.mode}:{},userImages:Z.userImages,userFiles:Z.userFiles})}catch{Q=!1,this.service.requeueFront(W,Z),this.emitPrompts(W)}finally{if(W.drainingPendingPrompts=!1,Q&&W.pendingPrompts.length>0&&W.status!=="failed"&&W.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,W){let Z=C7(W);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Z.id,prompt:Z.prompt,delivery:Z.delivery,attachmentCount:Z.attachmentCount,userImages:Z.userImages,userFiles:Z.userFiles}})}}function C7($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function H1($){return $.pendingPrompts.map(C7)}function Cv($,W,Z,Q){if(W.delivery==="steer")$.pendingPrompts.unshift(W);else if(Q==="steer")$.pendingPrompts.push(W);else $.pendingPrompts.splice(Z,0,W)}U0();class cY{deps;constructor($){this.deps=$}dispatchAgentEvent($,W,Z){let Q=this.deps.getSession($),J={sessionId:$,config:W,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=v3(Z),X=!!Q&&(!j.agentId||j.agentId===vY(Q.agent));c3(J,Z,X?{isPrimaryAgentEvent:!0,agentId:vY(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,W){let Z=this.deps.getSession($);if(Z){if(bj(Z,W),W.type==="agent_event"){let Q={sessionId:$,config:Z.config,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};c3(Q,W.event,{agentId:W.agentId,teamRole:"teammate",teamAgentId:W.agentId,isPrimaryAgentEvent:!1})}if(W.type==="teammate_spawned"){let Q=s1({agentId:W.teammate.runtimeAgentId??W.agentId,conversationId:W.teammate.conversationId,parentAgentId:W.teammate.parentAgentId,createdByAgentId:vY(Z.agent),teamId:Z.runtime.teamRuntime?.getTeamId(),teamName:Z.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:W.agentId});if(Q)_$(Z.config.telemetry,{ulid:$,modelId:W.teammate.modelId??Z.config.modelId,provider:Z.config.providerId,...Q})}}if(await yj($,W,this.deps.invokeBackendOptional),Z)hj(Z,$,W,this.deps.emit)}async handlePluginEvent($,W,Z){if(W.name==="plugin_log"){this.handlePluginLog($,W.payload);return}if(W.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Z;if(!V)return;let B=W.payload&&typeof W.payload==="object"?W.payload:void 0;if(!B)return;await V.ingestEvent(B);return}if(W.name!=="steer_message"&&W.name!=="queue_message"&&W.name!=="pending_prompt")return;let Q=W.payload&&typeof W.payload==="object"?W.payload:void 0,J=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,j=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!j)return;let X=W.name==="steer_message"?"steer":W.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:j,delivery:X})}handlePluginLog($,W,Z){let Q=this.deps.getSession($),J=Z??Q?.config.extensionContext?.logger??Q?.config.logger;if(!J||!W||typeof W!=="object")return;let j=W,X=typeof j.message==="string"?j.message:"";if(!X)return;let Y=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(Y.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)Y.pluginName=j.pluginName;if(j.level==="debug"){J.debug(X,Y);return}if(j.level==="error"){if(J.error)J.error(X,Y);else J.log(X,{...Y,severity:"error"});return}J.log(X,Y)}}function vY($){return $.getAgentId()}function uY($){return{sessionId:$.sessionId,source:$.source,pid:process.pid,startedAt:$.startedAt,endedAt:$.endedAt??null,exitCode:$.exitCode??null,status:$.status,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:t1($.config),teamName:$.config.teamName?.trim()||void 0,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,parentSessionId:typeof $.sessionMetadata?.parentSessionId==="string"?$.sessionMetadata.parentSessionId:void 0,parentAgentId:typeof $.sessionMetadata?.parentAgentId==="string"?$.sessionMetadata.parentAgentId:void 0,agentId:typeof $.sessionMetadata?.agentId==="string"?$.sessionMetadata.agentId:void 0,conversationId:typeof $.sessionMetadata?.conversationId==="string"?$.sessionMetadata.conversationId:void 0,isSubagent:typeof $.sessionMetadata?.isSubagent==="boolean"?$.sessionMetadata.isSubagent:!1,prompt:$.pendingPrompt,metadata:$.sessionMetadata,messagesPath:$.artifacts?.messagesPath,updatedAt:$.updatedAt??$.endedAt??$.startedAt}}function dY($,W){let Z=$[W];return typeof Z==="function"?Z:null}async function Cf($,W,...Z){let Q=dY($,W);if(!Q)throw Error(`session service method not available: ${W}`);return Promise.resolve(Q.apply($,Z))}async function Pf($,W,...Z){let Q=dY($,W);if(!Q)return;await Promise.resolve(Q.apply($,Z))}async function Sf($,W,...Z){let Q=dY($,W);if(!Q)return;return await Promise.resolve(Q.apply($,Z))}_1();U0();function lY($,W,Z){return{onSubAgentEvent:(Q)=>$.onAgentEvent(Z,W,Q),onSubAgentStart:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:Z});let j=s1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId});if(j)_$(W.telemetry,{ulid:Z,modelId:W.modelId,provider:W.providerId,...j});Q4(W.telemetry,{event:"started",ulid:Z,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Z,Q)},onSubAgentEnd:(Q)=>{let J=$.getSession(Z)?.runtime.teamRuntime,j=$.subAgentStarts.get(Q.subAgentId),X=j?Date.now()-j.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
760
+ `).length:0;Q4(W.telemetry,{event:"ended",ulid:Z,durationMs:X,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...s1({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Z,Q)}}}function pY($,W,Z,Q){let J=lY($,W,Z);return P$({configProvider:{getRuntimeConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:W.providerId,modelId:W.modelId,cwd:W.cwd,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking,maxIterations:W.maxIterations,hooks:W.hooks,extensions:W.extensions,logger:W.logger,telemetry:W.telemetry},getConnectionConfig:()=>$.getSession(Z)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:W.providerId,modelId:W.modelId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,providerConfig:W.providerConfig,knownModels:W.knownModels,thinking:W.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let X=W.enableTools?N2({cwd:W.cwd,...t0[n1({mode:W.mode})],executors:Q}):[];if(W.enableSpawnAgent)X.push(pY($,W,Z,Q));return a1(X)},...J})}import{readFile as Pv,stat as Sv}from"node:fs/promises";var bv=20480000;async function bf($){let W=await Sv($);if(!W.isFile())throw Error("Path is not a file");if(W.size>bv)throw Error("File is too large to read into context.");let Z=await Pv($,"utf8");if(Z.includes("\x00"))throw Error("Cannot read binary file into context.");return Z}var yf=5000;function pW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function vv($){if(!$||typeof $!=="object"||Array.isArray($))return;let W=$,Z=pW(W.inputTokens),Q=pW(W.outputTokens),J=pW(W.cacheReadTokens),j=pW(W.cacheWriteTokens),X=pW(W.totalCost);if(Z===void 0||Q===void 0||J===void 0||j===void 0||X===void 0)return;return{inputTokens:Z,outputTokens:Q,cacheReadTokens:J,cacheWriteTokens:j,totalCost:X}}function cv($,W){return{inputTokens:Math.max($.inputTokens,W.inputTokens),outputTokens:Math.max($.outputTokens,W.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,W.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,W.cacheWriteTokens),totalCost:Math.max($.totalCost,W.totalCost)}}function hf($,W){if(!W)return!1;if($.source_message_count!==W.source_message_count)return $.source_message_count<W.source_message_count;return Date.parse($.updated_at)<Date.parse(W.updated_at)}class k1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new t5;sessions=new Map;manifestMutationQueues=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new t$;constructor($){let W=hv();if(W)mv(W);let Z=d0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new i6,this.createAgentInstance=$.createAgent??((Q)=>new E$(Q)),this.defaultCapabilities=w0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new B1,this.oauthTokenManager=$.oauthTokenManager??new gY({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Z),this.defaultFetch=$.fetch,this.pendingPromptsController=new mY({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new cY({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,J,j)=>{this.invoke("persistSessionMessages",Q,J,j)},enqueuePendingPrompt:(Q,J)=>this.pendingPromptsController.enqueue(Q,J),invokeBackendOptional:(Q,...J)=>this.invokeOptional(Q,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let W=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!W?.apiKey)return $;return{...$,config:{...$.config,apiKey:W.apiKey}}}async startSession($){let W=$.source??K0.CLI,Z=X0(),Q=$.config.sessionId?.trim()??"",J=Q||Iv(),j=await this.applyInitialOAuthCredentials($),X=j.initialMessages??[],Y=X.length>0?l8(X):z0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let B=rY(V,J),H=rY(B,`${J}.messages.json`),G=rY(B,`${J}.json`),K=t1($.config),F=m0.parse({version:1,session_id:J,source:W,pid:process.pid,started_at:Z,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:K,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,messages_path:H}),A,D;if(Q.length>0&&X.length>0&&!j.prompt?.trim()){let b=await this.invokeOptionalValue("readSessionManifest",J);if(b)F=b,A={manifestPath:G,messagesPath:b.messages_path||H,compactionPath:b.compaction_path,manifest:b},D=await this.invokeOptionalValue("readSessionCompactionState",J)}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:Y,sessionDir:B,rootMessagesPath:A?.messagesPath??H,manifest:F});this.usageBySession.set(J,Y),this.aggregateUsageBySession.set(J,f);let _=w0(this.defaultCapabilities,$.capabilities),R=_?.toolExecutors??this.toolExecutors,T=$.localRuntime,O=T?.extensionContext?.logger??T?.logger,L=T?.extensionContext?.automation,C,N={getSession:(b)=>this.sessions.get(b),subAgentStarts:this.subAgentStarts,onAgentEvent:(b,$0,q0)=>this.eventBridge.dispatchAgentEvent(b,$0,q0),invokeBackendOptional:(b,...$0)=>this.invokeOptional(b,...$0)};C=await qK({input:j,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:_,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(b)=>{if(b.name==="plugin_log"){this.eventBridge.handlePluginLog(J,b.payload,O);return}this.eventBridge.handlePluginEvent(J,b,L)},onTeamEvent:(b)=>{this.eventBridge.handleTeamEvent(J,b),C.config.onTeamEvent?.(b)},createSpawnTool:()=>pY(N,C.config,J,R),createSubAgentLifecycleCallbacks:(b)=>lY(N,b,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(b)=>{await this.persistSessionMetadata(J,()=>b)}});let p=kZ(j.sessionMetadata??A?.manifest.metadata,C.gitState);if(!A)F.metadata=p;let k=await this.runtimeBuilder.build(C.runtimeBuilderInput),P=C.config,r=C.providerConfig;if(k.teamRuntime&&!P.teamName?.trim())P.teamName=k.teamRuntime.getTeamName();let c=async()=>{let b=this.sessions.get(J);if(!b||!L$(b.config.providerId))return!1;try{return await this.syncOAuthCredentials(b,{forceRefresh:!0}),!0}catch{return!1}};k.delegatedAgentConfigProvider?.updateConnectionDefaults({onAuthError:c});let g1=[...k.tools,...P.extraTools??[]],Z2=k.extensions??C.extensions,A8=j.initialCompactionState,g0,A0=z4(P),r0=A8??D,U8=A0&&r0?{...r0,conversation_id:r0.conversation_id?.trim()||J}:void 0,S0=A0?q4({compact:A0,getState:()=>g0?.compactionState,saveState:async(b)=>{let $0=g0;if(!$0)return;let q0={...b,conversation_id:$0.sessionId};try{if(!(await this.persistActiveSessionCompactionState($0,q0)).updated)P.logger?.debug?.("Skipped stale session compaction state",{sessionId:$0.sessionId,sourceMessageCount:q0.source_message_count})}catch(h0){P.logger?.error?.("Failed to persist session compaction state",{sessionId:$0.sessionId,error:h0}),W2(P.telemetry,{component:"core",operation:"session.persist_compaction_state",severity:"warn",handled:!0,error:h0,context:{sessionId:$0.sessionId,providerId:P.providerId,modelId:P.modelId}})}}}):void 0,G1={sessionId:J,providerId:r.providerId,modelId:r.modelId,apiKey:r.apiKey,baseUrl:r.baseUrl,headers:r.headers,onAuthError:c,knownModels:r.knownModels,providerConfig:r,thinking:P.thinking,reasoningEffort:P.reasoningEffort??r.reasoningEffort,thinkingBudgetTokens:P.thinkingBudgetTokens,maxTokensPerTurn:P.maxTokensPerTurn,temperature:P.temperature,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:S0,tools:g1,hooks:C.hooks,extensions:Z2,hookErrorMode:P.hookErrorMode,initialMessages:C.effectiveInput.initialMessages,userFileContentLoader:bf,toolPolicies:C.toolPolicies,requestToolApproval:C.requestToolApproval?async(b)=>{let $0=C.requestToolApproval,q0=this.sessions.get(J);if(q0)await this.markTurnPending(q0);try{if(!$0)return{approved:!1,reason:"Tool approval callback is not configured."};return await $0(b)}finally{let h0=this.sessions.get(J);if(h0?.status==="pending")await this.markTurnRunning(h0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:k.completionPolicy,consumePendingUserMessage:()=>{let b=this.pendingPromptsController.consumeSteer(J);return b?HW(b.prompt,b.mode??P.mode):void 0},logger:k.logger??P.logger,extensionContext:P.extensionContext,onEvent:(b)=>this.eventBridge.dispatchAgentEvent(J,P,b)};G1.hooks={...G1.hooks,onEvent:async(b)=>{if(await C.hooks?.onEvent?.(b),b.type!=="assistant-message")return;let $0=this.sessions.get(J);if(!$0)return;let q0=$0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,q0,P.systemPrompt)}catch(h0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:h0}),W2(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:h0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let y0=this.createAgentInstance(G1);if(G1.onEvent)y0.subscribeEvents(G1.onEvent);k.registerLeadAgent?.(y0);let O0=s1({agentId:y0.getAgentId(),conversationId:y0.getConversationId(),teamId:k.teamRuntime?.getTeamId(),teamName:k.teamRuntime?.getTeamName(),teamRole:k.teamRuntime?"lead":void 0});if(RK(P,J,Q.length>0,K,O0),O0)_$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...O0});if(k.teamRuntime)j9(P.telemetry,{ulid:J,teamId:k.teamRuntime.getTeamId(),teamName:k.teamRuntime.getTeamName(),leadAgentId:y0.getAgentId(),restoredFromPersistence:k.teamRestoredFromPersistence===!0});let v={sessionId:J,config:P,sessionMetadata:p,...A?{artifacts:A}:{},source:W,startedAt:A?.manifest.started_at??Z,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Z,pendingPrompt:F.prompt,runtime:k,agent:y0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:X,compactionState:U8,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:C.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(g0=v,v.compactionState&&!this.isCompactionStateForSession(v.sessionId,v.compactionState,v))v.config.logger?.log?.("Ignoring session compaction state for a different conversation",{severity:"warn",sessionId:v.sessionId,conversationId:v.compactionState.conversation_id}),v.compactionState=void 0;if(this.sessions.set(J,v),A)await this.refreshActiveSessionGitMetadata(v,C.gitState);if(this.emitStatus(J,"running"),X.length>0&&!A){if(await this.ensureSessionPersisted(v),await this.invoke("persistSessionMessages",v.sessionId,X,v.config.systemPrompt),v.compactionState){if(!(await this.persistActiveSessionCompactionState(v,v.compactionState)).updated)v.compactionState=void 0}if(!j.prompt?.trim())await this.updateStatus(v,"completed",0)}let i0;try{if(j.prompt?.trim())if(i0=await this.executeTurn(v,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!v.interactive)await this.finalizeSingleRun(v,i0.finishReason);else await this.completeInteractiveTurn(v,i0.finishReason)}catch(b){if(v.interactive&&v.aborting)i0=await this.completeAbortedInteractiveTurn(v);else{W2(v.config.telemetry,{component:"core",operation:"session.start",error:b,severity:"error",handled:!1,context:{sessionId:v.sessionId,providerId:v.config.providerId,modelId:v.config.modelId}});try{await this.failSession(v)}catch($0){v.config.logger?.error?.("Session failure cleanup threw",{sessionId:v.sessionId,error:$0})}throw b}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:H,result:i0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(W)=>this.getSession(W),readMessages:(W)=>this.readSessionMessages(W),buildStartInput:(W,Z)=>{let Q=W.restoredCheckpointMetadata?{...Z.sessionMetadata??{},checkpoint:W.restoredCheckpointMetadata}:Z.sessionMetadata;return{...Z,...Q?{sessionMetadata:Q}:{},initialMessages:W.initialMessages}},startSession:(W)=>this.startSession(W),getStartedSessionId:(W)=>W.sessionId,readRestoredSession:(W)=>this.getSession(W)})}async runTurn($){let W=this.getSessionOrThrow($.sessionId),Z=W.agent.canStartRun(),Q=$.delivery??(W.interactive&&!Z?"queue":void 0);if(W.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(W,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!W.interactive)await this.finalizeSingleRun(W,J.finishReason);else await this.completeInteractiveTurn(W,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(W.interactive&&W.aborting)return await this.completeAbortedInteractiveTurn(W);throw W2(W.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:W.sessionId,providerId:W.config.providerId,modelId:W.config.modelId}}),await this.failSession(W),J}}async getAccumulatedUsage($){let W=jj(this.usageBySession.get($)),Z=jj(this.aggregateUsageBySession.get($));return W||Z?{usage:W,aggregateUsage:Z}:void 0}async abort($,W){let Z=this.sessions.get($);if(!Z)return;Z.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Z.aborting=!0,this.pendingPromptsController.clearAborted(Z),Z.agent.abort(W)}async stopSession($){let W=this.sessions.get($);if(!W)return;if(W.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),W.interactive&&!G0(W.status)){await this.releaseSessionRuntime(W,"session_stop");return}if(W.interactive&&W.agent.canStartRun()){await this.shutdownSession(W,{status:this.resolveInteractiveStopStatus(W),exitCode:this.resolveInteractiveStopExitCode(W),shutdownReason:"session_stop",endReason:"stopped"});return}W.aborting=!0,W.agent.abort(Error("session_stop")),await this.shutdownSession(W,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let W=[...this.sessions.values()];if(W.length===0)return;await Promise.allSettled(W.map((Z)=>Z.interactive&&!G0(Z.status)?this.releaseSessionRuntime(Z,$):Z.interactive&&Z.agent.canStartRun()?this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let W=this.sessions.get($);if(W)return uY(W);let Z=$.trim();if(!Z)return;let Q=await this.getRow(Z);if(Q)return o4(Q);let J=await this.readManifest(Z);return J?YQ(J):void 0}async listSessions($=200){let Z=(await this.listRows($)).map(o4),Q=new Set(Z.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(Q.has(J.sessionId))continue;Z.unshift(uY(J))}return Z.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let W=await this.invoke("deleteSession",$);if(W.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return W.deleted}async updateSession($,W){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:W.prompt,metadata:W.metadata,title:W.title}))?.updated===!0}}async updateSessionCompactionState($,W){let Z=$.trim();if(!Z)return{updated:!1};let Q=this.sessions.get(Z),J=Q?void 0:await this.getSession(Z);if(!(Q??J))return{updated:!1};if(Q){let Y=await this.readSessionMessages(Z),V=W.source_message_count>0&&Y.length>=W.source_message_count,B=V?Y:void 0;if(V){if(!await this.canPersistCompactionState(Z,W,Q,void 0,Y))return{updated:!1};Q.agent.restore(Y)}return await this.persistActiveSessionCompactionState(Q,W,B)}if(!await this.canPersistCompactionState(Z,W,void 0,J))return{updated:!1};let X=await this.invokeOptionalValue("readSessionCompactionState",Z);if(hf(W,X))return{updated:!1};return await this.invoke("persistSessionCompactionState",Z,W),{updated:!0}}async readSessionCompactionState($){let W=$.trim();if(!W)return;let Z=this.sessions.get(W);if(Z)for(;;){let Q=Z.compactionStateWriteQueue;if(!Q)return Z.compactionState;await Q.catch(()=>{return})}return await this.invokeOptionalValue("readSessionCompactionState",W)}isCompactionStateForSession($,W,Z,Q){let J=W.conversation_id?.trim();if(!J)return!0;if(J===$)return!0;let j=Z?.agent.getConversationId()?.trim()||Q?.conversationId?.trim();return j?J===j:!1}async canPersistCompactionState($,W,Z,Q,J){if(!W.conversation_id?.trim())return!1;if(!this.isCompactionStateForSession($,W,Z,Q))return!1;let j=J??Z?.agent.getMessages()??await this.readSessionMessages($);return X2(W,j)!==void 0}async persistActiveSessionCompactionState($,W,Z){if(!await this.canPersistCompactionState($.sessionId,W,$,void 0,Z))return{updated:!1};return await this.enqueueCompactionStateWrite($,async()=>{if(hf(W,$.compactionState))return{updated:!1};return await this.invoke("persistSessionCompactionState",$.sessionId,W),$.compactionState=W,{updated:!0}})}async enqueueCompactionStateWrite($,W){let Q=($.compactionStateWriteQueue??Promise.resolve()).catch(()=>{return}).then(W),J=Q.then(()=>{return},()=>{return});$.compactionStateWriteQueue=J;try{return await Q}finally{if($.compactionStateWriteQueue===J)$.compactionStateWriteQueue=void 0}}async readSessionMessages($){let W=$.trim();if(!W)return[];let Z=await this.getRow(W);if(Z?.messagesPath)return l$(Z.messagesPath);let Q=await this.readManifest(W);return l$(Q?.messages_path)}async dispatchHookEvent($){await XA($,{queueSpawnRequest:(W)=>this.invokeOptional("queueSpawnRequest",W),upsertSubagentSessionFromHook:(W)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",W),appendSubagentHookAudit:(W,Z)=>this.invokeOptional("appendSubagentHookAudit",W,Z),applySubagentStatus:(W,Z)=>this.invokeOptional("applySubagentStatus",W,Z)})}subscribe($,W){return this.events.subscribe($,W)}async updateSessionModel($,W){await this.updateSessionConnection($,{modelId:W})}async updateSessionConnection($,W){let Z=T2(W),Q=this.getSessionOrThrow($);if(Z.providerId!==void 0)Q.config.providerId=Z.providerId;if(Z.modelId!==void 0)Q.config.modelId=Z.modelId;if(Z.apiKey!==void 0)Q.config.apiKey=Z.apiKey;if(Z.baseUrl!==void 0)Q.config.baseUrl=Z.baseUrl;if(Z.headers!==void 0)Q.config.headers=Z.headers;if(Z.providerConfig!==void 0)Q.config.providerConfig=Z.providerConfig;if(Object.hasOwn(Z,"reasoningEffort"))Q.config.reasoningEffort=Z.reasoningEffort??void 0;if(Object.hasOwn(Z,"thinkingBudgetTokens"))Q.config.thinkingBudgetTokens=Z.thinkingBudgetTokens??void 0;if(Object.hasOwn(Z,"thinking")){if(Q.config.thinking=Z.thinking??void 0,Z.thinking===!1||Z.thinking===null)Q.config.reasoningEffort=void 0,Q.config.thinkingBudgetTokens=void 0}let J={...Z.providerId!==void 0?{providerId:Z.providerId}:{},...Z.modelId!==void 0?{modelId:Z.modelId}:{},...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{},...Z.providerConfig!==void 0?{providerConfig:Z.providerConfig}:{},...Object.hasOwn(Z,"reasoningEffort")?{reasoningEffort:Z.reasoningEffort??void 0}:{},...Object.hasOwn(Z,"thinking")?{thinking:Z.thinking??void 0}:{},...Object.hasOwn(Z,"thinkingBudgetTokens")?{thinkingBudgetTokens:Z.thinkingBudgetTokens??void 0}:{}};if(Z.thinking===!1||Z.thinking===null)J.reasoningEffort=void 0,J.thinkingBudgetTokens=void 0;let j={...Z.apiKey!==void 0?{apiKey:Z.apiKey}:{},...Z.baseUrl!==void 0?{baseUrl:Z.baseUrl}:{},...Z.headers!==void 0?{headers:Z.headers}:{}};if(Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults(J),Q.agent.updateConnection(Z),Q.runtime.teamRuntime?.updateTeammateConnections(j),Z.providerId||Z.modelId)await this.mutateSessionManifest(Q,(X)=>{if(Z.providerId)X.provider=Z.providerId;if(Z.modelId)X.model=Z.modelId})}async mutateSessionManifest($,W){let Z=$.artifacts;if(!Z)return;let Q=$.sessionId,j=(this.manifestMutationQueues.get(Q)??Promise.resolve()).then(async()=>{let Y=await this.invokeOptionalValue("readSessionManifest",Q)??Z.manifest;return W(Y),Z.manifest=Y,await this.invoke("writeSessionManifest",Z.manifestPath,Y),Y}),X=j.then(()=>{return},()=>{return});this.manifestMutationQueues.set(Q,X);try{return await j}finally{if(this.manifestMutationQueues.get(Q)===X)this.manifestMutationQueues.delete(Q)}}handlePluginEvent($,W,Z){return this.eventBridge.handlePluginEvent($,W,Z)}async executeTurn($,W){let Z=await this.prepareTurnInput($,W),Q=Z.prompt.trim(),J=Z?.userImages?.length,j=Z?.userFiles?.length;if(!Q&&!J&&!j)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.refreshActiveSessionGitMetadata($),await this.syncOAuthCredentials($),await this.markTurnRunning($);try{let X=await this.executeAgentTurn($,Q,Z.userImages,Z.userFiles);while(kj($,X.finishReason)){let Y=await Ij($);if(Y.length===0)break;let V=xj($,Y);X=await this.executeAgentTurn($,V)}return X}finally{await this.refreshActiveSessionGitMetadata($)}}async completeInteractiveTurn($,W){if(BW($))return;$.lastInteractiveTurnFinishReason=W,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let W=$.lastInteractiveTurnFinishReason;if(!W)return"cancelled";switch(W){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return W}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let W=new Date,Z=$.agent.getMessages(),Q=z0();return $.persistedMessages=Z,$.started=$.started||Z.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:Z,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:W,endedAt:W,durationMs:0}}async executeAgentTurn($,W,Z,Q){let J=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),X=this.usageBySession.get($.sessionId)??z0(),Y=this.aggregateUsageBySession.get($.sessionId)??X;$.turnUsageBaseline=X,$.turnAggregateUsageBaseline=Y,$.turnPrimaryUsage=z0(),$.turnUsageByAgent=new Map,tW($.config.telemetry,$.sessionId,$.config.mode),_8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(W,Z,Q):()=>$.agent.run(W,Z,Q),B=await this.runWithAuthRetry($,V,j);$.started=!0;let H=$Z(B.messages,B,j);$.persistedMessages=H;let G=t4($.turnUsageByAgent?.values()??[]),K=f0(X,B.usage),F=f0(f0(z0(),B.usage),G),A=f0(Y,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,B),B}catch(V){throw W2($.config.telemetry,{component:"core",operation:"session.turn",error:V,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),V}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,W){if($.submitAndExitObserved)return;if(!W.toolCalls.some((Q)=>Q.name===T0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,W4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,W){let Z=t1($.config),Q=gv(W.prompt).trim();if(!Q)return{prompt:"",userImages:W.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles)};let J=await y8(Q,Z);NK($.config.telemetry,J);let j=HW(J.prompt,W.mode??$.config.mode),X=this.resolveAbsoluteFilePaths($.config.cwd,W.userFiles),Y=this.resolveAbsoluteFilePaths(Z,J.matchedFiles),V=Array.from(new Set([...X,...Y]));return{prompt:j,userImages:W.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let W=t1($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:W,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async refreshActiveSessionGitMetadata($,W){try{let Z=W??await fJ(t1($.config));if(!Z||!$.artifacts)return;if(_J($.artifacts.manifest.metadata,Z))return;await this.persistSessionMetadata($.sessionId,(Q)=>kZ({...Q??{},...$.sessionMetadata??{}},Z))}catch(Z){$.config.logger?.debug?.("Failed to refresh session git metadata",{sessionId:$.sessionId,error:Z})}}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,W){let Z=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??Z?.artifacts?.manifest,J=W(Q?.metadata);if(!Z?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Z.sessionMetadata=J,Z.artifacts.manifest.metadata=J}async finalizeSingleRun($,W){if(BW($))return;let Z=W==="aborted"||$.aborting,Q=W==="error";await this.shutdownSession($,{status:Z?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:W})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,W){if(W.status==="completed"&&!$.submitAndExitObserved)W4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});qQ($);let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),W2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:W.status,shutdownReason:W.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){await this.refreshActiveSessionGitMetadata($);try{await this.updateStatus($,W.status,W.exitCode)}catch(J){Q("update_status",J)}try{await $.agent.shutdown(W.shutdownReason)}catch(J){Q("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(W.shutdownReason))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:W.endReason,ts:Date.now()}}),Z.length>0&&W.status==="failed")throw Z[0]}async releaseSessionRuntime($,W){let Z=[],Q=(J,j)=>{Z.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:j,severity:"warn"}),W2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:W,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(W)}catch(J){Q("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(W))}catch(J){Q("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){Q("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Z.length>0)throw Z[0]}async updateStatus($,W,Z){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,W,Z);if(!Q.updated)return;let J=await this.mutateSessionManifest($,(j)=>{if(j.status=W,G0(W))delete j.ended_at,j.exit_code=null;else j.ended_at=Q.endedAt??X0(),j.exit_code=typeof Z==="number"?Z:null});if(!J)return;$.status=W,$.updatedAt=Q.endedAt??X0(),$.endedAt=G0(W)?null:J.ended_at,$.exitCode=J.exit_code,this.emitStatus($.sessionId,W)}async runWithAuthRetry($,W,Z){try{return await W()}catch(Q){if(!L$($.config.providerId)||!xv(Q))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Z),W()}}async syncOAuthCredentials($,W){let Z=null;try{Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:W?.forceRefresh})}catch(Q){if(Q instanceof w7)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!Z?.apiKey||$.config.apiKey===Z.apiKey)return;$.config.apiKey=Z.apiKey,$.agent.updateConnection({apiKey:Z.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Z.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Z.apiKey})}getSessionOrThrow($){let W=this.sessions.get($);if(!W){let Z=new Q$($);throw W2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Z,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Z}return W}resolveAbsoluteFilePaths($,W){if(!W||W.length===0)return[];let Z=W.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>kv(Q)?Q:iY($,Q));return Array.from(new Set(Z))}getSessionAgentTelemetryIdentity($){return s1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let W=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Z=f0($.initialUsage,W);return this.withPersistedAggregateUsageFloor(Z,$.manifest)}async summarizePersistedTeammateUsage($,W,Z){let Q=iY(W),J=`${Z}.messages.json`,j;try{j=yv($)}catch{return z0()}let X=z0();for(let Y of j){if(!Y.endsWith(".messages.json"))continue;if(Y===J)continue;let V=iY($,Y);if(V===Q)continue;let B=await l$(V);if(B.length===0)continue;X=f0(X,l8(B))}return X}withPersistedAggregateUsageFloor($,W){let Z=vv(W.metadata?.aggregateUsage);if(Z)return cv($,Z);let Q=W.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,W){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:W}})}async emitSessionSnapshot($){let W=await this.getSession($);if(!W)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:P1({session:W,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),yf))}async getRow($){let W=$.trim();if(!W)return;return(await this.listRows(yf)).find((Q)=>Q.sessionId===W)}async readManifest($){let W=$.trim();if(!W)return;return await this.invokeOptionalValue("readSessionManifest",W)}invoke($,...W){return Cf(this.sessionService,$,...W)}invokeOptional($,...W){return Pf(this.sessionService,$,...W)}invokeOptionalValue($,...W){return Sf(this.sessionService,$,...W)}}function dv($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((W)=>({name:W.name,input:W.input,output:W.output,error:W.error,durationMs:W.durationMs}))}}function lv($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function cQ($={}){let W=new k1({sessionService:new h1(new b1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Z){let Q=(Z.cwd?.trim()||Z.workspaceRoot).trim(),J=await W.startSession({source:Z.source?.trim()||K0.CLI,interactive:!1,config:{providerId:uv(Z.provider),modelId:Z.model,apiKey:Z.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:lv(Z),maxIterations:Z.maxIterations,enableTools:Z.enableTools!==!1,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},toolPolicies:Z.toolPolicies??{"*":{autoApprove:Z.autoApproveTools!==!1}},localRuntime:{configExtensions:Z.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Z,Q){let J=await W.runTurn({sessionId:Z,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((j)=>j.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:dv(J)}},async abortSession(Z){return await W.abort(Z,Error("hub schedule abort")),{applied:!0}},async stopSession(Z){return await W.stopSession(Z),{applied:!0}}}}import{release as pv}from"node:os";import{createClineTelemetryServiceConfig as rv}from"@cline/shared";U0();fW();var iv=300000,nv=5000;function kf(){let $=rv({metadata:{extension_version:dW,cline_type:"hub",platform:"cline-hub-daemon",platform_version:process.version,os_type:process.platform,os_version:pv()}}),W=a$($),Z,Q=()=>{try{return Z??=new B1,Z.getProviderSettings("cline")?.auth}catch{return}},J,j=()=>{let Y=Q(),V=Y?.accountId?.trim();if(!Y||!V)return;let B=`${V}:${Y.organizationId??""}`;if(B===J)return;J=B,K1(W.telemetry,{id:V,provider:"cline",organizationId:Y.organizationId,organizationName:Y.organizationName,memberId:Y.memberId})};j();let X=setInterval(j,iv);return X.unref?.(),{telemetry:W.telemetry,dispose:async()=>{clearInterval(X);let Y;await Promise.race([(async()=>{await W.flush(),await W.dispose()})(),new Promise((V)=>{Y=setTimeout(V,nv),Y.unref?.()})]),clearTimeout(Y)}}}ov(process.env.CLINE_VCR);function tv($){let W=process.cwd(),Z,Q,J;for(let j=0;j<$.length;j+=1){let X=$[j],Y=$[j+1];if(X==="--cwd"&&Y){W=Y,j+=1;continue}if(X==="--host"&&Y){Z=Y,j+=1;continue}if(X==="--port"&&Y){let V=Number(Y);if(Number.isFinite(V))Q=V;j+=1;continue}if(X==="--pathname"&&Y)J=Y,j+=1}return{cwd:W,host:Z,port:Q,pathname:J}}async function ev(){let $=tv(process.argv.slice(2));process.chdir($.cwd);let W=j1({host:$.host,port:$.port,pathname:$.pathname}),Z=kf(),Q;try{Q=await V8({host:W.host,port:W.port,pathname:W.pathname,owner:sv()==="production"?X1():u0(),telemetry:Z.telemetry,runtimeHandlers:cQ({telemetry:Z.telemetry}),cronOptions:{workspaceRoot:$.cwd}})}catch(Y){throw await Z.dispose().catch(()=>{return}),Y}let J=async()=>{await Q.close(),await Z.dispose().catch(()=>{return}),process.exit(0)},j=!1,X=(Y,V)=>{if(j)return;j=!0;let B=V instanceof Error?V.stack||V.message:String(V);process.stderr.write(`[hub-daemon] ${Y}: ${B}
761
761
  `),Q.close().catch((H)=>{let G=H instanceof Error?H.stack||H.message:String(H);process.stderr.write(`[hub-daemon] shutdown after ${Y} failed: ${G}
762
- `)}).finally(()=>{Z.dispose().catch(()=>{return}).finally(()=>{process.exit(1)})})};process.on("SIGINT",()=>{J()}),process.on("SIGTERM",()=>{J()}),process.on("uncaughtException",(Y)=>{X("uncaughtException",Y)}),process.on("unhandledRejection",(Y)=>{if(Y instanceof dv){process.stderr.write(`[hub-daemon] ignored agent runtime abort rejection: ${Y.message}
763
- `);return}X("unhandledRejection",Y)}),await new Promise(()=>{})}iv().catch(($)=>{let W=$ instanceof Error?$.stack||$.message:String($);process.stderr.write(`[hub-daemon] fatal: ${W}
762
+ `)}).finally(()=>{Z.dispose().catch(()=>{return}).finally(()=>{process.exit(1)})})};process.on("SIGINT",()=>{J()}),process.on("SIGTERM",()=>{J()}),process.on("uncaughtException",(Y)=>{X("uncaughtException",Y)}),process.on("unhandledRejection",(Y)=>{if(Y instanceof av){process.stderr.write(`[hub-daemon] ignored agent runtime abort rejection: ${Y.message}
763
+ `);return}X("unhandledRejection",Y)}),await new Promise(()=>{})}ev().catch(($)=>{let W=$ instanceof Error?$.stack||$.message:String($);process.stderr.write(`[hub-daemon] fatal: ${W}
764
764
  `),process.exit(1)});