@cline/core 0.0.54-nightly.1782962319 → 0.0.55

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
- import{createRequire as NA}from"node:module";var MA=Object.defineProperty;var RA=($)=>$;function EA($,Z){this[$]=RA.bind(null,Z)}var i9=($,Z)=>{for(var Q in Z)MA($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:EA.bind(Z,Q)})};var F$=($,Z)=>()=>($&&(Z=$($=0)),Z);var fJ=NA(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as CA,captureAgentUnexpectedReasoningTokens as PA,SDK_ERROR_TELEMETRY_EVENT as SA}from"@cline/shared";function l($,Z,Q){$?.capture({event:Z,properties:Q})}function v4($){if(!$)return;return $.substring(0,bA)}function yA($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function hA($){return typeof $==="string"?$:$.message}function _J($,Z){return $.some((Q)=>Z.has(Q.trim().toLowerCase()))}function kA($){l($,I.CLIENT.EXTENSION_ACTIVATED)}function s9($,Z){let Q=[...Z.vcs_types],W={root_count:Z.root_count,vcs_types:Q,is_multi_root:Z.root_count>1,has_git:_J(Q,new Set(["git"])),has_mercurial:_J(Q,new Set(["mercurial","hg"]))};if(Z.init_duration_ms!==void 0)W.init_duration_ms=Z.init_duration_ms;if(Z.feature_flag_enabled!==void 0)W.feature_flag_enabled=Z.feature_flag_enabled;if(Z.is_remote_workspace!==void 0)W.is_remote_workspace=Z.is_remote_workspace;l($,I.WORKSPACE.INITIALIZED,W)}function o9($,Z,Q){l($,I.WORKSPACE.INIT_ERROR,{error_type:yA(Z),error_message:v4(hA(Z)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function IA($,Z){l($,I.WORKSPACE.PATH_RESOLVED,{...Z})}function w1($,Z){l($,I.USER.AUTH_STARTED,{provider:Z})}function C1($,Z){l($,I.USER.AUTH_SUCCEEDED,{provider:Z})}function P1($,Z,Q){l($,I.USER.AUTH_FAILED,{provider:Z,errorMessage:v4(Q)})}function A$($,Z,Q){l($,I.USER.AUTH_LOGGED_OUT,{provider:Z,reason:Q})}function xA($,Z){l($,I.USER.PROVIDER_CONFIGURED,{provider:Z})}function zJ($,Z){$?.captureRequired(I.USER.TELEMETRY_OPT_OUT,Z)}function S1($,Z){let Q=Z.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:Z.id,account_email:Z.email,provider:Z.provider,organization_id:Z.organizationId,organization_name:Z.organizationName,member_id:Z.memberId})}function t9($,Z){l($,I.TASK.CREATED,Z)}function e9($,Z){l($,I.TASK.RESTARTED,Z)}function c4($,Z){l($,I.TASK.COMPLETED,Z)}function Z8($,Z){l($,I.TASK.CONVERSATION_TURN,{...Z,timestamp:new Date().toISOString()})}function $Z($,Z){l($,I.TASK.TOKEN_USAGE,Z)}function ZZ($,Z,Q){l($,I.TASK.MODE_SWITCH,{ulid:Z,mode:Q})}function Q8($,Z){l($,I.TASK.TOOL_USED,Z)}function QZ($,Z){l($,I.TASK.SKILL_USED,Z)}function WZ($,Z){l($,I.TASK.DIFF_EDIT_FAILED,Z)}function u4($,Z){l($,I.TASK.PROVIDER_API_ERROR,{...Z,errorMessage:v4(Z.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function TJ($,Z){l($,I.SDK.TOOL_TIMEOUT,gA(Z))}function gA($){let Z={};for(let[Q,W]of Object.entries($))if(W!==void 0)Z[Q]=W;return Z}function JZ($,Z,Q){l($,I.TASK.MENTION_USED,{mentionType:Z,contentLength:Q,timestamp:new Date().toISOString()})}function XZ($,Z,Q,W){l($,I.TASK.MENTION_FAILED,{mentionType:Z,errorType:Q,errorMessage:v4(W),timestamp:new Date().toISOString()})}function YZ($,Z,Q,W,J){l($,I.TASK.MENTION_SEARCH_RESULTS,{queryLength:Z.length,resultCount:Q,searchType:W,isEmpty:J,timestamp:new Date().toISOString()})}function f$($,Z){l($,I.TASK.AGENT_CREATED,{...Z,timestamp:new Date().toISOString()})}function jZ($,Z){l($,I.TASK.AGENT_TEAM_CREATED,{...Z,timestamp:new Date().toISOString()})}function d4($,Z){l($,Z.event==="ended"?I.TASK.SUBAGENT_COMPLETED:I.TASK.SUBAGENT_STARTED,{...Z,timestamp:new Date().toISOString()})}function VZ($,Z,Q,W){l($,I.HOOKS.DISCOVERY_COMPLETED,{hookName:Z,globalCount:Q,workspaceCount:W,totalCount:Q+W,timestamp:new Date().toISOString()})}function HZ($,Z){l($,I.TASK.COMPACTION_EXECUTED,{...Z,timestamp:new Date().toISOString()})}function BZ($,Z){l($,I.TASK.COMPACTION_SKIPPED,{...Z,timestamp:new Date().toISOString()})}var bA=500,I;var G0=F$(()=>{I={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:CA},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",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",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"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:SA,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as wU,readFileSync as CU,statSync as PU,writeFileSync as SU}from"node:fs";import{dirname as bU}from"node:path";import{resolveGlobalSettingsPath as DX}from"@cline/shared/storage";import{z as H2}from"zod";function j6(){return H6.parse({})}function yU(){V6=void 0}function hU($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function kU($){let Z;try{Z=CU($,"utf8")}catch{return j6()}try{let Q=H6.safeParse(JSON.parse(Z));return Q.success?Q.data:j6()}catch{return j6()}}function IU(){let $=DX(),Z=PU($,{throwIfNoEntry:!1}),Q=Z?.mtimeMs??0,W=Z?.size??0,J=V6;if(J&&J.path===$&&J.mtimeMs===Q&&J.size===W)return J;let X=hU(Z?kU($):j6());return V6={path:$,mtimeMs:Q,size:W,value:X},V6}function R0(){return IU().value}function h1($,Z={}){let Q=DX(),W=R0();wU(bU(Q),{recursive:!0});let J=H6.parse($);if(!W.telemetryOptOut&&J.telemetryOptOut)zJ(Z.telemetry);SU(Q,`${JSON.stringify(J,null,2)}
2
- `,"utf8"),yU()}function mZ(){return R0().telemetryOptOut}function xU($,Z={}){h1({...R0(),telemetryOptOut:$},Z)}function gU(){return R0().autoUpdateEnabled}function mU($,Z={}){h1({...R0(),autoUpdateEnabled:$},Z)}function G1($){return new Set($??R0().disabledTools??[])}function B6($){return new Set($??R0().disabledPlugins??[])}function vU($){return G1().has($)}function vZ($){let Z=R0(),Q=new Set(Z.disabledTools??[]),W=Q.has($);if(W)Q.delete($);else Q.add($);return h1({...Z,disabledTools:[...Q]}),!W}function LX($,Z){let Q=[...new Set($.map((X)=>X.trim()).filter(Boolean))];if(Q.length===0)return;let W=R0(),J=G1(W.disabledTools);for(let X of Q)if(Z)J.add(X);else J.delete(X);h1({...W,disabledTools:[...J]})}function _X($,Z){return LX([$],Z),Z}function cU($){return B6().has($)}function uU($,Z){let Q=$.trim();if(!Q)return;let W=R0(),J=B6(W.disabledPlugins);if(Z)J.add(Q);else J.delete(Q);h1({...W,disabledPlugins:[...J]})}function cZ($,Z){let Q=B6(Z);if(Q.size===0)return[...$];return $.filter((W)=>!Q.has(W))}function k1($,Z){let Q=G1(Z);if(Q.size===0)return[...$];return $.filter((W)=>!Q.has(W.name))}function uZ($,Z){if(!$||$.length===0)return $;let Q=G1(Z);if(Q.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(J,X)=>W.setup?.({...J,registerTool:(Y)=>{if(!Q.has(Y.name))J.registerTool(Y)}},X)}})}var UX,H6,V6;var r0=F$(()=>{G0();UX=H2.preprocess(($)=>Array.isArray($)?$.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter(Boolean):void 0,H2.array(H2.string()).optional()).transform(($)=>{if(!$)return;let Z=[...new Set($)].sort((Q,W)=>Q.localeCompare(W));return Z.length>0?Z:void 0}),H6=H2.object({telemetryOptOut:H2.boolean().default(!1).catch(!1),autoUpdateEnabled:H2.boolean().default(!0).catch(!0),disabledTools:UX.optional(),disabledPlugins:UX.optional()}).strip().transform(($)=>{let Z={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)Z.disabledTools=$.disabledTools;if($.disabledPlugins?.length)Z.disabledPlugins=$.disabledPlugins;return Z})});var Xj={};i9(Xj,{normalizeUserMessage:()=>fz,buildInitialUserContent:()=>Az});async function Az($,Z,Q,W){let J=Uz(Z),X=await Lz(Q,W);if(J.length===0&&!X)return $;let Y=[{type:"text",text:$},...J];if(X)Y.push(...X);return Y}function fz($){if($==null)return"";if(typeof $==="string")return $;let Z=$.content;if(typeof Z==="string")return Z;if(!Array.isArray(Z))return"";let Q=[];for(let W of Z)if(W&&typeof W==="object"&&W.type==="text"){let J=W.text;if(typeof J==="string")Q.push(J)}return Q.join(`
3
- `)}function Uz($){if(!$||$.length===0)return[];let Z=[];for(let Q of $){let W=Dz(Q);if(W)Z.push(W)}return Z}function Dz($){let Z=$.trim();if(!Z)return;let Q=Z.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let W=Q[1],J=Q[2];if(!W||!J)return;return{type:"image",mediaType:W,data:J}}return{type:"image",mediaType:"image/png",data:Z}}async function Lz($,Z){if(!$||$.length===0)return;let Q=Z??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(J)=>{let X=J.replace(/\\/g,"/");try{let Y=await Q(J);return{type:"file",path:X,content:Y}}catch(Y){let j=Y instanceof Error?Y.message:String(Y);return{type:"file",path:X,content:`Error fetching content: ${j}`}}}));if(W.length===0)return;return W}var YV={};i9(YV,{updateMcpSettingsFileSync:()=>f1,updateMcpSettingsFile:()=>X5,updateMcpServerOAuthStateAsync:()=>eQ,updateMcpServerOAuthState:()=>h8,setMcpServerDisabled:()=>b8,resolveMcpServerRegistrations:()=>$1,resolveDefaultMcpSettingsPath:()=>Z0,registerMcpServersFromSettingsFile:()=>k8,normalizeMcpServerOAuthState:()=>S2,loadMcpSettingsFile:()=>S8,listMcpServerOAuthStatuses:()=>$7,hasMcpSettingsFile:()=>w$,getMcpServerOAuthState:()=>y8,McpSettingsUpdateSkippedError:()=>W5,McpSettingsMutatorPurityError:()=>C2,McpSettingsLockTimeoutError:()=>P2});import{existsSync as pj,mkdirSync as iQ,readFileSync as rj,renameSync as sQ,rmdirSync as VT,rmSync as nQ,statSync as HT,unlinkSync as ij,writeFileSync as nj}from"node:fs";import{randomUUID as BT}from"node:crypto";import{dirname as aj,join as lj}from"node:path";import{setTimeout as GT}from"node:timers/promises";import{resolveMcpSettingsPath as KT}from"@cline/shared/storage";import{z as w}from"zod";function aQ($){if(!$)return;if($==="http")return"streamableHttp";return $}function Z0(){return KT()}function qT($,Z){iQ(aj($),{recursive:!0});let Q=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{nj(Q,Z,{encoding:"utf8",flag:"wx"}),sQ(Q,$)}catch(W){try{ij(Q)}catch{}throw W}}function RT($){Atomics.wait(MT,0,0,$)}function ET($){return`${$}.lock`}function ej(){return`${process.pid}.${Date.now()}.${BT()}`}function $V($,Z){iQ(aj($),{recursive:!0});let Q=`${$}.tmp.${Z}`;nQ(Q,{recursive:!0,force:!0}),iQ(Q,{recursive:!0}),nj(lj(Q,`owner.${Z}`),Z,{encoding:"utf8",flag:"wx"});try{return sQ(Q,$),{lockDir:$,ownerFile:lj($,`owner.${Z}`)}}catch(W){if(nQ(Q,{recursive:!0,force:!0}),pj($))return;throw W}}function ZV($,Z){let Q;try{Q=Date.now()-HT($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Q<tQ)return;Z.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Q}ms); reclaiming.`,{severity:"warn"});let W=`${$}.stale.${ej()}`;try{sQ($,W)}catch(J){if(J.code==="ENOENT")return;throw J}nQ(W,{recursive:!0,force:!0})}function NT($){try{ij($.ownerFile)}catch(Z){if(Z.code!=="ENOENT")throw Z}try{VT($.lockDir)}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTEMPTY"&&Q!=="EEXIST")throw Z}}function QV($){let Z=ET($);if(J5.has(Z))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:Z,token:ej()}}function wT($,Z){let{lockDir:Q,token:W}=QV($),J=Z.timeoutMs??tQ,X=Date.now();while(!0){let Y=$V(Q,W);if(Y)return J5.add(Q),Y;if(Date.now()-X>J)throw new P2(`Timed out waiting for MCP settings lock at ${Q} after ${J}ms.`);ZV(Q,Z),RT(tj)}}async function CT($,Z){let{lockDir:Q,token:W}=QV($),J=Z.timeoutMs??tQ,X=Date.now();while(!0){let Y=$V(Q,W);if(Y)return J5.add(Q),Y;if(Date.now()-X>J)throw new P2(`Timed out waiting for MCP settings lock at ${Q} after ${J}ms.`);ZV(Q,Z),await GT(tj)}}function WV($,Z,Q){try{let W=PT(Z),J=ST(W,Q);return qT(Z,`${JSON.stringify(W,null,2)}
4
- `),J}finally{J5.delete($.lockDir),NT($)}}function f1($,Z,Q={}){let W=wT($,Q);return WV(W,$,Z)}async function X5($,Z,Q={}){let W=await CT($,Q);return WV(W,$,Z)}function PT($){let Z=yT($);if(!Z.mcpServers||typeof Z.mcpServers!=="object"||Array.isArray(Z.mcpServers))Z.mcpServers={};return Z}function ST($,Z){let Q=JSON.stringify($),W=JSON.parse(Q),J=Z(W),X=JSON.stringify(W),Y=Z($);if(JSON.stringify($)!==X)throw new C2("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(Y)!==JSON.stringify(J))throw new C2("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return Y}function bT($){let Z=rj($,"utf8"),Q;try{Q=JSON.parse(Z)}catch(W){let J=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function yT($){try{return bT($)}catch(Z){if(Z.code==="ENOENT")return{};throw Z}}function JV($,Z){if(!Object.hasOwn($,Z))return;let Q=$[Z];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function hT($,Z,Q){Object.defineProperty($,Z,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function S8($={}){let Z=$.filePath??Z0(),Q=rj(Z,"utf8"),W;try{W=JSON.parse(Q)}catch(X){let Y=X instanceof Error?X.message:String(X);throw Error(`Failed to parse MCP settings JSON at "${Z}": ${Y}`)}let J=OT.safeParse(W);if(!J.success){let X=J.error.issues.map((Y)=>{let j=Y.path.join(".");return j?`${j}: ${Y.message}`:Y.message}).join("; ");throw Error(`Invalid MCP settings at "${Z}": ${X}`)}return J.data}function S2($){if(!$)return;let Z={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(Z).length>0?Z:void 0}function kT($){if($===void 0)return;let Z=oQ.safeParse($);if(!Z.success)return;return S2(Z.data)}function w$($={}){let Z=$.filePath??Z0();return pj(Z)}function $1($={}){let Z=S8($);return Object.entries(Z.mcpServers).map(([Q,W])=>({name:Q,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function b8($){let Z=$.filePath??Z0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");f1(Z,(W)=>{let J=W.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${Z}": mcpServers must be an object.`);let X={...J},Y=JV(X,Q);if(!Y)throw Error(`Unknown MCP server: ${Q}`);let j={...Y};if($.disabled)j.disabled=!0;else delete j.disabled;hT(X,Q,j),W.mcpServers=X})}function y8($,Z={}){let Q=S8(Z);if(!Object.hasOwn(Q.mcpServers,$))return;return S2(Q.mcpServers[$]?.oauth)}function XV($,Z){return(Q)=>{let W=Q.mcpServers,J=JV(W,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let X=kT(J.oauth)??{},Y=S2(Z(X));if(Y)J.oauth=Y;else delete J.oauth;return Y??{}}}function h8($,Z,Q={}){let W=Q.filePath??Z0();return f1(W,XV($,Z))}async function eQ($,Z,Q={}){let W=Q.filePath??Z0();return X5(W,XV($,Z))}function $7($={}){return $1($).map((Q)=>{let W=Q.transport.type!=="stdio",J=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:W,oauthConfigured:W&&typeof J==="string"&&J.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,W)=>Q.serverName.localeCompare(W.serverName))}async function k8($,Z={}){let Q=$1(Z);for(let W of Q)await $.registerServer(W);return Q}var P8,sj,oQ,FT,AT,fT,UT,DT,LT,oj,_T,zT,TT,OT,W5,P2,C2,tQ=1e4,tj=25,MT,J5;var Y5=F$(()=>{P8=w.record(w.string(),w.string()),sj=w.record(w.string(),w.unknown()),oQ=w.object({clientInformation:w.record(w.string(),w.unknown()).optional(),tokens:w.record(w.string(),w.unknown()).optional(),codeVerifier:w.string().optional(),discoveryState:w.record(w.string(),w.unknown()).optional(),redirectUrl:w.string().url().optional(),lastError:w.string().optional(),lastAuthenticatedAt:w.number().int().positive().optional()}).strip(),FT=w.object({type:w.literal("stdio"),command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:P8.optional()}),AT=w.object({type:w.literal("sse"),url:w.string().url(),headers:P8.optional()}),fT=w.object({type:w.literal("streamableHttp"),url:w.string().url(),headers:P8.optional()}),UT=w.discriminatedUnion("type",[FT,AT,fT]),DT=w.object({transport:UT,disabled:w.boolean().optional(),metadata:sj.optional(),oauth:oQ.optional()}),LT=w.enum(["stdio","sse","http","streamableHttp"]).optional(),oj=w.object({type:w.enum(["stdio","sse","streamableHttp"]).optional(),transportType:LT,disabled:w.boolean().optional(),metadata:sj.optional(),oauth:oQ.optional()});_T=oj.extend({command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:P8.optional()}).superRefine(($,Z)=>{let Q=$.type??aQ($.transportType);if(Q&&Q!=="stdio")Z.addIssue({code:w.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})),zT=oj.extend({url:w.string().url(),headers:P8.optional()}).superRefine(($,Z)=>{let Q=$.type??aQ($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")Z.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??aQ($.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}}),TT=w.union([DT,_T,zT]),OT=w.object({mcpServers:w.record(w.string(),TT)}).passthrough();W5=class W5 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};P2=class P2 extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};C2=class C2 extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};MT=new Int32Array(new SharedArrayBuffer(4)),J5=new Set});import{existsSync as UE,mkdirSync as DE,readFileSync as LE,writeFileSync as _E}from"node:fs";import{resolve as zE}from"node:path";import{resolveSessionDataDir as TE}from"@cline/shared/storage";import{nanoid as OE}from"nanoid";import*as qE from"node-machine-id";function m0($){let Z=$?.trim();if(Z)return Z;let Q=EE();if(Q)return Q;return NE()}function RE(){let $=qE;return $.machineIdSync??$.default?.machineIdSync}function EE(){try{let $=RE();if(!$)return;return $().trim()||void 0}catch{return}}function NE(){let $=TE(),Z=zE($,ME);try{if(UE(Z)){let W=LE(Z,"utf8").trim();if(W.length>0)return W}}catch{}let Q=`cl-${OE()}`;try{DE($,{recursive:!0}),_E(Z,Q,"utf8")}catch{}return Q}var ME="machine-id";var g2=()=>{};class C4{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($,Z){if(!this.isEnabled())return;this.emitLog($,Z,!1)}emitRequired($,Z){this.emitLog($,Z,!0)}recordCounter($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.counters.get($);if(!X)X=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,X);X.add(Z,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.histograms.get($);if(!X)X=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,X);X.record(Z,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.buildAttributes(Q),Y=JSON.stringify(X),j=this.gaugeValues.get($);if(Z===null){if(j){if(j.delete(Y),j.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=j;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let H=this.meter.createObservableGauge($,W?{description:W}:void 0);H.addCallback((B)=>{for(let G of this.snapshotGaugeSeries($))B.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,H)}V.set(Y,{value:Z,attributes:X})}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($,Z,Q){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(Z,Q));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,Z=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...Z?{_required:!0}:{}}}snapshotGaugeSeries($){let Z=this.gaugeValues.get($);if(!Z)return[];return Array.from(Z.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,Z="",Q=new WeakSet,W=0){if(!$)return{};let J={},X=100,Y=10;for(let[j,V]of Object.entries($)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let H=Z?`${Z}.${j}`:j;if(V===null||V===void 0){J[H]=String(V);continue}if(Array.isArray(V)){let B=V.length>X?V.slice(0,X):V;try{J[H]=JSON.stringify(B)}catch{J[H]="[UnserializableArray]"}if(V.length>X)J[`${H}_truncated`]=!0,J[`${H}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[H]=V.toISOString();continue}if(V instanceof Error){J[H]=V.message;continue}if(Q.has(V)){J[H]="[Circular]";continue}if(W>=Y){J[H]="[MaxDepthExceeded]";continue}Q.add(V),Object.assign(J,this.flattenProperties(V,H,Q,W+1));continue}if($S(V)){J[H]=V;continue}try{J[H]=JSON.stringify(V)}catch{J[H]=String(V)}}return J}}function $S($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class _9{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,Z){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:Z})}emitRequired($,Z){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:Z})}recordCounter($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:Z,attributes:Q,description:W,required:J===!0})}recordHistogram($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:Z,attributes:Q,description:W,required:J===!0})}recordGauge($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:Z,attributes:Q,description:W,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class P4{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new _9({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 Z=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,Z)}captureRequired($,Z){let Q=this.buildAttributes(Z);for(let W of this.adapters)W.emitRequired($,Q)}recordCounter($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordCounter($,Z,X,W,J)}recordHistogram($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordHistogram($,Z,X,W,J)}recordGauge($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordGauge($,Z,X,W,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 V3=()=>{};import{metrics as ZS,trace as QS}from"@opentelemetry/api";import{logs as WS}from"@opentelemetry/api-logs";import{OTLPLogExporter as JS}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as XS}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as YS}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as jS}from"@opentelemetry/resources";import{BatchLogRecordProcessor as VS,ConsoleLogRecordExporter as HS,LoggerProvider as BS}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as GS,MeterProvider as KS,PeriodicExportingMetricReader as BK}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as FS,ConsoleSpanExporter as AS,SimpleSpanProcessor as fS}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as US}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as DS,ATTR_SERVICE_VERSION as LS}from"@opentelemetry/semantic-conventions";class GK{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($,Z){this.resolveProperties(Z)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class S4{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let Z=jS({[DS]:$.serviceName??"cline",...$.serviceVersion?{[LS]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(Z),this.loggerProvider=this.createLoggerProvider(Z),this.tracerProvider=this.createTracerProvider(Z),this.meterProvider)ZS.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)WS.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",Z){return QS.getTracer($,Z??this.options.serviceVersion)}createAdapter($){return new C4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let Z=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new P4({...$,adapters:[Z],distinctId:m0($.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 Z=H3(this.options.metricsExporter);if(Z.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(Q*0.8)),J=Z.map((X)=>TS(X,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:W})).filter((X)=>X!==null);if(J.length===0)return null;return new KS({resource:$,readers:J})}createTracerProvider($){let Z=H3(this.options.tracesExporter);if(Z.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let X of Z){let Y=zS(X,{endpoint:Q,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Y)J.push(Y)}if(J.length===0)return null;return new US({resource:$,spanProcessors:J})}createLoggerProvider($){let Z=H3(this.options.logsExporter);if(Z.length===0)return null;let Q=Z.map((W)=>{let J=_S(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new VS(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(Q.length===0)return null;return new BS({resource:$,processors:Q})}}function z9($){let Z=new S4($),Q=Z.createTelemetryService($);return Q.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:Z,telemetry:Q}}function a$($){if(mZ())return{telemetry:new GK($)};if($.enabled!==!0)return{telemetry:new P4({...$,distinctId:m0($.distinctId)})};return z9($)}function T9($){let{telemetry:Z,provider:Q}=a$($);return{telemetry:Z,provider:Q,flush:async()=>{let X=Q;if(X&&typeof X.forceFlush==="function")try{await X.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([Z.dispose(),Q?.dispose()])}}}function H3($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function _S($,Z){if($==="console")return new HS;if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/logs");return new JS({url:Q,headers:Z.headers})}function zS($,Z){if($==="console")return new fS(new AS);if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/traces");return new FS(new YS({url:Q,headers:Z.headers}))}function TS($,Z){if($==="console")return new BK({exporter:new GS,exportIntervalMillis:Z.interval,exportTimeoutMillis:Z.timeout});if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/metrics");return new BK({exporter:new XS({url:Q,headers:Z.headers}),exportIntervalMillis:Z.interval,exportTimeoutMillis:Z.timeout})}function B3($,Z){let Q=new URL($),W=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=W.endsWith(Z)?W:`${W}${Z}`,Q.toString()}var O9=F$(()=>{r0();g2();V3()});var LF={};i9(LF,{resolveCoreDistinctId:()=>m0,createOpenTelemetryTelemetryService:()=>z9,createConfiguredTelemetryService:()=>a$,createConfiguredTelemetryHandle:()=>T9,OpenTelemetryProvider:()=>S4,OpenTelemetryAdapter:()=>C4});var P9=F$(()=>{g2();O9()});import*as u00 from"@cline/llms";import{ClineNotSubscribedError as l00,ClineOrgIndividualInferenceSubscriptionError as p00,getClineOrgIndividualInferenceSubscriptionMessage as r00,getClineNotSubscribedMessage as i00,getClinePassSubscriptionUrl as n00,isClineNotSubscribedError as a00,isClineNotSubscribedMessage as s00,isClineOrgIndividualInferenceSubscriptionError as o00,isClineOrgIndividualInferenceSubscriptionMessage as t00}from"@cline/llms";import{buildClineSystemPrompt as $10,buildSdkErrorProperties as Z10,ContributionRegistry as Q10,captureSdkError as W10,createClineTelemetryServiceConfig as J10,createClineTelemetryServiceMetadata as X10,createContributionRegistry as Y10,createTool as j10,emptyWorkspaceManifest as V10,FEATURE_FLAGS as H10,FeatureFlagDefaultValue as B10,formatDisplayUserInput as G10,noopBasicLogger as K10,normalizeSdkError as F10,normalizeUserInput as A10,parseUserCommandEnvelope as f10,registerDisposable as U10,SDK_ERROR_TELEMETRY_EVENT as D10}from"@cline/shared";export*from"@cline/shared/storage";function wA($){if(typeof $!=="object"||$===null||!("error"in $))return;let Z=$.error;return typeof Z==="string"&&Z.trim()?Z:void 0}function UJ($,Z,Q){let W=wA(Q);if(W)return W;let J=Z.trim();if(J){let X=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${X}`}return`Cline account request failed with status ${$}`}class n9{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let Z=$.apiBaseUrl.trim();if(!Z)throw Error("apiBaseUrl is required");this.apiBaseUrl=Z,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 Z=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(Z)}/balance`)}async fetchUsageTransactions($){let Z=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Z)}/usages`)).items??[]}async fetchPaymentTransactions($){let Z=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Z)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let Z=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)Z.searchParams.set("type",$.type);return this.request(`${Z.pathname}${Z.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Z)}`)}async fetchOrganizationBalance($){let Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Z)}/balance`)}async fetchOrganizationUsageTransactions($){let Z=$.organizationId.trim();if(!Z)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(Z,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Z)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let Z=$?.trim();if(Z)return Z;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,Z){let Q=Z?.trim();if(Q)return Q;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let Y=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===$)?.memberId;if(!Y?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Y}async request($,Z){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,X=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let Y=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Z?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...W??{}},body:Z?.body!==void 0?JSON.stringify(Z.body):void 0,signal:J.signal});if(Y.status===204||Z?.expectNoContent){if(!Y.ok)throw Error(`Cline account request failed with status ${Y.status}`);return}let j=await Y.text(),V;if(j.trim())try{V=JSON.parse(j)}catch{if(!Y.ok)throw Error(UJ(Y.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Y.ok)throw Error(UJ(Y.status,j,V));if(typeof V==="object"&&V!==null){let H=V;if(typeof H.success==="boolean"){if(!H.success)throw Error(H.error||"Cline account request failed");return H.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(X)}}}function DJ($){return $.action==="clineAccount"}async function LJ($,Z){switch($.operation){case"fetchMe":return Z.fetchMe();case"fetchBalance":return Z.fetchBalance($.userId);case"fetchUsageTransactions":return Z.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return Z.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return Z.fetchUserOrganizations();case"fetchOrganizationBalance":return Z.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return Z.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await Z.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return Z.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class a9{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 Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:Z})}async fetchOrganizationUsageTransactions($){let Z=$.organizationId.trim();if(!Z)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:Z,...$.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}}function m4($){return{onAuth:({url:Z,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(Z)).catch((W)=>{$.onOpenUrlError?.({url:Z,error:W})})}catch(W){$.onOpenUrlError?.({url:Z,error:W})}$.onOutput?.(Z)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}G0();import{getClineEnvironmentConfig as GZ}from"@cline/shared";function mA(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function H1($){let Z=await import("node:http"),Q=$.host??"127.0.0.1",W=$.timeoutMs??300000,J=$.successHtml??vA,X=mA(),Y=!1,j=null,V=null,H=null,B=(F)=>{if(Y)return;Y=!0,X.resolve(F)},G=()=>{if(j)clearTimeout(j),j=null;let F=H;if(H=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:F})).catch(()=>{})},K=async()=>{return j=setTimeout(()=>{G(),B(null)},W),X.promise};for(let F of $.ports){let A=Z.createServer((f,D)=>{try{let U=new URL(f.url||"",`http://${Q}:${F}`);if(U.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let T={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(T.error){D.statusCode=400,D.end(`Authentication failed: ${T.error}`),G(),B(T);return}if(!T.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&T.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(J),G(),B(T)}catch{D.statusCode=500,D.end("Internal error")}}),L=await new Promise((f)=>{let D=(U)=>{A.off("error",D),f({bound:!1,error:U})};A.once("error",D),A.listen(F,Q,()=>{A.off("error",D),V=A,f({bound:!0})})});if(L.error){if(L.error.code==="EADDRINUSE")continue;throw G(),L.error}if(L.bound){H=F;let f=`http://${Q}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:F,callbackUrl:f})).catch(()=>{});return{callbackUrl:f,waitForCallback:K,cancelWait:()=>{G(),B(null)},close:()=>{G(),B(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var vA=`<!DOCTYPE html>
1
+ import{createRequire as NA}from"node:module";var MA=Object.defineProperty;var RA=($)=>$;function EA($,Z){this[$]=RA.bind(null,Z)}var n9=($,Z)=>{for(var Q in Z)MA($,Q,{get:Z[Q],enumerable:!0,configurable:!0,set:EA.bind(Z,Q)})};var F$=($,Z)=>()=>($&&(Z=$($=0)),Z);var fJ=NA(import.meta.url);import{AGENT_UNEXPECTED_REASONING_TOKENS_EVENT as CA,captureAgentUnexpectedReasoningTokens as PA,SDK_ERROR_TELEMETRY_EVENT as SA}from"@cline/shared";function l($,Z,Q){$?.capture({event:Z,properties:Q})}function v4($){if(!$)return;return $.substring(0,bA)}function yA($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function hA($){return typeof $==="string"?$:$.message}function _J($,Z){return $.some((Q)=>Z.has(Q.trim().toLowerCase()))}function kA($){l($,I.CLIENT.EXTENSION_ACTIVATED)}function o9($,Z){let Q=[...Z.vcs_types],W={root_count:Z.root_count,vcs_types:Q,is_multi_root:Z.root_count>1,has_git:_J(Q,new Set(["git"])),has_mercurial:_J(Q,new Set(["mercurial","hg"]))};if(Z.init_duration_ms!==void 0)W.init_duration_ms=Z.init_duration_ms;if(Z.feature_flag_enabled!==void 0)W.feature_flag_enabled=Z.feature_flag_enabled;if(Z.is_remote_workspace!==void 0)W.is_remote_workspace=Z.is_remote_workspace;l($,I.WORKSPACE.INITIALIZED,W)}function t9($,Z,Q){l($,I.WORKSPACE.INIT_ERROR,{error_type:yA(Z),error_message:v4(hA(Z)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function IA($,Z){l($,I.WORKSPACE.PATH_RESOLVED,{...Z})}function C1($,Z){l($,I.USER.AUTH_STARTED,{provider:Z})}function P1($,Z){l($,I.USER.AUTH_SUCCEEDED,{provider:Z})}function S1($,Z,Q){l($,I.USER.AUTH_FAILED,{provider:Z,errorMessage:v4(Q)})}function A$($,Z,Q){l($,I.USER.AUTH_LOGGED_OUT,{provider:Z,reason:Q})}function xA($,Z){l($,I.USER.PROVIDER_CONFIGURED,{provider:Z})}function zJ($,Z){$?.captureRequired(I.USER.TELEMETRY_OPT_OUT,Z)}function b1($,Z){let Q=Z.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:Z.id,account_email:Z.email,provider:Z.provider,organization_id:Z.organizationId,organization_name:Z.organizationName,member_id:Z.memberId})}function e9($,Z){l($,I.TASK.CREATED,Z)}function $Z($,Z){l($,I.TASK.RESTARTED,Z)}function c4($,Z){l($,I.TASK.COMPLETED,Z)}function Z8($,Z){l($,I.TASK.CONVERSATION_TURN,{...Z,timestamp:new Date().toISOString()})}function ZZ($,Z){l($,I.TASK.TOKEN_USAGE,Z)}function QZ($,Z,Q){l($,I.TASK.MODE_SWITCH,{ulid:Z,mode:Q})}function Q8($,Z){l($,I.TASK.TOOL_USED,Z)}function WZ($,Z){l($,I.TASK.SKILL_USED,Z)}function JZ($,Z){l($,I.TASK.DIFF_EDIT_FAILED,Z)}function u4($,Z){l($,I.TASK.PROVIDER_API_ERROR,{...Z,errorMessage:v4(Z.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function TJ($,Z){l($,I.SDK.TOOL_TIMEOUT,gA(Z))}function gA($){let Z={};for(let[Q,W]of Object.entries($))if(W!==void 0)Z[Q]=W;return Z}function XZ($,Z,Q){l($,I.TASK.MENTION_USED,{mentionType:Z,contentLength:Q,timestamp:new Date().toISOString()})}function YZ($,Z,Q,W){l($,I.TASK.MENTION_FAILED,{mentionType:Z,errorType:Q,errorMessage:v4(W),timestamp:new Date().toISOString()})}function jZ($,Z,Q,W,J){l($,I.TASK.MENTION_SEARCH_RESULTS,{queryLength:Z.length,resultCount:Q,searchType:W,isEmpty:J,timestamp:new Date().toISOString()})}function f$($,Z){l($,I.TASK.AGENT_CREATED,{...Z,timestamp:new Date().toISOString()})}function VZ($,Z){l($,I.TASK.AGENT_TEAM_CREATED,{...Z,timestamp:new Date().toISOString()})}function d4($,Z){l($,Z.event==="ended"?I.TASK.SUBAGENT_COMPLETED:I.TASK.SUBAGENT_STARTED,{...Z,timestamp:new Date().toISOString()})}function HZ($,Z,Q,W){l($,I.HOOKS.DISCOVERY_COMPLETED,{hookName:Z,globalCount:Q,workspaceCount:W,totalCount:Q+W,timestamp:new Date().toISOString()})}function BZ($,Z){l($,I.TASK.COMPACTION_EXECUTED,{...Z,timestamp:new Date().toISOString()})}function GZ($,Z){l($,I.TASK.COMPACTION_SKIPPED,{...Z,timestamp:new Date().toISOString()})}var bA=500,I;var G0=F$(()=>{I={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},AGENT:{UNEXPECTED_REASONING_TOKENS:CA},USER:{AUTH_STARTED:"user.auth_started",AUTH_SUCCEEDED:"user.auth_succeeded",AUTH_FAILED:"user.auth_failed",AUTH_LOGGED_OUT:"user.auth_logged_out",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",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"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:SA,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as wU,readFileSync as CU,statSync as PU,writeFileSync as SU}from"node:fs";import{dirname as bU}from"node:path";import{resolveGlobalSettingsPath as DX}from"@cline/shared/storage";import{z as L$}from"zod";function j6(){return H6.parse({})}function hU(){V6=void 0}function kU($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function IU($){let Z;try{Z=CU($,"utf8")}catch{return j6()}try{let Q=H6.safeParse(JSON.parse(Z));return Q.success?Q.data:j6()}catch{return j6()}}function xU(){let $=DX(),Z=PU($,{throwIfNoEntry:!1}),Q=Z?.mtimeMs??0,W=Z?.size??0,J=V6;if(J&&J.path===$&&J.mtimeMs===Q&&J.size===W)return J;let X=kU(Z?IU($):j6());return V6={path:$,mtimeMs:Q,size:W,value:X},V6}function D0(){return xU().value}function G1($,Z={}){let Q=DX(),W=D0();wU(bU(Q),{recursive:!0});let J=H6.parse($);if(!W.telemetryOptOut&&J.telemetryOptOut)zJ(Z.telemetry);SU(Q,`${JSON.stringify(J,null,2)}
2
+ `,"utf8"),hU()}function vZ(){return D0().telemetryOptOut}function gU($,Z={}){G1({...D0(),telemetryOptOut:$},Z)}function mU(){return D0().autoUpdateEnabled}function vU($,Z={}){G1({...D0(),autoUpdateEnabled:$},Z)}function cU(){return D0().compactionStrategy??"basic"}function uU($){G1({...D0(),compactionStrategy:$})}function K1($){return new Set($??D0().disabledTools??[])}function B6($){return new Set($??D0().disabledPlugins??[])}function dU($){return K1().has($)}function cZ($){let Z=D0(),Q=new Set(Z.disabledTools??[]),W=Q.has($);if(W)Q.delete($);else Q.add($);return G1({...Z,disabledTools:[...Q]}),!W}function LX($,Z){let Q=[...new Set($.map((X)=>X.trim()).filter(Boolean))];if(Q.length===0)return;let W=D0(),J=K1(W.disabledTools);for(let X of Q)if(Z)J.add(X);else J.delete(X);G1({...W,disabledTools:[...J]})}function _X($,Z){return LX([$],Z),Z}function lU($){return B6().has($)}function pU($,Z){let Q=$.trim();if(!Q)return;let W=D0(),J=B6(W.disabledPlugins);if(Z)J.add(Q);else J.delete(Q);G1({...W,disabledPlugins:[...J]})}function uZ($,Z){let Q=B6(Z);if(Q.size===0)return[...$];return $.filter((W)=>!Q.has(W))}function k1($,Z){let Q=K1(Z);if(Q.size===0)return[...$];return $.filter((W)=>!Q.has(W.name))}function dZ($,Z){if(!$||$.length===0)return $;let Q=K1(Z);if(Q.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(J,X)=>W.setup?.({...J,registerTool:(Y)=>{if(!Q.has(Y.name))J.registerTool(Y)}},X)}})}var UX,yU,H6,V6;var r0=F$(()=>{G0();UX=L$.preprocess(($)=>Array.isArray($)?$.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter(Boolean):void 0,L$.array(L$.string()).optional()).transform(($)=>{if(!$)return;let Z=[...new Set($)].sort((Q,W)=>Q.localeCompare(W));return Z.length>0?Z:void 0}),yU=L$.enum(["basic","agentic"]).catch("basic"),H6=L$.object({telemetryOptOut:L$.boolean().default(!1).catch(!1),autoUpdateEnabled:L$.boolean().default(!0).catch(!0),compactionStrategy:yU.optional(),disabledTools:UX.optional(),disabledPlugins:UX.optional()}).strip().transform(($)=>{let Z={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.compactionStrategy)Z.compactionStrategy=$.compactionStrategy;if($.disabledTools?.length)Z.disabledTools=$.disabledTools;if($.disabledPlugins?.length)Z.disabledPlugins=$.disabledPlugins;return Z})});var Xj={};n9(Xj,{normalizeUserMessage:()=>_z,buildInitialUserContent:()=>Lz});async function Lz($,Z,Q,W){let J=zz(Z),X=await Oz(Q,W);if(J.length===0&&!X)return $;let Y=[{type:"text",text:$},...J];if(X)Y.push(...X);return Y}function _z($){if($==null)return"";if(typeof $==="string")return $;let Z=$.content;if(typeof Z==="string")return Z;if(!Array.isArray(Z))return"";let Q=[];for(let W of Z)if(W&&typeof W==="object"&&W.type==="text"){let J=W.text;if(typeof J==="string")Q.push(J)}return Q.join(`
3
+ `)}function zz($){if(!$||$.length===0)return[];let Z=[];for(let Q of $){let W=Tz(Q);if(W)Z.push(W)}return Z}function Tz($){let Z=$.trim();if(!Z)return;let Q=Z.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let W=Q[1],J=Q[2];if(!W||!J)return;return{type:"image",mediaType:W,data:J}}return{type:"image",mediaType:"image/png",data:Z}}async function Oz($,Z){if(!$||$.length===0)return;let Q=Z??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(J)=>{let X=J.replace(/\\/g,"/");try{let Y=await Q(J);return{type:"file",path:X,content:Y}}catch(Y){let j=Y instanceof Error?Y.message:String(Y);return{type:"file",path:X,content:`Error fetching content: ${j}`}}}));if(W.length===0)return;return W}var YV={};n9(YV,{updateMcpSettingsFileSync:()=>U1,updateMcpSettingsFile:()=>Y5,updateMcpServerOAuthStateAsync:()=>eQ,updateMcpServerOAuthState:()=>h8,setMcpServerDisabled:()=>b8,resolveMcpServerRegistrations:()=>$1,resolveDefaultMcpSettingsPath:()=>Z0,registerMcpServersFromSettingsFile:()=>k8,normalizeMcpServerOAuthState:()=>S2,loadMcpSettingsFile:()=>S8,listMcpServerOAuthStatuses:()=>$7,hasMcpSettingsFile:()=>C$,getMcpServerOAuthState:()=>y8,McpSettingsUpdateSkippedError:()=>J5,McpSettingsMutatorPurityError:()=>C2,McpSettingsLockTimeoutError:()=>P2});import{existsSync as pj,mkdirSync as iQ,readFileSync as rj,renameSync as sQ,rmdirSync as KT,rmSync as nQ,statSync as FT,unlinkSync as ij,writeFileSync as nj}from"node:fs";import{randomUUID as AT}from"node:crypto";import{dirname as aj,join as lj}from"node:path";import{setTimeout as fT}from"node:timers/promises";import{resolveMcpSettingsPath as UT}from"@cline/shared/storage";import{z as w}from"zod";function aQ($){if(!$)return;if($==="http")return"streamableHttp";return $}function Z0(){return UT()}function NT($,Z){iQ(aj($),{recursive:!0});let Q=`${$}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{nj(Q,Z,{encoding:"utf8",flag:"wx"}),sQ(Q,$)}catch(W){try{ij(Q)}catch{}throw W}}function CT($){Atomics.wait(wT,0,0,$)}function PT($){return`${$}.lock`}function ej(){return`${process.pid}.${Date.now()}.${AT()}`}function $V($,Z){iQ(aj($),{recursive:!0});let Q=`${$}.tmp.${Z}`;nQ(Q,{recursive:!0,force:!0}),iQ(Q,{recursive:!0}),nj(lj(Q,`owner.${Z}`),Z,{encoding:"utf8",flag:"wx"});try{return sQ(Q,$),{lockDir:$,ownerFile:lj($,`owner.${Z}`)}}catch(W){if(nQ(Q,{recursive:!0,force:!0}),pj($))return;throw W}}function ZV($,Z){let Q;try{Q=Date.now()-FT($).mtimeMs}catch(J){if(J.code==="ENOENT")return;throw J}if(Q<tQ)return;Z.logger?.log(`[mcp-settings] Stale lock directory at ${$} (age ${Q}ms); reclaiming.`,{severity:"warn"});let W=`${$}.stale.${ej()}`;try{sQ($,W)}catch(J){if(J.code==="ENOENT")return;throw J}nQ(W,{recursive:!0,force:!0})}function ST($){try{ij($.ownerFile)}catch(Z){if(Z.code!=="ENOENT")throw Z}try{KT($.lockDir)}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTEMPTY"&&Q!=="EEXIST")throw Z}}function QV($){let Z=PT($);if(X5.has(Z))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:Z,token:ej()}}function bT($,Z){let{lockDir:Q,token:W}=QV($),J=Z.timeoutMs??tQ,X=Date.now();while(!0){let Y=$V(Q,W);if(Y)return X5.add(Q),Y;if(Date.now()-X>J)throw new P2(`Timed out waiting for MCP settings lock at ${Q} after ${J}ms.`);ZV(Q,Z),CT(tj)}}async function yT($,Z){let{lockDir:Q,token:W}=QV($),J=Z.timeoutMs??tQ,X=Date.now();while(!0){let Y=$V(Q,W);if(Y)return X5.add(Q),Y;if(Date.now()-X>J)throw new P2(`Timed out waiting for MCP settings lock at ${Q} after ${J}ms.`);ZV(Q,Z),await fT(tj)}}function WV($,Z,Q){try{let W=hT(Z),J=kT(W,Q);return NT(Z,`${JSON.stringify(W,null,2)}
4
+ `),J}finally{X5.delete($.lockDir),ST($)}}function U1($,Z,Q={}){let W=bT($,Q);return WV(W,$,Z)}async function Y5($,Z,Q={}){let W=await yT($,Q);return WV(W,$,Z)}function hT($){let Z=xT($);if(!Z.mcpServers||typeof Z.mcpServers!=="object"||Array.isArray(Z.mcpServers))Z.mcpServers={};return Z}function kT($,Z){let Q=JSON.stringify($),W=JSON.parse(Q),J=Z(W),X=JSON.stringify(W),Y=Z($);if(JSON.stringify($)!==X)throw new C2("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different settings.");if(JSON.stringify(Y)!==JSON.stringify(J))throw new C2("MCP settings mutator must be deterministic and free of side effects; repeated calls produced different return values.");return Y}function IT($){let Z=rj($,"utf8"),Q;try{Q=JSON.parse(Z)}catch(W){let J=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${J}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function xT($){try{return IT($)}catch(Z){if(Z.code==="ENOENT")return{};throw Z}}function JV($,Z){if(!Object.hasOwn($,Z))return;let Q=$[Z];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function gT($,Z,Q){Object.defineProperty($,Z,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function S8($={}){let Z=$.filePath??Z0(),Q=rj(Z,"utf8"),W;try{W=JSON.parse(Q)}catch(X){let Y=X instanceof Error?X.message:String(X);throw Error(`Failed to parse MCP settings JSON at "${Z}": ${Y}`)}let J=ET.safeParse(W);if(!J.success){let X=J.error.issues.map((Y)=>{let j=Y.path.join(".");return j?`${j}: ${Y.message}`:Y.message}).join("; ");throw Error(`Invalid MCP settings at "${Z}": ${X}`)}return J.data}function S2($){if(!$)return;let Z={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(Z).length>0?Z:void 0}function mT($){if($===void 0)return;let Z=oQ.safeParse($);if(!Z.success)return;return S2(Z.data)}function C$($={}){let Z=$.filePath??Z0();return pj(Z)}function $1($={}){let Z=S8($);return Object.entries(Z.mcpServers).map(([Q,W])=>({name:Q,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function b8($){let Z=$.filePath??Z0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");U1(Z,(W)=>{let J=W.mcpServers;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${Z}": mcpServers must be an object.`);let X={...J},Y=JV(X,Q);if(!Y)throw Error(`Unknown MCP server: ${Q}`);let j={...Y};if($.disabled)j.disabled=!0;else delete j.disabled;gT(X,Q,j),W.mcpServers=X})}function y8($,Z={}){let Q=S8(Z);if(!Object.hasOwn(Q.mcpServers,$))return;return S2(Q.mcpServers[$]?.oauth)}function XV($,Z){return(Q)=>{let W=Q.mcpServers,J=JV(W,$);if(!J)throw Error(`Unknown MCP server: ${$}`);let X=mT(J.oauth)??{},Y=S2(Z(X));if(Y)J.oauth=Y;else delete J.oauth;return Y??{}}}function h8($,Z,Q={}){let W=Q.filePath??Z0();return U1(W,XV($,Z))}async function eQ($,Z,Q={}){let W=Q.filePath??Z0();return Y5(W,XV($,Z))}function $7($={}){return $1($).map((Q)=>{let W=Q.transport.type!=="stdio",J=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:W,oauthConfigured:W&&typeof J==="string"&&J.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,W)=>Q.serverName.localeCompare(W.serverName))}async function k8($,Z={}){let Q=$1(Z);for(let W of Q)await $.registerServer(W);return Q}var P8,sj,oQ,DT,LT,_T,zT,TT,OT,oj,qT,MT,RT,ET,J5,P2,C2,tQ=1e4,tj=25,wT,X5;var j5=F$(()=>{P8=w.record(w.string(),w.string()),sj=w.record(w.string(),w.unknown()),oQ=w.object({clientInformation:w.record(w.string(),w.unknown()).optional(),tokens:w.record(w.string(),w.unknown()).optional(),codeVerifier:w.string().optional(),discoveryState:w.record(w.string(),w.unknown()).optional(),redirectUrl:w.string().url().optional(),lastError:w.string().optional(),lastAuthenticatedAt:w.number().int().positive().optional()}).strip(),DT=w.object({type:w.literal("stdio"),command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:P8.optional()}),LT=w.object({type:w.literal("sse"),url:w.string().url(),headers:P8.optional()}),_T=w.object({type:w.literal("streamableHttp"),url:w.string().url(),headers:P8.optional()}),zT=w.discriminatedUnion("type",[DT,LT,_T]),TT=w.object({transport:zT,disabled:w.boolean().optional(),metadata:sj.optional(),oauth:oQ.optional()}),OT=w.enum(["stdio","sse","http","streamableHttp"]).optional(),oj=w.object({type:w.enum(["stdio","sse","streamableHttp"]).optional(),transportType:OT,disabled:w.boolean().optional(),metadata:sj.optional(),oauth:oQ.optional()});qT=oj.extend({command:w.string().min(1),args:w.array(w.string()).optional(),cwd:w.string().min(1).optional(),env:P8.optional()}).superRefine(($,Z)=>{let Q=$.type??aQ($.transportType);if(Q&&Q!=="stdio")Z.addIssue({code:w.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})),MT=oj.extend({url:w.string().url(),headers:P8.optional()}).superRefine(($,Z)=>{let Q=$.type??aQ($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")Z.addIssue({code:w.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??aQ($.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}}),RT=w.union([TT,qT,MT]),ET=w.object({mcpServers:w.record(w.string(),RT)}).passthrough();J5=class J5 extends Error{constructor($){super($);this.name="McpSettingsUpdateSkippedError"}};P2=class P2 extends Error{constructor($){super($);this.name="McpSettingsLockTimeoutError"}};C2=class C2 extends Error{constructor($){super($);this.name="McpSettingsMutatorPurityError"}};wT=new Int32Array(new SharedArrayBuffer(4)),X5=new Set});import{existsSync as zE,mkdirSync as TE,readFileSync as OE,writeFileSync as qE}from"node:fs";import{resolve as ME}from"node:path";import{resolveSessionDataDir as RE}from"@cline/shared/storage";import{nanoid as EE}from"nanoid";import*as NE from"node-machine-id";function m0($){let Z=$?.trim();if(Z)return Z;let Q=PE();if(Q)return Q;return SE()}function CE(){let $=NE;return $.machineIdSync??$.default?.machineIdSync}function PE(){try{let $=CE();if(!$)return;return $().trim()||void 0}catch{return}}function SE(){let $=RE(),Z=ME($,wE);try{if(zE(Z)){let W=OE(Z,"utf8").trim();if(W.length>0)return W}}catch{}let Q=`cl-${EE()}`;try{TE($,{recursive:!0}),qE(Z,Q,"utf8")}catch{}return Q}var wE="machine-id";var g2=()=>{};class C4{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($,Z){if(!this.isEnabled())return;this.emitLog($,Z,!1)}emitRequired($,Z){this.emitLog($,Z,!0)}recordCounter($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.counters.get($);if(!X)X=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,X);X.add(Z,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.histograms.get($);if(!X)X=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,X);X.record(Z,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,Z,Q,W,J=!1){if(!this.meter||!J&&!this.isEnabled())return;let X=this.buildAttributes(Q),Y=JSON.stringify(X),j=this.gaugeValues.get($);if(Z===null){if(j){if(j.delete(Y),j.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let V=j;if(!V)V=new Map,this.gaugeValues.set($,V);if(!this.gauges.has($)){let H=this.meter.createObservableGauge($,W?{description:W}:void 0);H.addCallback((B)=>{for(let G of this.snapshotGaugeSeries($))B.observe(G.value,this.flattenProperties(G.attributes))}),this.gauges.set($,H)}V.set(Y,{value:Z,attributes:X})}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($,Z,Q){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(Z,Q));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,Z=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...Z?{_required:!0}:{}}}snapshotGaugeSeries($){let Z=this.gaugeValues.get($);if(!Z)return[];return Array.from(Z.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,Z="",Q=new WeakSet,W=0){if(!$)return{};let J={},X=100,Y=10;for(let[j,V]of Object.entries($)){if(j==="__proto__"||j==="constructor"||j==="prototype")continue;let H=Z?`${Z}.${j}`:j;if(V===null||V===void 0){J[H]=String(V);continue}if(Array.isArray(V)){let B=V.length>X?V.slice(0,X):V;try{J[H]=JSON.stringify(B)}catch{J[H]="[UnserializableArray]"}if(V.length>X)J[`${H}_truncated`]=!0,J[`${H}_original_length`]=V.length;continue}if(typeof V==="object"){if(V instanceof Date){J[H]=V.toISOString();continue}if(V instanceof Error){J[H]=V.message;continue}if(Q.has(V)){J[H]="[Circular]";continue}if(W>=Y){J[H]="[MaxDepthExceeded]";continue}Q.add(V),Object.assign(J,this.flattenProperties(V,H,Q,W+1));continue}if(JS(V)){J[H]=V;continue}try{J[H]=JSON.stringify(V)}catch{J[H]=String(V)}}return J}}function JS($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class z9{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,Z){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:Z})}emitRequired($,Z){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:Z})}recordCounter($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:Z,attributes:Q,description:W,required:J===!0})}recordHistogram($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:Z,attributes:Q,description:W,required:J===!0})}recordGauge($,Z,Q,W,J){if(!J&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:Z,attributes:Q,description:W,required:J===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class P4{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new z9({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 Z=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,Z)}captureRequired($,Z){let Q=this.buildAttributes(Z);for(let W of this.adapters)W.emitRequired($,Q)}recordCounter($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordCounter($,Z,X,W,J)}recordHistogram($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordHistogram($,Z,X,W,J)}recordGauge($,Z,Q,W,J=!1){let X=this.buildAttributes(Q);for(let Y of this.adapters)Y.recordGauge($,Z,X,W,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 V3=()=>{};import{metrics as XS,trace as YS}from"@opentelemetry/api";import{logs as jS}from"@opentelemetry/api-logs";import{OTLPLogExporter as VS}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as HS}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as BS}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as GS}from"@opentelemetry/resources";import{BatchLogRecordProcessor as KS,ConsoleLogRecordExporter as FS,LoggerProvider as AS}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as fS,MeterProvider as US,PeriodicExportingMetricReader as BK}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as DS,ConsoleSpanExporter as LS,SimpleSpanProcessor as _S}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as zS}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as TS,ATTR_SERVICE_VERSION as OS}from"@opentelemetry/semantic-conventions";class GK{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($,Z){this.resolveProperties(Z)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class S4{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let Z=GS({[TS]:$.serviceName??"cline",...$.serviceVersion?{[OS]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(Z),this.loggerProvider=this.createLoggerProvider(Z),this.tracerProvider=this.createTracerProvider(Z),this.meterProvider)XS.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)jS.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",Z){return YS.getTracer($,Z??this.options.serviceVersion)}createAdapter($){return new C4({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let Z=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new P4({...$,adapters:[Z],distinctId:m0($.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 Z=H3(this.options.metricsExporter);if(Z.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(Q*0.8)),J=Z.map((X)=>RS(X,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:W})).filter((X)=>X!==null);if(J.length===0)return null;return new US({resource:$,readers:J})}createTracerProvider($){let Z=H3(this.options.tracesExporter);if(Z.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,J=[];for(let X of Z){let Y=MS(X,{endpoint:Q,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(Y)J.push(Y)}if(J.length===0)return null;return new zS({resource:$,spanProcessors:J})}createLoggerProvider($){let Z=H3(this.options.logsExporter);if(Z.length===0)return null;let Q=Z.map((W)=>{let J=qS(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!J)return null;return new KS(J,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(Q.length===0)return null;return new AS({resource:$,processors:Q})}}function T9($){let Z=new S4($),Q=Z.createTelemetryService($);return Q.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:Z,telemetry:Q}}function s$($){if(vZ())return{telemetry:new GK($)};if($.enabled!==!0)return{telemetry:new P4({...$,distinctId:m0($.distinctId)})};return T9($)}function O9($){let{telemetry:Z,provider:Q}=s$($);return{telemetry:Z,provider:Q,flush:async()=>{let X=Q;if(X&&typeof X.forceFlush==="function")try{await X.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([Z.dispose(),Q?.dispose()])}}}function H3($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function qS($,Z){if($==="console")return new FS;if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/logs");return new VS({url:Q,headers:Z.headers})}function MS($,Z){if($==="console")return new _S(new LS);if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/traces");return new DS(new BS({url:Q,headers:Z.headers}))}function RS($,Z){if($==="console")return new BK({exporter:new fS,exportIntervalMillis:Z.interval,exportTimeoutMillis:Z.timeout});if(!Z.endpoint)return null;let Q=B3(Z.endpoint,"/v1/metrics");return new BK({exporter:new HS({url:Q,headers:Z.headers}),exportIntervalMillis:Z.interval,exportTimeoutMillis:Z.timeout})}function B3($,Z){let Q=new URL($),W=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=W.endsWith(Z)?W:`${W}${Z}`,Q.toString()}var q9=F$(()=>{r0();g2();V3()});var LF={};n9(LF,{resolveCoreDistinctId:()=>m0,createOpenTelemetryTelemetryService:()=>T9,createConfiguredTelemetryService:()=>s$,createConfiguredTelemetryHandle:()=>O9,OpenTelemetryProvider:()=>S4,OpenTelemetryAdapter:()=>C4});var S9=F$(()=>{g2();q9()});import*as r00 from"@cline/llms";import{ClineNotSubscribedError as n00,ClineOrgIndividualInferenceSubscriptionError as a00,getClineOrgIndividualInferenceSubscriptionMessage as s00,getClineNotSubscribedMessage as o00,getClinePassSubscriptionUrl as t00,isClineNotSubscribedError as e00,isClineNotSubscribedMessage as $10,isClineOrgIndividualInferenceSubscriptionError as Z10,isClineOrgIndividualInferenceSubscriptionMessage as Q10}from"@cline/llms";import{buildClineSystemPrompt as J10,buildSdkErrorProperties as X10,ContributionRegistry as Y10,captureSdkError as j10,createClineTelemetryServiceConfig as V10,createClineTelemetryServiceMetadata as H10,createContributionRegistry as B10,createTool as G10,emptyWorkspaceManifest as K10,FEATURE_FLAGS as F10,FeatureFlagDefaultValue as A10,formatDisplayUserInput as f10,noopBasicLogger as U10,normalizeSdkError as D10,normalizeUserInput as L10,parseUserCommandEnvelope as _10,registerDisposable as z10,SDK_ERROR_TELEMETRY_EVENT as T10}from"@cline/shared";export*from"@cline/shared/storage";function wA($){if(typeof $!=="object"||$===null||!("error"in $))return;let Z=$.error;return typeof Z==="string"&&Z.trim()?Z:void 0}function UJ($,Z,Q){let W=wA(Q);if(W)return W;let J=Z.trim();if(J){let X=J.length>200?`${J.slice(0,200)}...`:J;return`Cline account request failed with status ${$}: ${X}`}return`Cline account request failed with status ${$}`}class a9{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let Z=$.apiBaseUrl.trim();if(!Z)throw Error("apiBaseUrl is required");this.apiBaseUrl=Z,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 Z=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(Z)}/balance`)}async fetchUsageTransactions($){let Z=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Z)}/usages`)).items??[]}async fetchPaymentTransactions($){let Z=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(Z)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchAvailableSubscriptionPlans($){let Z=new URL("/api/v1/plans",this.apiBaseUrl);if($?.type)Z.searchParams.set("type",$.type);return this.request(`${Z.pathname}${Z.search}`)}async fetchCurrentUserPlan(){return this.request("/api/v1/users/me/plan")}async fetchOrganization($){let Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Z)}`)}async fetchOrganizationBalance($){let Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(Z)}/balance`)}async fetchOrganizationUsageTransactions($){let Z=$.organizationId.trim();if(!Z)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(Z,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(Z)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let Z=$?.trim();if(Z)return Z;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let J=await this.fetchMe();if(!J.id?.trim())throw Error("Unable to resolve current user id");return J.id}async resolveOrganizationMemberId($,Z){let Q=Z?.trim();if(Q)return Q;let J=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(J)return J;let Y=(await this.fetchUserOrganizations()).find((j)=>j.organizationId===$)?.memberId;if(!Y?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return Y}async request($,Z){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},J=new AbortController,X=setTimeout(()=>J.abort(),this.requestTimeoutMs);try{let Y=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:Z?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...W??{}},body:Z?.body!==void 0?JSON.stringify(Z.body):void 0,signal:J.signal});if(Y.status===204||Z?.expectNoContent){if(!Y.ok)throw Error(`Cline account request failed with status ${Y.status}`);return}let j=await Y.text(),V;if(j.trim())try{V=JSON.parse(j)}catch{if(!Y.ok)throw Error(UJ(Y.status,j,void 0));throw Error("Cline account response was not valid JSON")}if(!Y.ok)throw Error(UJ(Y.status,j,V));if(typeof V==="object"&&V!==null){let H=V;if(typeof H.success==="boolean"){if(!H.success)throw Error(H.error||"Cline account request failed");return H.data}}if(V===void 0||V===null)throw Error("Cline account response payload was empty");return V}finally{clearTimeout(X)}}}function DJ($){return $.action==="clineAccount"}async function LJ($,Z){switch($.operation){case"fetchMe":return Z.fetchMe();case"fetchBalance":return Z.fetchBalance($.userId);case"fetchUsageTransactions":return Z.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return Z.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return Z.fetchUserOrganizations();case"fetchOrganizationBalance":return Z.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return Z.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await Z.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return Z.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class s9{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 Z=$.trim();if(!Z)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:Z})}async fetchOrganizationUsageTransactions($){let Z=$.organizationId.trim();if(!Z)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:Z,...$.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}}function m4($){return{onAuth:({url:Z,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(Z)).catch((W)=>{$.onOpenUrlError?.({url:Z,error:W})})}catch(W){$.onOpenUrlError?.({url:Z,error:W})}$.onOutput?.(Z)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}G0();import{getClineEnvironmentConfig as KZ}from"@cline/shared";function mA(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function H1($){let Z=await import("node:http"),Q=$.host??"127.0.0.1",W=$.timeoutMs??300000,J=$.successHtml??vA,X=mA(),Y=!1,j=null,V=null,H=null,B=(F)=>{if(Y)return;Y=!0,X.resolve(F)},G=()=>{if(j)clearTimeout(j),j=null;let F=H;if(H=null,V)V.close(),V.closeAllConnections?.(),V=null;if(F!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:F})).catch(()=>{})},K=async()=>{return j=setTimeout(()=>{G(),B(null)},W),X.promise};for(let F of $.ports){let A=Z.createServer((f,D)=>{try{let U=new URL(f.url||"",`http://${Q}:${F}`);if(U.pathname!==$.callbackPath){D.statusCode=404,D.end("Not found");return}let T={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(T.error){D.statusCode=400,D.end(`Authentication failed: ${T.error}`),G(),B(T);return}if(!T.code){D.statusCode=400,D.end("Missing authorization code");return}if($.expectedState&&T.state!==$.expectedState){D.statusCode=400,D.end("State mismatch");return}D.statusCode=200,D.setHeader("Content-Type","text/html; charset=utf-8"),D.end(J),G(),B(T)}catch{D.statusCode=500,D.end("Internal error")}}),L=await new Promise((f)=>{let D=(U)=>{A.off("error",D),f({bound:!1,error:U})};A.once("error",D),A.listen(F,Q,()=>{A.off("error",D),V=A,f({bound:!0})})});if(L.error){if(L.error.code==="EADDRINUSE")continue;throw G(),L.error}if(L.bound){H=F;let f=`http://${Q}:${F}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:F,callbackUrl:f})).catch(()=>{});return{callbackUrl:f,waitForCallback:K,cancelWait:()=>{G(),B(null)},close:()=>{G(),B(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var vA=`<!DOCTYPE html>
5
5
  <html lang="en">
6
6
  <head>
7
7
  <meta charset="utf-8">
@@ -42,8 +42,8 @@ import{createRequire as NA}from"node:module";var MA=Object.defineProperty;var RA
42
42
  </div>
43
43
  <script>setTimeout(() => window.close(), 3000);</script>
44
44
  </body>
45
- </html>`;function OJ($){let Z="";for(let Q=0;Q<$.length;Q+=1)Z+=String.fromCharCode($[Q]??0);return btoa(Z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function cA($){let Q=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(W)}function uA($=32){let Z=new Uint8Array($);return crypto.getRandomValues(Z),OJ(Z)}async function l4(){let $=uA(),Z=OJ(await cA($));return{verifier:$,challenge:Z}}function p4($){return $.endsWith("/")?$.slice(0,-1):$}function U$($,Z){return new URL(Z,`${p4($)}/`).toString()}function W2($,Z={}){let Q=$.trim();if(!Q)return{};try{let W=new URL(Q);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:Z.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(Z.allowHashCodeState&&Q.includes("#")){let[W,J]=Q.split("#",2);return{code:W||void 0,state:J||void 0}}if(Q.includes("code=")){let W=new URLSearchParams(Q);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:Z.includeProvider?W.get("provider")??void 0:void 0}}return{code:Q}}function dA($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function _0($){if(!$)return null;try{let Z=$.split(".");if(Z.length!==3)return null;let Q=Z[1];if(!Q)return null;let W=Q.replace(/-/g,"+").replace(/_/g,"/"),J=W.padEnd(W.length+(4-W.length%4)%4,"="),X=dA(J);if(!X)return null;return JSON.parse(X)}catch{return null}}function J2($){try{let Z=JSON.parse($),Q=Z.error,W=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,J=typeof Z.error_description==="string"?Z.error_description:typeof Z.message==="string"?Z.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:W,message:J}}catch{return{}}}function X2($,Z){return Date.now()>=$.expires-Z}async function Y2($){if(!$.onManualCodeInput){let X=await $.waitForCallback();return{code:X?.code,state:X?.state,provider:X?.provider,error:X?.error}}let Z,Q,W=$.onManualCodeInput().then((X)=>{Z=X,$.cancelWait()}).catch((X)=>{Q=X instanceof Error?X:Error(String(X)),$.cancelWait()}),J=await $.waitForCallback();if(Q)throw Q;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(Z)return W2(Z,$.parseOptions);if(await W,Q)throw Q;if(Z)return W2(Z,$.parseOptions);return{}}var r4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},EJ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},KZ="https://api.workos.com",lA="/auth",qJ=Array.from({length:11},($,Z)=>48801+Z),pA=300000,rA=30000,j2=30000,iA=300,nA=5;class b1 extends Error{status;errorCode;constructor($,Z){super($);this.name="ClineOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 aA($){let Z=Date.parse($);if(Number.isNaN(Z))throw Error(`Invalid expiresAt value: ${$}`);return Z}function FZ($,Z,Q={}){let W=$.userInfo.clineUserId??Q.accountId,J=$.refreshToken??Q.refresh;if(!J)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:J,expires:aA($.expiresAt),accountId:W??void 0,email:$.userInfo.email||Q.email,metadata:{provider:Z,tokenType:$.tokenType,userInfo:$.userInfo}}}async function AZ($){if(!$)return{};return typeof $==="function"?await $():$}function MJ($,Z){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return Z;return Math.floor($)}async function RJ($){await new Promise((Z)=>setTimeout(Z,$))}function fZ($,Z){if(!$.success||!$.data?.accessToken)throw Error(Z);return $.data}async function NJ($,Z){let Q=await fetch(U$(KZ,EJ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(Z?.requestTimeoutMs??j2)}),W=await Q.json().catch(()=>({}));if(!Q.ok)throw new b1(`Device authorization failed: ${Q.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Q.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:MJ(W.expires_in,iA),pollIntervalSeconds:MJ(W.interval,nA)}}async function wJ($){let Z=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=Z){let W=await fetch(U$($.workosApiBaseUrl,EJ.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 W.json().catch(()=>({}));if(W.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 RJ(Q*1000);break}case"slow_down":{Q+=1,await RJ(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new b1(J.error_description||"WorkOS authorization failed",{status:W.status,errorCode:J.error});default:throw new b1(`WorkOS token polling failed: ${W.status}${J.error_description?` - ${J.error_description}`:""}`,{status:W.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function CJ($,Z,Q){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(U$(Z.apiBaseUrl,r4.register),{method:"POST",headers:{"Content-Type":"application/json",...await AZ(Z.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Z.requestTimeoutMs??j2)});if(!J.ok){let Y=await J.text().catch(()=>""),j=J2(Y);throw new b1(`Token registration failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let X=await J.json();return FZ(fZ(X,"Invalid token exchange response"),Q??Z.provider)}async function sA($,Z,Q,W){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Z,provider:W??Q.provider},X=await fetch(U$(Q.apiBaseUrl,r4.token),{method:"POST",headers:{"Content-Type":"application/json",...await AZ(Q.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Q.requestTimeoutMs??j2)});if(!X.ok){let j=await X.text().catch(()=>""),V=J2(j);throw new b1(`Token exchange failed: ${X.status}${V.message?` - ${V.message}`:""}`,{status:X.status,errorCode:V.code})}let Y=await X.json();return FZ(fZ(Y,"Invalid token exchange response"),W??Q.provider)}async function UZ($){w1($.telemetry,$.provider??"cline");let Z=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:qJ,W=$.callbackPath??lA,J=Z?null:await H1({ports:Q,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=J?.callbackUrl||`http://127.0.0.1:${Q[0]??qJ[0]}${W}`;try{let Y;if(Z){let j=GZ().workOsClientId,V=await NJ(j,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let H=await wJ({clientId:j,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??j2,workosApiBaseUrl:KZ,onProgress:$.callbacks.onProgress});Y=await CJ(H,$,$.provider)}else{let j=new URL(U$($.apiBaseUrl,r4.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",X),j.searchParams.set("redirect_uri",X),$.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let V,H=$.provider,B=await Y2({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(B.error)throw Error(`OAuth error: ${B.error}`);if(V=B.code,H=B.provider??H,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=W2(G,{includeProvider:!0});V=K.code,H=K.provider??H}if(!V)throw Error("Missing authorization code");Y=await sA(V,X,$,H)}return C1($.telemetry,$.provider??"cline"),S1($.telemetry,{id:Y.accountId,email:Y.email,provider:$.provider??"cline"}),Y}catch(Y){throw P1($.telemetry,$.provider??"cline",Y instanceof Error?Y.message:String(Y)),Y}finally{J?.close()}}async function oA($){return await NJ(GZ().workOsClientId,$)}async function tA($){let Z=$.provider??"cline";w1($.telemetry,Z);try{let Q=await wJ({clientId:GZ().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??j2,workosApiBaseUrl:KZ}),W=await CJ(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return C1($.telemetry,Z),S1($.telemetry,{id:W.accountId,email:W.email,provider:Z}),W}catch(Q){throw P1($.telemetry,Z,Q instanceof Error?Q.message:String(Q)),Q}}async function PJ($,Z){let Q=await fetch(U$(Z.apiBaseUrl,r4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await AZ(Z.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Z.requestTimeoutMs??j2)});if(!Q.ok){let X=await Q.text().catch(()=>""),Y=J2(X);throw new b1(`Token refresh failed: ${Q.status}${Y.message?` - ${Y.message}`:""}`,{status:Q.status,errorCode:Y.code})}let W=await Q.json(),J=$.metadata?.provider??Z.provider;return FZ(fZ(W,"Invalid token refresh response"),J,$)}async function DZ($,Z,Q){if(!$)return null;let W=Q?.refreshBufferMs??pA,J=Q?.retryableTokenGraceMs??rA;if(Q?.forceRefresh!==!0&&!X2($,W))return $;try{return await PJ($,Z)}catch(Y){if(Y instanceof b1&&Y.isLikelyInvalidGrant())return A$(Z.telemetry,Z.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}G0();import{nanoid as eA}from"nanoid";var W0={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 i4 extends Error{status;errorCode;constructor($,Z){super($);this.name="OpenAICodexOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 $f($,Z,Q=W0.redirectUri){let W=await fetch(W0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:W0.clientId,code:$,code_verifier:Z,redirect_uri:Q}),signal:AbortSignal.timeout(W0.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let J=await W.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 Zf($){try{let Z=await fetch(W0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:W0.clientId}),signal:AbortSignal.timeout(W0.httpTimeoutMs)});if(!Z.ok){let W=await Z.text().catch(()=>""),J=J2(W);throw new i4(`Token refresh failed: ${Z.status}${J.message?` - ${J.message}`:""}`,{status:Z.status,errorCode:J.code})}let Q=await Z.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(Z){if(Z instanceof i4)throw Z;return{type:"failed"}}}async function Qf($="pi"){let{verifier:Z,challenge:Q}=await l4(),W=eA(32),J=new URL(W0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",W0.clientId),J.searchParams.set("redirect_uri",W0.redirectUri),J.searchParams.set("scope",W0.scopes),J.searchParams.set("code_challenge",Q),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",W),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:Z,state:W,url:J.toString()}}function Wf(){try{let $=new URL(W0.redirectUri),Z=$.port.length>0?Number.parseInt($.port,10):W0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Z)?Z:W0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:W0.callbackPort,callbackPath:"/auth/callback",redirectUri:W0.redirectUri}}}function Jf($,Z){let Q=Z?_0(Z):_0($),W=Q?Q:_0($),X=W?.[W0.jwtClaimPath]?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;let Y=W?.organizations;if(Array.isArray(Y)&&Y.length>0){let V=Y[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function SJ($,Z){let Q=Jf($.access,$.idToken)??Z?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Z?.refresh||"",expires:$.expires,accountId:Q,email:$.email??Z?.email,metadata:{...Z?.metadata??{},provider:"openai-codex"}}}async function LZ($){w1($.telemetry,"openai-codex");let Z=Wf(),{verifier:Q,state:W,url:J}=await Qf($.originator),X=await H1({host:Z.host,ports:[Z.port],callbackPath:Z.callbackPath,expectedState:W});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let Y;try{let j=await Y2({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==W)throw Error("State mismatch");if(Y=j.code,!Y){let B=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=W2(B,{allowHashCodeState:!0});if(G.state&&G.state!==W)throw Error("State mismatch");Y=G.code}if(!Y)throw Error("Missing authorization code");let V=await $f(Y,Q,Z.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let H=SJ(V);return C1($.telemetry,"openai-codex"),S1($.telemetry,{id:H.accountId,email:H.email,provider:"openai-codex"}),H}catch(j){throw P1($.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{X.close()}}async function bJ($,Z){let Q=await Zf($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=SJ(Q,Z);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function _Z($,Z){if(!$)return null;let Q=Z?.refreshBufferMs??W0.refreshBufferMs,W=Z?.retryableTokenGraceMs??W0.retryableTokenGraceMs;if(Z?.forceRefresh!==!0&&!X2($,Q))return $;try{return await bJ($.refresh,$)}catch(X){if(X instanceof i4&&X.isLikelyInvalidGrant())return A$(Z?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}G0();import{nanoid as yJ}from"nanoid";class zZ{ttlMs;maxEntries;entries=new Map;constructor($,Z){this.ttlMs=$;this.maxEntries=Z}get($,Z=Date.now()){this.pruneExpired(Z);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,Z,Q=Date.now(),W=this.ttlMs){this.pruneExpired(Q),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:Z,expiresAt:Q+W})}pruneExpired($){for(let[Z,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(Z)}}var Xf="a8331954c0cf48ba99b5dd223a14c6ea",Yf="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",jf="openid offline_access",OZ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Vf="c1aba3deed5740659981a752714eba33",Hf="https://login-ext.identity.oraclecloud.com",Bf="openid offline_access",qZ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm";var Gf="/auth/oca",Kf=Array.from({length:11},($,Z)=>48801+Z),Ff=300000,Af=30000,hJ=30000,ff=600000;class n4 extends Error{status;errorCode;constructor($,Z){super($);this.name="OcaOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 y1={internal:{clientId:Xf,idcsUrl:Yf,scopes:jf,baseUrl:OZ},external:{clientId:Vf,idcsUrl:Hf,scopes:Bf,baseUrl:qZ}},W8=new Map,Uf=86400000,Df=300000,Lf=32,TZ=new zZ(Uf,Lf);function kJ($){if(typeof $==="function")return $();return $??"internal"}function IJ($){return{internal:{clientId:$?.internal?.clientId??y1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??y1.internal.idcsUrl,scopes:$?.internal?.scopes??y1.internal.scopes,baseUrl:$?.internal?.baseUrl??y1.internal.baseUrl},external:{clientId:$?.external?.clientId??y1.external.clientId,idcsUrl:$?.external?.idcsUrl??y1.external.idcsUrl,scopes:$?.external?.scopes??y1.external.scopes,baseUrl:$?.external?.baseUrl??y1.external.baseUrl}}}function _f($=Date.now()){let Z=$-ff;for(let[Q,W]of W8.entries())if(W.createdAt<Z)W8.delete(Q)}function zf($,Z,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=_0(Z)?.exp;if(typeof J==="number"&&J>0)return J*1000;let Y=_0(Q)?.exp;if(typeof Y==="number"&&Y>0)return Y*1000;return Date.now()+3600000}function xJ($,Z,Q){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let J=$.refresh_token??Q?.refresh;if(!J)throw Error("Token response did not include a refresh token");let X=_0($.id_token),Y=_0(W),j=X?.sub??Y?.sub,V=X?.email??Y?.email;return{access:W,refresh:J,expires:zf($,W,$.id_token),accountId:j??Q?.accountId,email:V??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:Z,subject:j,idToken:$.id_token}}}async function gJ($,Z){let Q=p4($),W=TZ.get(Q);if(W)return W;let J=`${Q}/.well-known/openid-configuration`,X=await fetch(J,{method:"GET",signal:AbortSignal.timeout(Z)});if(!X.ok){let V=`${Q}/oauth2/v1/token`;return TZ.set(Q,V,Date.now(),Df),V}let j=(await X.json()).token_endpoint||`${Q}/oauth2/v1/token`;return TZ.set(Q,j),j}function mJ($){return{code:$.error,message:$.error_description}}async function Tf($){let Z=W8.get($.state);if(!Z)throw Error("No PKCE verifier found for this state");W8.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,W=await gJ(Q.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Z.redirectUri,client_id:Q.clientId,code_verifier:Z.verifier}),X=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),Y=await X.json();if(!X.ok){let V=mJ(Y);throw new n4(`Token exchange failed: ${X.status}${V.message?` - ${V.message}`:""}`,{status:X.status,errorCode:V.code})}let j=_0(Y.id_token);if(!Y.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==Z.nonce)throw Error("OIDC nonce verification failed");return xJ(Y,$.mode)}function Of($){let Z=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${p4(Z.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",Z.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",Z.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function MZ($){w1($.telemetry,"oca");let Z=IJ($.config),Q=kJ($.mode),W=$.callbackPorts?.length?$.callbackPorts:Kf,J=$.callbackPath??Gf,X=$.requestTimeoutMs??hJ,Y=await H1({ports:W,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=Y.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let V=yJ(16),H=yJ(16),{verifier:B,challenge:G}=await l4();_f(),W8.set(V,{verifier:B,nonce:H,mode:Q,redirectUri:j,createdAt:Date.now()});let K=Of({callbackUrl:j,mode:Q,state:V,nonce:H,challenge:G,config:Z});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await Y2({waitForCallback:Y.waitForCallback,cancelWait:Y.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,L=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(!L||L!==V)throw Error("State mismatch");let f=await Tf({code:A,state:L,mode:Q,config:Z,requestTimeoutMs:X});return C1($.telemetry,"oca"),S1($.telemetry,{id:f.accountId,email:f.email,provider:"oca"}),f}catch(F){throw P1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{Y.close()}}async function vJ($,Z={}){let Q=IJ(Z.config),W=Z.requestTimeoutMs??hJ,J=$.metadata?.mode,X=J==="internal"||J==="external"?J:kJ(Z.mode),Y=X==="external"?Q.external:Q.internal,j=await gJ(Y.idcsUrl,W),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Y.clientId}),H=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(W)}),B=await H.json();if(!H.ok){let G=mJ(B);throw new n4(`Token refresh failed: ${H.status}${G.message?` - ${G.message}`:""}`,{status:H.status,errorCode:G.code})}return xJ(B,X,$)}async function RZ($,Z,Q){if(!$)return null;let W=Z?.refreshBufferMs??Q?.refreshBufferMs??Ff,J=Z?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??Af;if(Z?.forceRefresh!==!0&&!X2($,W))return $;try{return await vJ($,Q)}catch(Y){if(Y instanceof n4&&Y.isLikelyInvalidGrant())return A$(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}import{getClineEnvironmentConfig as cJ}from"@cline/shared";var a4="workos:";function qf($){let Z=$.trim();return Z.toLowerCase().startsWith(a4)?Z:`${a4}${Z}`}function Mf($){let Z=$.trim();return Z.toLowerCase().startsWith(a4)?Z.slice(a4.length):Z}function Rf($){let Q=_0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function Ef($,Z){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let W=Rf(Z);if(W)return W;return Date.now()-1}function Nf($,Z){let Q=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!Q||!W)return null;let J=Z?.normalizeAccessToken?.(Q)??Q;if(!J)return null;return{access:J,refresh:W,expires:Ef($,J),accountId:$.auth?.accountId}}function wf($){let Z=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:Z,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},W={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(W,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return W}function EZ($){let Z=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:Z,getApiKey(Q){let W=Q?.auth?.accessToken?.trim();if(W)return $.formatAccessToken?.(W)??W;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return wf({...Q,storageProviderId:Z,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function uJ($){return EZ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:qf,normalizeStoredAccessToken:Mf,login:({settings:Z,callbacks:Q,telemetry:W})=>UZ({apiBaseUrl:Z?.baseUrl?.trim()||cJ().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:W}),refresh:({settings:Z,credentials:Q,forceRefresh:W,telemetry:J})=>DZ(Q,{apiBaseUrl:Z.baseUrl?.trim()||cJ().apiBaseUrl,telemetry:J},{forceRefresh:W})})}var Cf=[uJ({providerId:"cline"}),uJ({providerId:"cline-pass",storageProviderId:"cline"}),EZ({providerId:"oca",login:({settings:$,callbacks:Z,telemetry:Q})=>MZ({mode:$?.oca?.mode,callbacks:Z,telemetry:Q}),refresh:({settings:$,credentials:Z,forceRefresh:Q,telemetry:W})=>RZ(Z,{forceRefresh:Q,telemetry:W},{mode:$.oca?.mode,telemetry:W})}),EZ({providerId:"openai-codex",login:({callbacks:$,telemetry:Z})=>LZ({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:Z}),refresh:({credentials:$,forceRefresh:Z,telemetry:Q})=>_Z($,{forceRefresh:Z,telemetry:Q})})],Pf=new Map(Cf.map(($)=>[$.providerId,$]));function B0($){return Pf.get($.trim().toLowerCase())}function J8($){return B0($)!==void 0}function Sf($){return B0($)?.storageProviderId}function bf($,Z){let Q=B0(Z),W=Q?.storageProviderId??Z,J=$.getProviderSettings(W);return Q?.getApiKey(J)??s4(Z,J)}async function NZ($,Z,Q){let W=B0(Z);if(!W)throw Error(`Provider "${Z}" does not support OAuth login`);let J=$.getProviderSettings(W.storageProviderId),X=await W.login({settings:J,callbacks:Q.callbacks,telemetry:Q.telemetry});return W.saveCredentials({manager:$,settings:J,credentials:X})}function wZ($,Z){let Q=B0($);if(!Q)return null;return Nf(Z,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function X8($){let Z=B0($.providerId);if(!Z)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return Z.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function s4($,Z){let Q=B0($);if(Q)return Q.getApiKey(Z);return Z?.auth?.accessToken?.trim()||Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0}function yf($,Z){let Q=B0($);if(!Q)return Z.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:Z.access}})??Z.access}import*as S0 from"@cline/llms";import{z as R}from"zod";import*as i from"@cline/llms";function CZ($){if(!Array.isArray($))return[];return $.map((Z)=>{if(typeof Z==="string")return Z.trim();if(Z&&typeof Z==="object"){let Q=Z;for(let W of[Q.id,Q.name,Q.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((Z)=>Z.length>0)}function hf($,Z){let Q=CZ($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let W=$,J=CZ(W.data??W.models);if(J.length>0)return J;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let Y=Object.keys(W.models).filter((j)=>j.trim().length>0);if(Y.length>0)return Y}let X=W.providers?.[Z];if(X&&typeof X==="object"){let j=CZ(X.models??X);if(j.length>0)return j}return[]}async function o4($,Z){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return hf(await Q.json(),Z)}function dJ($){return $.replace(/\/+$/,"")}function t4($,Z,Q){let W=Q?.trim();if(!W)return;let J=$?.trim();if(!J||!Z?.trim())return W;try{let X=new URL(W),Y=new URL(Z),j=new URL(J);if(X.origin!==Y.origin)return W;let V=dJ(Y.pathname),H=dJ(j.pathname);if(V&&X.pathname.startsWith(`${V}/`)){let B=X.pathname.slice(V.length);j.pathname=`${H}${B}`}else j.pathname=X.pathname;return j.search=X.search,j.hash=X.hash,j.toString()}catch{return W}}function kf($){return Object.fromEntries(Object.entries($).map(([Z,Q])=>[Z,{...Q}]))}function If($){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 xf=Object.values(i.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:kf($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),rJ=Object.fromEntries(xf.map(($)=>[$.id,$]));function gf($){return rJ[$]}function mf(){return Object.fromEntries(Object.entries(rJ).filter(([,$])=>If($)))}function iJ($=[]){let Z=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return Z.length>0?Z:void 0}var nJ="https://models.dev/api.json",vf=600000,aJ=300000,cf=5000,$6=new Map,Y8=new Map,SZ=new Map,e4=new Map;async function uf(){return i.getGeneratedProviderModels()}async function df($,Z={},Q={},W={},J={},X={}){if($==="litellm")return i.sortModelsByReleaseDate(W);let Y=await uf(),j=i.resolveProviderModelCatalogKeys($),V=Object.assign({},...j.map((K)=>Y[K]??{})),H=Boolean(i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),B=Object.keys(J).length>0;if(H&&B)return i.sortModelsByReleaseDate({...J,...X});if($==="openai-codex")return i.sortModelsByReleaseDate({...Z,...i.filterOpenAICodexModels(Q),...J,...X});if($==="cline-pass"&&Object.keys(Q).length>0)return i.sortModelsByReleaseDate({...Q,...X});let G=i.sortModelsByReleaseDate({...V,...Z,...Q,...W,...J});if($==="cline")return i.sortModelsByReleaseDate({...i.preferCanonicalModelIds(G,i.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...X});return i.sortModelsByReleaseDate({...G,...X})}function lf($,Z){let Q=i.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((W)=>Z[W]??{}))}function Z6($){let Z=$?.trim();return Z&&Z.length>0?Z:""}function bZ($){let Z=$.apiKey?.trim()||$.accessToken?.trim();return Z&&Z.length>0?Z:void 0}function pf($){let Z=2166136261;for(let Q=0;Q<$.length;Q+=1)Z^=$.charCodeAt(Q),Z+=(Z<<1)+(Z<<4)+(Z<<7)+(Z<<8)+(Z<<24);return(Z>>>0).toString(16)}function rf($,Z){return`${$}:${Z6(Z.baseUrl)}:${pf(bZ(Z)??"")}`}async function Q6($,Z,Q=cf){let W=new AbortController,J=setTimeout(()=>W.abort(),Q);try{return await fetch($,{...Z,signal:W.signal})}finally{clearTimeout(J)}}function D$($,Z,Q){if(Q&&!$.includes(Z))$.push(Z)}function W6($,Z){let Q=["streaming","tools"];return D$(Q,"images",Boolean(Z.supportsImages)),D$(Q,"prompt-cache",Boolean(Z.supportsPromptCache)),D$(Q,"reasoning",Boolean(Z.supportsReasoning)),{id:$,name:Z.name??$,contextWindow:Z.contextWindow,maxInputTokens:Z.maxInputTokens,maxTokens:Z.maxTokens,capabilities:Q,releaseDate:Z.releaseDate,status:"active"}}async function nf($,Z){let Q=await Q6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let J=(await Q.json())?.data??[],X={};for(let Y of J){let j=Y.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let V=Y.supported_features??[];X[j]=W6(j,{name:j,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return X}function lJ($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let Z=Number($);return Number.isFinite(Z)?Z:void 0}return}async function af($,Z){let Q=await Q6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":Z}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let J=(await Q.json())?.data??[],X={};for(let Y of J){let j=Y.id?.trim();if(!j)continue;X[j]=W6(j,{name:j,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return X}async function sf($,Z){let W=`${(Z6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await Q6(W,{method:"GET",headers:{Authorization:`Bearer ${Z}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let Y=(await J.json())?.data??[],j={};for(let V of Y){let H=V.id?.trim();if(!H)continue;let B=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];D$(F,"tools",B.includes("tools")),D$(F,"reasoning",B.includes("reasoning")),D$(F,"temperature",G.includes("temperature")),D$(F,"images",K.includes("image"));let A={input:lJ(V.pricing?.prompt),output:lJ(V.pricing?.completion)};j[H]={id:H,name:V.name??H,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 j}function of($){let Z=Z6($).replace(/\/+$/,"");if(!Z)return"http://localhost:4000";return Z.endsWith("/v1")?Z.slice(0,-3):Z}function tf($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function ef($){let Z=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Q=500,W=Z?`: ${Z.slice(0,500)}${Z.length>500?"...":""}`:"";return`HTTP ${$.status}${W}`}async function $U($,Z){let Q=of($.baseUrl),W=[],J=[["x-litellm-api-key",{"x-litellm-api-key":Z}],["Authorization",{Authorization:`Bearer ${Z}`}]];for(let X of tf(Q))for(let[Y,j]of J)try{let V=await Q6(X,{method:"GET",headers:{accept:"application/json",...j}});if(V.ok){let B=(await V.json())?.data??[],G={};for(let K of B){let F=K.model_name?.trim(),L=K.litellm_params?.model?.trim()||F;if(!L)continue;let f=K.model_info,D=W6(L,{name:F??L,maxTokens:f?.max_output_tokens??f?.max_tokens,maxInputTokens:f?.max_input_tokens??f?.max_tokens,supportsImages:f?.supports_vision,supportsPromptCache:f?.supports_prompt_caching,supportsReasoning:f?.supports_reasoning});if(G[L]=D,F)G[F]={...D,id:F,name:F}}return G}W.push(`${new URL(X).pathname} (${Y}): ${await ef(V)}`)}catch(V){let H=V instanceof Error?V.message:String(V);W.push(`${new URL(X).pathname} (${Y}): ${H}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${W.join("; ")}`)}var sJ={baseten:nf,hicap:af,litellm:$U,poolside:sf},pJ=new Map,PZ=new Map;function ZU($,Z){return`${$}:${Z6(Z.baseUrl)}`}async function QU($,Z,Q){let W=i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=t4(Q.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!J)return{};let X=Z?.cacheTtlMs??aJ,Y=ZU($,Q),j=Date.now(),V=pJ.get(Y);if(V&&V.expiresAt>j)return V.data;let H=PZ.get(Y);if(H)return H;let B=o4(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,W6(F,{name:F})]));return pJ.set(Y,{data:K,expiresAt:j+X}),K}).finally(()=>{PZ.delete(Y)});return PZ.set(Y,B),B}async function WU($,Z){let Q=bZ(Z);if(!Q)return{};let W=sJ[$];if(!W)return{};return W(Z,Q)}function JU($,Z,Q){if(!Q)return!1;if(!sJ[$])return!1;if(Z?.loadPrivateOnAuth===!1)return!1;return Boolean(bZ(Q))}async function XU($,Z,Q){let W=Z?.cacheTtlMs??aJ,J=rf($,Q),X=Date.now(),Y=SZ.get(J);if(Y&&Y.expiresAt>X)return Y.data;let j=e4.get(J);if(j)return j;let V=WU($,Q).then((H)=>{return SZ.set(J,{data:H,expiresAt:X+W}),H}).finally(()=>{e4.delete(J)});return e4.set(J,V),V}async function YU($){return i.fetchLiveProviderModels($,globalThis.fetch)}async function J6($={}){let Z=$.url??nJ,Q=$.cacheTtlMs??vf,W=Date.now(),J=$6.get(Z);if(J&&J.expiresAt>W)return J.data;let X=Y8.get(Z);if(X)return X;let Y=YU(Z).then((j)=>{return $6.set(Z,{data:j,expiresAt:W+Q}),j}).finally(()=>{Y8.delete(Z)});return Y8.set(Z,Y),Y}function jU($){if($){$6.delete($),Y8.delete($);return}$6.clear(),Y8.clear()}function VU(){SZ.clear(),e4.clear()}function HU($){return Object.fromEntries(Object.entries($).map(([Z,Q])=>[Z,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:iJ(Q.capabilities)}]))}var yZ=HU(mf());function oJ($){let Z=gf($);if(!Z)return;return{baseUrl:Z.baseUrl||void 0,modelId:Z.modelId,knownModels:Z.knownModels,capabilities:iJ(Z.capabilities)}}async function hZ($,Z,Q){let W=oJ($);if(!W)return;try{let J=Z?.loadLatestOnInit?await J6(Z):void 0,X=J?lf($,J):{},Y=Q&&JU($,Z,Q)?await XU($,Z,Q):{},V=Boolean(i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:Q,H=V?await QU($,Z,V).catch(()=>({})):{},B=await df($,W.knownModels,X,Y,H,Q?.knownModels);return{...W,knownModels:B}}catch(J){if(Z?.failOnError)throw J;if($==="litellm")return{...W,knownModels:{}};return W}}var kZ=S0.BUILT_IN_PROVIDER,BU=S0.BUILT_IN_PROVIDER_IDS,GU=S0.isBuiltInProviderId,X6=S0.normalizeProviderId,IZ=R.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),tJ=R.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),eJ=R.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),$X=R.object({apiKey:R.string().optional(),accessToken:R.string().optional(),refreshToken:R.string().optional(),expiresAt:R.number().int().positive().optional(),accountId:R.string().optional()}),KU=R.enum(["none","low","medium","high","xhigh"]),ZX=R.object({enabled:R.boolean().optional(),effort:KU.optional(),budgetTokens:R.number().int().positive().optional()}),QX=R.object({accessKey:R.string().optional(),secretKey:R.string().optional(),sessionToken:R.string().optional(),region:R.string().optional(),profile:R.string().optional(),authentication:R.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:R.boolean().optional(),useCrossRegionInference:R.boolean().optional(),useGlobalInference:R.boolean().optional(),endpoint:R.string().url().optional(),customModelBaseId:R.string().optional()}),WX=R.object({projectId:R.string().optional(),region:R.string().optional()}),JX=R.object({apiVersion:R.string().optional(),useIdentity:R.boolean().optional()}),XX=R.object({clientId:R.string().optional(),clientSecret:R.string().optional(),tokenUrl:R.string().url().optional(),resourceGroup:R.string().optional(),deploymentId:R.string().optional(),useOrchestrationMode:R.boolean().optional(),api:R.enum(["orchestration","foundation-models"]).optional(),defaultSettings:R.record(R.string(),R.unknown()).optional()}),YX=R.object({mode:R.enum(["internal","external"]).optional(),usePromptCache:R.boolean().optional()}),jX=R.object({loadLatestOnInit:R.boolean().optional(),loadPrivateOnAuth:R.boolean().optional(),url:R.string().url().optional(),cacheTtlMs:R.number().int().positive().optional(),failOnError:R.boolean().optional()}),V2=R.object({provider:IZ,apiKey:R.string().optional(),auth:$X.optional(),model:R.string().optional(),protocol:tJ.optional(),client:eJ.optional(),routingProviderId:IZ.optional(),maxTokens:R.number().int().positive().optional(),contextWindow:R.number().int().positive().optional(),baseUrl:R.string().url().optional(),headers:R.record(R.string(),R.string()).optional(),timeout:R.number().int().positive().optional(),reasoning:ZX.optional(),aws:QX.optional(),gcp:WX.optional(),azure:JX.optional(),sap:XX.optional(),oca:YX.optional(),region:R.string().optional(),apiLine:R.enum(["china","international"]).optional(),capabilities:R.array(R.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:jX.optional()});function VX($){return V2.parse($)}function HX($){return V2.safeParse($)}function FU($){return $.protocol==="openai-responses"||$.client==="openai"}function B1($,Z={}){let Q=$.provider,W=X6(Q),J=Z.includeKnownModels!==!1,X=$.reasoning?.effort||"none",Y=X==="none"?void 0:X,j=yZ[W],V=Object.assign({},...S0.resolveProviderModelCatalogKeys(W).map((L)=>S0.getGeneratedModelsForProvider(L))),H=Object.keys(V)[0],B=s4(W,$),G=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?OZ:qZ:j?.baseUrl),K=$.routingProviderId??(FU($)&&W!==kZ.OPENAI_NATIVE?kZ.OPENAI_NATIVE:void 0),F=J?j?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Q,clientType:$.client,routingProviderId:K,modelId:$.model??j?.modelId??H??"default",...J?{knownModels:F}:{},apiKey:B,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:Y,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??j?.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(([L,f])=>f!==void 0))}function AU($){let Z=VX($);return B1(Z)}function fU($){let Z=HX($);if(Z.success)return{success:!0,config:B1(Z.data)};return{success:!1,error:Z.error}}import{SESSION_STATUS_VALUES as UU}from"@cline/shared";var xZ=UU,DU=["idle","running","pending"];function LU($){return!DU.includes($)}function j0($){return!LU($)}var z0={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"};function BX($){if($===!0)return{};if(!$)return;return $}function GX($){if($==="user")return"global";return $}class gZ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let Z=this.getService().ingestEvent($);return{event:Z.event,duplicate:Z.duplicate,matchedSpecIds:Z.matchedSpecs.map((Q)=>Q.specId),queuedRuns:Z.queuedRuns,suppressions:Z.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function KX($){let{host:Z}=$;return{async startSession(Q){let W=(Q.cwd?.trim()||Q.workspaceRoot).trim(),J=await Z.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:X6(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:W,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:TU(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Q,W){let J=await Z.runTurn({sessionId:Q,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((X)=>X.content),delivery:W.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:zU(J)}},async abortSession(Q){return await Z.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}function Y6($){let Z=_U($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,X=$.context?.telemetry??$.telemetry;if(!Z&&!Q&&!W&&!J&&!X)return $.context;return{...$.context??{},...Q?{client:Q}:{},...W?{user:W}:{},...J?{logger:J}:{},...X?{telemetry:X}:{},...Z?{automation:Z}:{}}}function _U($,Z){if(!$)return;return{ingestEvent:(Q)=>{Z.ingestEvent(Q)}}}function zU($){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((Z)=>({name:Z.name,input:Z.input,output:Z.output,error:Z.error,durationMs:Z.durationMs}))}}function TU($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as g8,readFileSync as LO}from"node:fs";import{basename as Y7,dirname as MV,extname as _O,isAbsolute as NV,join as zO,relative as wV,resolve as RV}from"node:path";import{createHash as OU}from"node:crypto";import{watch as qU}from"node:fs";import{readdir as MU,readFile as RU}from"node:fs/promises";import{join as EU}from"node:path";function NU($){return OU("sha1").update($).digest("hex")}function fX($){return Boolean($&&typeof $==="object"&&"code"in $)}function FX($){return fX($)&&$.code==="ENOENT"}function AX($){return fX($)&&($.code==="EACCES"||$.code==="EPERM")}class j8{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($,Z){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=Z?.debounceMs??75,this.emitParseErrors=Z?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let W of Q.directories){let J=this.baseTypesByDirectory.get(W);if(J)J.add(Q.type);else this.baseTypesByDirectory.set(W,new Set([Q.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 Z=this.definitionsByType.get($);if(!Z)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(Z)})}getSnapshot($){let Z=this.recordsByType.get($);return new Map([...Z?.entries()??[]].map(([Q,W])=>[Q,{...W}]))}getAllSnapshots(){let $=new Map;for(let[Z,Q]of this.recordsByType.entries())$.set(Z,new Map([...Q.entries()].map(([W,J])=>[W,{...J}])));return $}emit($){for(let Z of this.listeners)Z($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[Z,Q]of this.watchersByDirectory.entries()){if($.has(Z))continue;Q.close(),this.watchersByDirectory.delete(Z)}this.watchedTypesByDirectory=$;for(let Z of $.keys()){if(this.watchersByDirectory.has(Z))continue;try{let Q=qU(Z,()=>{let W=this.watchedTypesByDirectory.get(Z);if(!W)return;for(let J of W)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(Z,Q),Q.on("error",(W)=>{let J=this.watchedTypesByDirectory.get(Z);if(!J)return;for(let X of J)this.emit({kind:"error",type:X,error:W,filePath:Z})})}catch(Q){if(!FX(Q)&&!AX(Q)){let W=$.get(Z);if(!W)continue;for(let J of W)this.emit({kind:"error",type:J,error:Q,filePath:Z})}}}}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 Z of $){let Q=this.definitionsByType.get(Z);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Z,discoveredDirectories:Q}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[J,X]of W.entries()){if(Z.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:X.filePath})}for(let[J,X]of Z.entries()){let Y=W.get(J);if(Y&&Y.filePath===X.filePath&&Y.fingerprint===X.fingerprint)continue;this.emit({kind:"upsert",record:{type:X.type,id:J,item:X.item,filePath:X.filePath}})}if(this.recordsByType.set($.type,Z),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Z=new Map,Q=new Set;for(let W of $.directories){Q.add(W);let J=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let X of J){let{fileName:Y,filePath:j}=X;if(Q.add(X.directoryPath),$.includeFile&&!$.includeFile(Y,j))continue;try{let V=await RU(j,"utf8"),H={type:$.type,directoryPath:X.directoryPath,fileName:Y,filePath:j,content:V},B=$.parseFile(H),G=$.resolveId(B,H).trim();if(!G)continue;Z.set(G,{type:$.type,id:G,item:B,filePath:j,fingerprint:NU(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:j})}}}return{records:Z,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Z,Q]of this.baseTypesByDirectory.entries())$.set(Z,new Set(Q));for(let[Z,Q]of this.discoveredDirectoriesByType.entries())for(let W of Q){let J=$.get(W);if(J)J.add(Z);else $.set(W,new Set([Z]))}return $}async readDirectoryFileCandidates($){try{return(await MU($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:EU($,Q.name)})).sort((Q,W)=>Q.fileName.localeCompare(W.fileName))}catch(Z){if(FX(Z)||AX(Z))return[];throw Z}}}import{readdir as YQ,readFile as lD,stat as XQ}from"node:fs/promises";import{basename as K1,dirname as pD,extname as z6,join as E0,resolve as K8}from"node:path";import{AGENTS_RULES_FILE_NAME as lX,RULES_CONFIG_DIRECTORY_NAME as pX,resolveGlobalAgentsRulesPath as rD,resolveRulesConfigSearchPaths as iD,resolveSkillsConfigSearchPaths as nD,resolveWorkflowsConfigSearchPaths as aD,SKILLS_CONFIG_DIRECTORY_NAME as jQ,WORKFLOWS_CONFIG_DIRECTORY_NAME as VQ}from"@cline/shared/storage";import sD from"yaml";r0();import{existsSync as U6,readFileSync as SD,statSync as bD}from"node:fs";import{basename as yD,dirname as A6,join as D6,resolve as f6}from"node:path";import{discoverPluginModulePaths as hD,resolveConfiguredPluginModulePaths as mX,resolvePluginConfigSearchPaths as kD,SKILLS_CONFIG_DIRECTORY_NAME as ID}from"@cline/shared/storage";import{resolve as VD}from"node:path";import{normalizePluginManifest as HD}from"@cline/shared";import{existsSync as K0,readFileSync as G2}from"node:fs";import{builtinModules as dU,createRequire as rZ}from"node:module";import{dirname as I1,extname as H8,isAbsolute as lU,resolve as u}from"node:path";import{fileURLToPath as TX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as pU}from"@cline/shared";var OX=I1(TX(import.meta.url)),rU=rZ(import.meta.url),iU=u(OX,"..","..","..","..",".."),dZ=sU(iU),nU=["@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"],iZ=new Set(dU.flatMap(($)=>[$,$.replace(/^node:/,"")])),V8=new Set(pU),aU=["development","node","import","require","default"];function sU($){let Z={},Q={"@cline/sdk":u($,"packages/sdk/src/index.ts"),"@cline/agents":u($,"packages/agents/src/index.ts"),"@cline/core":u($,"packages/core/src/index.ts"),"@cline/llms":u($,"packages/llms/src/index.ts"),"@cline/shared":u($,"packages/shared/src/index.ts"),"@cline/shared/storage":u($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":u($,"packages/shared/src/db/index.ts")};for(let[W,J]of Object.entries(Q))if(K0(J))Z[W]=J;for(let W of["agents","core","llms","shared"]){let J=u($,"packages",W),X=u(J,"package.json");if(!K0(X))continue;try{let Y=JSON.parse(G2(X,"utf8"));if(typeof Y.name!=="string"||!Y.exports)continue;if(typeof Y.exports==="string"){let j=u(J,Y.exports);if(K0(j))Z[Y.name]=j;continue}if(typeof Y.exports!=="object")continue;for(let[j,V]of Object.entries(Y.exports)){let H=oU(J,V);if(!H)continue;let B=j==="."?Y.name:`${Y.name}/${j.replace(/^\.\//,"")}`;Z[B]=H}}catch{}}return Z}function oU($,Z){let Q=nZ(Z);if(!Q)return null;let W=qX($,Q);for(let J of W)if(K0(J))return J;return null}function nZ($,Z=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(Z.has($))return null;Z.add($);let Q=$;for(let W of aU){let J=nZ(Q[W],Z);if(J)return J}return null}function qX($,Z){let Q=Z.replace(/^\.\//,""),W=[u($,Z)];if(Q.startsWith("dist/")){let J=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[u($,`${J}.ts`),u($,`${J}.tsx`),u($,`${J}.mts`),u($,`${J}.cts`),...W]}return W}function tU($){return Object.fromEntries(Object.entries($).sort(([Z],[Q])=>Q.length-Z.length))}function G6($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function B2($){if($.startsWith("@")){let[Z,Q]=$.split("/",3);return Q?`${Z}/${Q}`:$}return $.split("/",1)[0]??$}function eU($){let Z=B2($);if($===Z)return".";return`.${$.slice(Z.length)}`}function MX($){return B2($).startsWith("@cline/")}function lZ($,Z){let Q=B2(Z),W=I1($);while(!0){let J=u(W,"node_modules",Q);if(K0(J)||K0(u(J,"package.json")))return!0;let X=u(W,"..");if(X===W)return!1;W=X}}function zX($){return pZ($)!==null}function pZ($){try{return rU.resolve($)}catch{}return $D($)}function $D($){let Z=B2($),Q=RX(Z);if(!Q)return null;let W=u(Q,"package.json");try{let J=JSON.parse(G2(W,"utf8")),X=eU($),Y=X==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,X)?J.exports[X]:void 0,j=nZ(Y)??(X==="."&&typeof J.main==="string"?J.main:null);if(!j)return null;let V=u(Q,j),H=[V,...qX(Q,j).filter((B)=>B!==V)];for(let B of H)if(K0(B))return B;return null}catch{return null}}function ZD(){let $=[OX],Z=process.env.CLINE_WRAPPER_PATH?.trim();if(Z)$.push(I1(I1(Z)));let Q=process.execPath?.trim();if(Q)$.push(I1(Q));return[...new Set($.map((W)=>u(W)))]}function QD($,Z){let Q=$;while(!0){let W=u(Q,"package.json");if(K0(W))try{if(JSON.parse(G2(W,"utf8")).name===Z)return Q}catch{}let J=u(Q,"node_modules",Z,"package.json");if(K0(J))return I1(J);let X=u(Q,"..");if(X===Q)return null;Q=X}}function RX($){for(let Z of ZD()){let Q=QD(Z,$);if(Q)return Q}return null}function WD($){let Q=I1($);for(let W=0;W<4;W++){let J=u(Q,"package.json");if(K0(J))try{let Y=JSON.parse(G2(J,"utf8"));return Y!=null&&typeof Y==="object"&&"cline"in Y}catch{return!1}let X=u(Q,"..");if(X===Q)return!1;Q=X}return!1}function EX($,Z){let Q=Z.startsWith("file:")?TX(Z):lU(Z)?Z:u(I1($),Z);if(K0(Q)&&V8.has(H8(Q)))return Q;for(let W of V8){let J=`${Q}${W}`;if(K0(J))return J}for(let W of V8){let J=u(Q,`index${W}`);if(K0(J))return J}return null}function NX($){let Z=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of Q)for(let J of $.matchAll(W)){let X=J[1];if(X)Z.add(X)}return[...Z]}function JD($){return H8($)!==".ts"}function wX($,Z,Q=new Set){if(Q.has($)||!K0($))return;if(Q.add($),!V8.has(H8($)))return;let W=G2($,"utf8"),J=JD($);for(let X of NX(W)){if(X.startsWith("node:")||iZ.has(X))continue;if(G6(X)){if(!J)continue;if(Object.hasOwn(dZ,X)||Object.hasOwn(dZ,B2(X))||lZ($,X)||MX(X)&&zX(X)||Z&&zX(X))continue;throw Error(`Cannot find module '${B2(X)}'`)}let Y=EX($,X);if(Y)wX(Y,Z,Q)}}function CX($,Z=new Set,Q=new Set){if(Z.has($)||!K0($))return Q;if(Z.add($),!V8.has(H8($)))return Q;let W=G2($,"utf8");for(let J of NX(W)){if(Q.add(J),G6(J))continue;let X=EX($,J);if(X)CX(X,Z,Q)}return Q}function XD($,Z){let Q=rZ($),W={},J=CX($),X=new Set(nU);for(let[Y,j]of Object.entries(dZ)){try{Q.resolve(Y);continue}catch{}W[Y]=j}for(let Y of J)if(G6(Y)&&(MX(Y)||Z))X.add(Y);for(let Y of X){if(Object.hasOwn(W,Y)||lZ($,Y))continue;let j=pZ(Y);if(j)W[Y]=j}if(!Z)return W;for(let Y of J){if(!G6(Y)||Object.hasOwn(W,Y)||lZ($,Y)||Y.startsWith("node:")||iZ.has(Y))continue;let j=pZ(Y);if(j)W[Y]=j}return W}function YD($){let Z=H8($);return Z===".ts"||Z===".tsx"||Z===".mts"||Z===".cts"}var L$;function jD(){if(L$!==void 0)return L$;let $=RX("jiti");if(!$)return L$=null,null;let Z=u($,"dist","babel.cjs");if(!K0(Z))return L$=null,null;try{let W=rZ(Z)(Z);L$=typeof W==="function"?W:null}catch{L$=null}return L$}async function PX($,Z={}){let Q=!WD($);wX($,Q);let W=XD($,Q),J=tU(W),X=await import("jiti"),Y=typeof X==="function"?X:typeof X.default==="function"?X.default:void 0;if(!Y)throw Error("Unable to load jiti");let j=Object.entries(J).filter(([,G])=>YD(G)).map(([G])=>G),V=jD(),H=V?(G)=>V({...G,interopDefault:!0}):void 0;return await Y($,{alias:J,cache:Z.useCache,requireCache:Z.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...iZ],transformModules:j,tryNative:!1,...H?{transform:H}:{}}).import($,{})}function SX($,Z){if(!$)return!0;if($.providerIds?.length){if(!Z?.providerId||!$.providerIds.includes(Z.providerId))return!1}if($.modelIds?.length){if(!Z?.modelId||!$.modelIds.includes(Z.modelId))return!1}return!0}function bX($){return typeof $==="object"&&$!==null}function aZ($){return Array.isArray($)&&$.every((Z)=>typeof Z==="string")}function BD($,Z){if(!bX($.manifest))throw Error(`Invalid plugin module at ${Z}: missing required "manifest"`);if(!aZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${Z}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${Z}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!aZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${Z}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!aZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${Z}: manifest.modelIds must be a string array when provided`)}function GD($,Z){if(!bX($))throw Error(`Invalid plugin module at ${Z}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${Z}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${Z}: missing required "manifest"`);BD($,Z)}async function sZ($,Z={}){let Q=VD(Z.cwd??process.cwd(),$),W=await PX(Q,{useCache:Z.useCache}),J=Z.exportName??"plugin",X=W.default??W[J];GD(X,Q);let Y=X,j=Y.setup,V=j?(H,B)=>{let G={...Z.session,...B.session},K={...B,session:Object.keys(G).length>0?G:void 0,client:Z.client??B.client,user:Z.user??B.user,workspaceInfo:Z.workspaceInfo??B.workspaceInfo,automation:Z.automation??B.automation,logger:Z.logger??B.logger,telemetry:Z.telemetry??B.telemetry};return j(H,K)}:void 0;return{...Y,manifest:HD(Y.manifest),setup:V}}async function yX($,Z={}){return(await B8($,Z)).plugins}async function B8($,Z={}){let Q=[],W=[],J=new Map,X=0;for(let j of $)try{let V=await sZ(j,Z);if(!SX(V.manifest,Z))continue;let H=J.get(V.name);if(H)W.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:j,overriddenPluginPath:H.pluginPath,message:`Plugin "${V.name}" from ${j} overrides ${H.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:j,order:X++})}catch(V){let H=V instanceof Error?V.message:String(V);Q.push({pluginPath:j,phase:"load",message:H,stack:V instanceof Error?V.stack:void 0})}let Y=[...J.values()].sort((j,V)=>j.order-V.order);return{plugins:Y.map((j)=>j.plugin),pluginPaths:Y.map((j)=>j.pluginPath),failures:Q,warnings:W}}import{existsSync as eZ}from"node:fs";import{createRequire as gX}from"node:module";import{dirname as F6,join as K2}from"node:path";import{fileURLToPath as LD}from"node:url";import{spawn as KD}from"node:child_process";import{basename as FD}from"node:path";import{augmentNodeCommandForDebug as AD,withResolvedClineBuildEnv as fD}from"@cline/shared";function hX($){if($ instanceof Error)return $;return Error(String($))}var UD="CLINE_JS_RUNTIME_PATH";function kX($){let Z=$?.trim();if(!Z)return!1;let Q=FD(Z).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function IX($={}){let Z=$.env??process.env,Q=$.runtimeExecutable?.trim()||Z[UD]?.trim();if(Q)return Q;let W=$.execPath?.trim()||process.execPath;if(kX(W))return W;for(let J of[Z.BUN_EXEC_PATH,Z.npm_node_execpath,Z.NODE]){let X=J?.trim();if(X&&kX(X))return X}return"node"}function DD($,Z={}){let Q=IX({env:Z.env,execPath:Z.execPath,runtimeExecutable:Z.runtimeExecutable});return AD([Q,...$],{env:Z.env,execArgv:Z.execArgv,debugRole:Z.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class K6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let Z=this.pending.get($);if(!Z)return;if(this.pending.delete($),Z.timeout)clearTimeout(Z.timeout);return Z}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],Z=DD($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=KD(Z[0]??IX(this.options),Z.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:fD(process.env),windowsHide:!0});this.process=Q;let W="",J=(X)=>{let Y=W+X;W=Y.length>4000?Y.slice(-4000):Y};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(X)=>{J(X)}),Q.on("message",(X)=>{this.onMessage(X)}),Q.on("error",(X)=>{this.failPending(Error(`${this.processLabel} process error: ${hX(X).message}`))}),Q.on("exit",(X,Y)=>{this.process=null;let j=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(X)}, signal=${String(Y)})${j?`: ${j}`:""}`))})}async call($,Z,Q={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,X={type:"call",id:J,method:$,args:Z};return await new Promise((Y,j)=>{let V={resolve:(H)=>Y(H),reject:j};if((Q.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(J,V),W.send(X,(H)=>{if(!H)return;let B=this.clearPendingRequest(J);if(!B)return;B.reject(Error(`${this.processLabel} failed to send call "${$}": ${hX(H).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((Z)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Z()},300);$.once("exit",()=>{clearTimeout(Q),Z()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),Z()}}),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 Z=this.clearPendingRequest($.id);if(!Z)return;if($.ok){Z.resolve($.result);return}Z.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[Z,Q]of this.pending.entries()){if(this.pending.delete(Z),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function _D($){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 G8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function zD(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function TD(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=gX($).resolve(`${zD()}/package.json`),W=K2(F6(Q),"extensions","plugin-sandbox-bootstrap.js");return eZ(W)?W:void 0}catch{return}}function OD(){let $=process.execPath?.trim();if(!$)return;let Z=K2(F6(F6($)),"extensions","plugin-sandbox-bootstrap.js");return eZ(Z)?Z:void 0}function qD(){let $=F6(LD(import.meta.url)),Z=gX(import.meta.url),Q=[K2($,"plugin-sandbox-bootstrap.js"),K2($,"extensions","plugin-sandbox-bootstrap.js"),K2($,"agents","plugin-sandbox-bootstrap.js"),TD(),OD()];for(let X of Q.filter((Y)=>typeof Y==="string"))if(eZ(X))return{file:X};let W=K2($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=Z.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
46
- `)}}var oZ=qD();function tZ($,Z,Q){if(typeof $==="number"&&$>0)return $;if(Q){let W=process.env[Q];if(W){let J=Number(W);if(Number.isInteger(J)&&J>0)return J}}return Z}async function F2($){let Z=new K6({name:"plugin-sandbox",..."file"in oZ?{bootstrapFile:oZ.file}:{bootstrapScript:oZ.script},onEvent:$.onEvent}),Q=tZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=tZ($.hookTimeoutMs,3000),J=tZ($.contributionTimeoutMs,60000),X={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},Y,j=()=>{return Y??=Z.call("initialize",X,{timeoutMs:Q}).finally(()=>{Y=void 0}),Y},V;try{V=await Z.call("initialize",X,{timeoutMs:Q})}catch(G){throw await Z.shutdown().catch(()=>{}),G}let H=V.plugins.map(_D);return{extensions:H.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{MD(F,Z,G,J,j),RD(F,Z,G,J,j),ED(F,Z,G,J,j),wD(F,Z,G,J,j),ND(F,G)}};return K.hooks=PD(Z,G,W,j),K}),failures:V.failures,pluginPaths:H.map((G)=>G.pluginPath),shutdown:async()=>{await Z.shutdown()},warnings:V.warnings}}function MD($,Z,Q,W,J){for(let X of Q.contributions?.tools??[]){let Y={name:X.name,description:X.description??"",inputSchema:X.inputSchema??{type:"object",properties:{}},timeoutMs:X.timeoutMs,retryable:X.retryable,execute:async(j,V)=>{try{return await Z.call("executeTool",{pluginId:Q.pluginId,contributionId:X.id,input:j,context:V},{timeoutMs:W})}catch(H){if(!G8(H))throw H;return await J(),await Z.call("executeTool",{pluginId:Q.pluginId,contributionId:X.id,input:j,context:V},{timeoutMs:W})}}};$.registerTool(Y)}}function RD($,Z,Q,W,J){for(let X of Q.contributions?.commands??[])$.registerCommand({name:X.name,description:X.description,handler:async(Y)=>{try{return await Z.call("executeCommand",{pluginId:Q.pluginId,contributionId:X.id,input:Y},{timeoutMs:W})}catch(j){if(!G8(j))throw j;return await J(),await Z.call("executeCommand",{pluginId:Q.pluginId,contributionId:X.id,input:Y},{timeoutMs:W})}}})}function ED($,Z,Q,W,J){for(let X of Q.contributions?.rules??[])$.registerRule({id:X.ruleId,source:X.source,content:X.hasContentHandler===!0?async()=>{try{return await Z.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:X.id},{timeoutMs:W})}catch(Y){if(!G8(Y))throw Y;return await J(),await Z.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:X.id},{timeoutMs:W})}}:X.content??""})}function ND($,Z){for(let Q of Z.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of Z.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of Z.contributions?.mcpServers??[])$.registerMcpServer(Q)}function wD($,Z,Q,W,J){for(let X of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:X.name,async build(Y){try{let j=await Z.call("buildMessages",{pluginId:Q.pluginId,contributionId:X.id,messages:Y},{timeoutMs:W});return xX(j)?j:Y}catch(j){if(!G8(j))throw j;await J();let V=await Z.call("buildMessages",{pluginId:Q.pluginId,contributionId:X.id,messages:Y},{timeoutMs:W});return xX(V)?V:Y}}})}function xX($){return Array.isArray($)&&$.every((Z)=>typeof Z==="object"&&Z!==null&&("role"in Z)&&("content"in Z))}function CD($,Z,Q,W,J){return async(X)=>{try{return await $.call("invokeHook",{pluginId:Z,hookName:Q,payload:X},{timeoutMs:W})}catch(Y){if(!G8(Y))throw Y;return await J(),await $.call("invokeHook",{pluginId:Z,hookName:Q,payload:X},{timeoutMs:W})}}}function PD($,Z,Q,W){let J={};for(let X of Z.hooks??[])J[X]=CD($,Z.pluginId,X,Q,W);return Object.keys(J).length>0?J:void 0}var ZQ="package.json",xD="package";function QQ($){return kD($)}function WQ($){return hD($)}function gD($){try{return U6($)&&bD($).isDirectory()}catch{return!1}}function JQ($){let Z=[],Q=new Set;for(let W of $){let J=f6(W);if(Q.has(J))continue;Q.add(J),Z.push(J)}return Z}function vX($){let Z=JQ($);return cZ(Z)}function cX($){return QQ($).flatMap((Z)=>WQ(Z)).filter((Z)=>U6(Z))}function mD($,Z){let Q=[];for(let W of $)try{Q.push(...mX([W],Z))}catch{}return Q}function $Q($){return typeof $==="object"&&$!==null}function vD($){try{let Z=JSON.parse(SD(D6($,ZQ),"utf8"));if(!$Q(Z)||!$Q(Z.cline))return[];let Q=Z.cline.plugins;if(!Array.isArray(Q))return[];let W=[];for(let J of Q){if(typeof J==="string"){W.push(J);continue}if(!$Q(J)||!Array.isArray(J.paths))continue;for(let X of J.paths)if(typeof X==="string")W.push(X)}return W}catch{return[]}}function uX($,Z){let Q=f6(Z);return vD($).some((W)=>f6($,W)===Q)}function cD($,Z){return yD($)===xD&&U6(D6(A6($),ZQ))&&uX(A6($),Z)}function uD($){let Z=f6($),Q=[],W=A6(Z);while(!0){if(cD(W,Z)){Q.push(W);break}if(U6(D6(W,ZQ))){if(uX(W,Z))Q.push(W);break}let J=A6(W);if(J===W)break;W=J}return JQ(Q)}function _$($={}){let Z=$.cwd??process.cwd(),Q=cX($.workspacePath),W=mX($.pluginPaths??[],Z);return vX([...W,...Q])}function dD($={}){let Z=$.cwd??process.cwd(),Q=cX($.workspacePath),W=mD($.pluginPaths??[],Z);return vX([...W,...Q])}function z$($){let Z=[];for(let Q of $)for(let W of uD(Q)){let J=D6(W,ID);if(gD(J))Z.push(J)}return JQ(Z)}function dX($={}){return z$(dD($))}async function L6($={}){let Z=_$($);if(Z.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await B8(Z,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:W.plugins,failures:W.failures,pluginPaths:W.pluginPaths,warnings:W.warnings}}let Q=await F2({pluginPaths:Z,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:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}var _6="SKILL.md",oD="managed.json",tD=new Set([".md",".markdown",".txt"]);function HQ($){return $.trim().toLowerCase()}function A2($){let Z=$;return Z?.code==="ENOENT"||Z?.code==="EACCES"||Z?.code==="EPERM"||Z?.code==="ELOOP"}function T6($){return tD.has(z6($).toLowerCase())}function rX($){let Z=[],Q=new Set;for(let W of $){let J=K8(W);if(Q.has(J))continue;Q.add(J),Z.push(W)}return Z}function eD($){let Z=[...$?.directories??fQ($?.workspacePath)];if($?.pluginSkillDirectories)Z.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)Z.push(...dX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return rX(Z)}async function BQ($){try{let Z=await YQ($,{withFileTypes:!0}),Q=[];for(let W of Z){if(!W.isDirectory())continue;let J=E0($,W.name),X=E0(J,oD);try{let Y=await lD(X,"utf8"),j=JSON.parse(Y);if(j&&typeof j==="object")Q.push(J)}catch(Y){if(A2(Y))continue;if(Y?.name==="SyntaxError")continue;throw Y}}return Q.sort((W,J)=>W.localeCompare(J))}catch(Z){if(A2(Z))return[];throw Z}}function GQ($){let Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(Z);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,W,J]=Q;try{let X=sD.parse(W);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:$,hadFrontmatter:!0,parseError:Y}}}function O6($,Z,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${Z}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${Z}' must be a string.`);let W=$.trim();if(!W&&Q)throw Error(`Frontmatter field '${Z}' cannot be empty.`);return W||void 0}function f2($,Z){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${Z}' must be a boolean.`);return $}function $L($,Z){if(K1($.filePath).toLowerCase()!==lX.toLowerCase())return K1($.filePath,z6($.filePath));if(Z&&K8($.filePath)===K8(Z,lX))return"Workspace AGENTS.md";if(K8($.filePath)===K8(rD()))return"Global AGENTS.md";return K1($.filePath,z6($.filePath))}function KQ($,Z){let{data:Q,body:W,parseError:J}=GQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in skill file.");let j=O6(Q.name,"name",!1)??Z.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:O6(Q.description,"description",!1),disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function FQ($,Z){let{data:Q,body:W,parseError:J}=GQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in rule file.");let Y=O6(Q.name,"name",!1)??Z.trim();if(!Y)throw Error("Missing rule name.");return{name:Y,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function AQ($,Z){let{data:Q,body:W,parseError:J}=GQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in workflow file.");let Y=O6(Q.name,"name",!1)??Z.trim();if(!Y)throw Error("Missing workflow name.");return{name:Y,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function fQ($){return nD($)}function UQ($){return iD($)}function DQ($){return aD($)}async function iX($){if(K1($)===".cline"){let Z=await BQ($);return(await Promise.all(Z.map((W)=>iX(E0(W,jQ))))).flat()}try{let Z=await YQ($,{withFileTypes:!0}),Q=[];for(let W of Z){if(W.isFile()&&W.name===_6){Q.push({directoryPath:$,fileName:W.name,filePath:E0($,W.name)});continue}let J=E0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await XQ(J).then((Y)=>Y.isDirectory()).catch((Y)=>{if(A2(Y))return!1;throw Y}))Q.push({directoryPath:J,fileName:_6,filePath:E0(J,_6)})}return Q}catch(Z){if(A2(Z))return[];throw Z}}async function q6($){if(K1($)===".cline"){let Z=await BQ($);return(await Promise.all(Z.map((W)=>q6(E0(W,"rules.md"))))).flat()}try{if((await XQ($)).isFile())return[{directoryPath:pD($),fileName:K1($),filePath:$}]}catch(Z){if(!A2(Z))throw Z}try{let Q=(await YQ($,{withFileTypes:!0})).filter((J)=>J.isFile()&&T6(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:E0($,J.name)})),W=E0($,"AGENTS.md");try{if((await XQ(W)).isFile()){if(!Q.some((Y)=>Y.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return Q}catch(Z){if(A2(Z))return[];throw Z}}async function ZL($){if(K1($)===".cline"){let Z=await BQ($);return(await Promise.all(Z.map((W)=>q6(E0(W,VQ))))).flat()}return q6($)}function LQ($){let Z=eD($),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?rX([...Z,Q]):Z,discoverFiles:iX,includeFile:(W)=>W===_6,parseFile:(W)=>KQ(W.content,K1(W.directoryPath)),resolveId:(W)=>HQ(W.name)}}function _Q($){let Z=$?.directories??UQ($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...Z,Q]:Z,discoverFiles:q6,includeFile:(W,J)=>W===".clinerules"||T6(W)||T6(J),parseFile:(W)=>FQ(W.content,$L(W,$?.workspacePath)),resolveId:(W)=>HQ(W.name)}}function zQ($){let Z=$?.directories??DQ($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...Z,Q]:Z,discoverFiles:ZL,includeFile:(W)=>T6(W),parseFile:(W)=>AQ(W.content,K1(W.filePath,z6(W.filePath))),resolveId:(W)=>HQ(W.name)}}function nX($){let Z=[LQ($?.skills),_Q($?.rules),zQ($?.workflows)];return new j8(Z,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as aX}from"@cline/shared";function QL($,Z){if($.description?.trim())return aX($.description,".");if(Z==="workflow")return;return aX($.instructions,".")}function WL($){return $.disabled!==!0}function sX($,Z){return[...$.getSnapshot(Z).entries()].map(([Q,W])=>({id:Q,record:W})).filter(({record:Q})=>WL(Q.item)).map(({id:Q,record:W})=>({id:Q,name:W.item.name,instructions:W.item.instructions,description:QL(W.item,Z),kind:Z})).sort((Q,W)=>Q.name.localeCompare(W.name))}function F8($){let Z=new Map;for(let Q of[...sX($,"workflow"),...sX($,"skill")])if(!Z.has(Q.name))Z.set(Q.name,Q);return[...Z.values()].sort((Q,W)=>Q.name.localeCompare(W.name))}function oX($,Z){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let W=Q[1];if(!W)return $;let J=W.length+1,X=$.slice(J),Y=F8(Z).find((j)=>j.name===W);return Y?`${Y.instructions}${X}`:$}function tX($){return $.disabled!==!0}function M6($){if($.length===0)return"";return`
45
+ </html>`;function OJ($){let Z="";for(let Q=0;Q<$.length;Q+=1)Z+=String.fromCharCode($[Q]??0);return btoa(Z).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function cA($){let Q=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(W)}function uA($=32){let Z=new Uint8Array($);return crypto.getRandomValues(Z),OJ(Z)}async function l4(){let $=uA(),Z=OJ(await cA($));return{verifier:$,challenge:Z}}function p4($){return $.endsWith("/")?$.slice(0,-1):$}function U$($,Z){return new URL(Z,`${p4($)}/`).toString()}function J2($,Z={}){let Q=$.trim();if(!Q)return{};try{let W=new URL(Q);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:Z.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(Z.allowHashCodeState&&Q.includes("#")){let[W,J]=Q.split("#",2);return{code:W||void 0,state:J||void 0}}if(Q.includes("code=")){let W=new URLSearchParams(Q);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:Z.includeProvider?W.get("provider")??void 0:void 0}}return{code:Q}}function dA($){if(typeof atob==="function")try{return atob($)}catch{return null}if(typeof Buffer<"u")try{return Buffer.from($,"base64").toString("utf8")}catch{return null}return null}function z0($){if(!$)return null;try{let Z=$.split(".");if(Z.length!==3)return null;let Q=Z[1];if(!Q)return null;let W=Q.replace(/-/g,"+").replace(/_/g,"/"),J=W.padEnd(W.length+(4-W.length%4)%4,"="),X=dA(J);if(!X)return null;return JSON.parse(X)}catch{return null}}function X2($){try{let Z=JSON.parse($),Q=Z.error,W=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,J=typeof Z.error_description==="string"?Z.error_description:typeof Z.message==="string"?Z.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:W,message:J}}catch{return{}}}function Y2($,Z){return Date.now()>=$.expires-Z}async function j2($){if(!$.onManualCodeInput){let X=await $.waitForCallback();return{code:X?.code,state:X?.state,provider:X?.provider,error:X?.error}}let Z,Q,W=$.onManualCodeInput().then((X)=>{Z=X,$.cancelWait()}).catch((X)=>{Q=X instanceof Error?X:Error(String(X)),$.cancelWait()}),J=await $.waitForCallback();if(Q)throw Q;if(J?.code||J?.error)return{code:J.code,state:J.state,provider:J.provider,error:J.error};if(Z)return J2(Z,$.parseOptions);if(await W,Q)throw Q;if(Z)return J2(Z,$.parseOptions);return{}}var r4={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},EJ={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},FZ="https://api.workos.com",lA="/auth",qJ=Array.from({length:11},($,Z)=>48801+Z),pA=300000,rA=30000,V2=30000,iA=300,nA=5;class y1 extends Error{status;errorCode;constructor($,Z){super($);this.name="ClineOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 aA($){let Z=Date.parse($);if(Number.isNaN(Z))throw Error(`Invalid expiresAt value: ${$}`);return Z}function AZ($,Z,Q={}){let W=$.userInfo.clineUserId??Q.accountId,J=$.refreshToken??Q.refresh;if(!J)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:J,expires:aA($.expiresAt),accountId:W??void 0,email:$.userInfo.email||Q.email,metadata:{provider:Z,tokenType:$.tokenType,userInfo:$.userInfo}}}async function fZ($){if(!$)return{};return typeof $==="function"?await $():$}function MJ($,Z){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return Z;return Math.floor($)}async function RJ($){await new Promise((Z)=>setTimeout(Z,$))}function UZ($,Z){if(!$.success||!$.data?.accessToken)throw Error(Z);return $.data}async function NJ($,Z){let Q=await fetch(U$(FZ,EJ.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(Z?.requestTimeoutMs??V2)}),W=await Q.json().catch(()=>({}));if(!Q.ok)throw new y1(`Device authorization failed: ${Q.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Q.status,errorCode:W.error});if(!W.device_code||!W.user_code||!W.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:W.device_code,userCode:W.user_code,verificationUri:W.verification_uri,verificationUriComplete:W.verification_uri_complete,expiresInSeconds:MJ(W.expires_in,iA),pollIntervalSeconds:MJ(W.interval,nA)}}async function wJ($){let Z=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=Z){let W=await fetch(U$($.workosApiBaseUrl,EJ.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 W.json().catch(()=>({}));if(W.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 RJ(Q*1000);break}case"slow_down":{Q+=1,await RJ(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new y1(J.error_description||"WorkOS authorization failed",{status:W.status,errorCode:J.error});default:throw new y1(`WorkOS token polling failed: ${W.status}${J.error_description?` - ${J.error_description}`:""}`,{status:W.status,errorCode:J.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function CJ($,Z,Q){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},J=await fetch(U$(Z.apiBaseUrl,r4.register),{method:"POST",headers:{"Content-Type":"application/json",...await fZ(Z.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Z.requestTimeoutMs??V2)});if(!J.ok){let Y=await J.text().catch(()=>""),j=X2(Y);throw new y1(`Token registration failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let X=await J.json();return AZ(UZ(X,"Invalid token exchange response"),Q??Z.provider)}async function sA($,Z,Q,W){let J={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:Z,provider:W??Q.provider},X=await fetch(U$(Q.apiBaseUrl,r4.token),{method:"POST",headers:{"Content-Type":"application/json",...await fZ(Q.headers)},body:JSON.stringify(J),signal:AbortSignal.timeout(Q.requestTimeoutMs??V2)});if(!X.ok){let j=await X.text().catch(()=>""),V=X2(j);throw new y1(`Token exchange failed: ${X.status}${V.message?` - ${V.message}`:""}`,{status:X.status,errorCode:V.code})}let Y=await X.json();return AZ(UZ(Y,"Invalid token exchange response"),W??Q.provider)}async function DZ($){C1($.telemetry,$.provider??"cline");let Z=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:qJ,W=$.callbackPath??lA,J=Z?null:await H1({ports:Q,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=J?.callbackUrl||`http://127.0.0.1:${Q[0]??qJ[0]}${W}`;try{let Y;if(Z){let j=KZ().workOsClientId,V=await NJ(j,$);$.callbacks.onAuth({url:V.verificationUriComplete??V.verificationUri,instructions:`Enter this code in your browser: ${V.userCode}`});let H=await wJ({clientId:j,deviceCode:V.deviceCode,expiresInSeconds:V.expiresInSeconds,initialPollIntervalSeconds:V.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??V2,workosApiBaseUrl:FZ,onProgress:$.callbacks.onProgress});Y=await CJ(H,$,$.provider)}else{let j=new URL(U$($.apiBaseUrl,r4.authorize));j.searchParams.set("client_type","extension"),j.searchParams.set("callback_url",X),j.searchParams.set("redirect_uri",X),$.callbacks.onAuth({url:j.toString(),instructions:"Continue the authentication process in your browser."});let V,H=$.provider,B=await j2({waitForCallback:J?.waitForCallback??(async()=>null),cancelWait:J?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(B.error)throw Error(`OAuth error: ${B.error}`);if(V=B.code,H=B.provider??H,!V){let G=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),K=J2(G,{includeProvider:!0});V=K.code,H=K.provider??H}if(!V)throw Error("Missing authorization code");Y=await sA(V,X,$,H)}return P1($.telemetry,$.provider??"cline"),b1($.telemetry,{id:Y.accountId,email:Y.email,provider:$.provider??"cline"}),Y}catch(Y){throw S1($.telemetry,$.provider??"cline",Y instanceof Error?Y.message:String(Y)),Y}finally{J?.close()}}async function oA($){return await NJ(KZ().workOsClientId,$)}async function tA($){let Z=$.provider??"cline";C1($.telemetry,Z);try{let Q=await wJ({clientId:KZ().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??V2,workosApiBaseUrl:FZ}),W=await CJ(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return P1($.telemetry,Z),b1($.telemetry,{id:W.accountId,email:W.email,provider:Z}),W}catch(Q){throw S1($.telemetry,Z,Q instanceof Error?Q.message:String(Q)),Q}}async function PJ($,Z){let Q=await fetch(U$(Z.apiBaseUrl,r4.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await fZ(Z.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(Z.requestTimeoutMs??V2)});if(!Q.ok){let X=await Q.text().catch(()=>""),Y=X2(X);throw new y1(`Token refresh failed: ${Q.status}${Y.message?` - ${Y.message}`:""}`,{status:Q.status,errorCode:Y.code})}let W=await Q.json(),J=$.metadata?.provider??Z.provider;return AZ(UZ(W,"Invalid token refresh response"),J,$)}async function LZ($,Z,Q){if(!$)return null;let W=Q?.refreshBufferMs??pA,J=Q?.retryableTokenGraceMs??rA;if(Q?.forceRefresh!==!0&&!Y2($,W))return $;try{return await PJ($,Z)}catch(Y){if(Y instanceof y1&&Y.isLikelyInvalidGrant())return A$(Z.telemetry,Z.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}G0();import{nanoid as eA}from"nanoid";var W0={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 i4 extends Error{status;errorCode;constructor($,Z){super($);this.name="OpenAICodexOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 $f($,Z,Q=W0.redirectUri){let W=await fetch(W0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:W0.clientId,code:$,code_verifier:Z,redirect_uri:Q}),signal:AbortSignal.timeout(W0.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let J=await W.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 Zf($){try{let Z=await fetch(W0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:W0.clientId}),signal:AbortSignal.timeout(W0.httpTimeoutMs)});if(!Z.ok){let W=await Z.text().catch(()=>""),J=X2(W);throw new i4(`Token refresh failed: ${Z.status}${J.message?` - ${J.message}`:""}`,{status:Z.status,errorCode:J.code})}let Q=await Z.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(Z){if(Z instanceof i4)throw Z;return{type:"failed"}}}async function Qf($="pi"){let{verifier:Z,challenge:Q}=await l4(),W=eA(32),J=new URL(W0.authorizationEndpoint);return J.searchParams.set("response_type","code"),J.searchParams.set("client_id",W0.clientId),J.searchParams.set("redirect_uri",W0.redirectUri),J.searchParams.set("scope",W0.scopes),J.searchParams.set("code_challenge",Q),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("state",W),J.searchParams.set("id_token_add_organizations","true"),J.searchParams.set("codex_cli_simplified_flow","true"),J.searchParams.set("originator",$),{verifier:Z,state:W,url:J.toString()}}function Wf(){try{let $=new URL(W0.redirectUri),Z=$.port.length>0?Number.parseInt($.port,10):W0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(Z)?Z:W0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:W0.callbackPort,callbackPath:"/auth/callback",redirectUri:W0.redirectUri}}}function Jf($,Z){let Q=Z?z0(Z):z0($),W=Q?Q:z0($),X=W?.[W0.jwtClaimPath]?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;let Y=W?.organizations;if(Array.isArray(Y)&&Y.length>0){let V=Y[0];if(typeof V?.id==="string"&&V.id.length>0)return V.id}let j=W?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return null}function SJ($,Z){let Q=Jf($.access,$.idToken)??Z?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||Z?.refresh||"",expires:$.expires,accountId:Q,email:$.email??Z?.email,metadata:{...Z?.metadata??{},provider:"openai-codex"}}}async function _Z($){C1($.telemetry,"openai-codex");let Z=Wf(),{verifier:Q,state:W,url:J}=await Qf($.originator),X=await H1({host:Z.host,ports:[Z.port],callbackPath:Z.callbackPath,expectedState:W});$.onAuth({url:J,instructions:"Continue the authentication process in your browser."});let Y;try{let j=await j2({waitForCallback:X.waitForCallback,cancelWait:X.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(j.state&&j.state!==W)throw Error("State mismatch");if(Y=j.code,!Y){let B=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),G=J2(B,{allowHashCodeState:!0});if(G.state&&G.state!==W)throw Error("State mismatch");Y=G.code}if(!Y)throw Error("Missing authorization code");let V=await $f(Y,Q,Z.redirectUri);if(V.type!=="success")throw Error("Token exchange failed");let H=SJ(V);return P1($.telemetry,"openai-codex"),b1($.telemetry,{id:H.accountId,email:H.email,provider:"openai-codex"}),H}catch(j){throw S1($.telemetry,"openai-codex",j instanceof Error?j.message:String(j)),j}finally{X.close()}}async function bJ($,Z){let Q=await Zf($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=SJ(Q,Z);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function zZ($,Z){if(!$)return null;let Q=Z?.refreshBufferMs??W0.refreshBufferMs,W=Z?.retryableTokenGraceMs??W0.retryableTokenGraceMs;if(Z?.forceRefresh!==!0&&!Y2($,Q))return $;try{return await bJ($.refresh,$)}catch(X){if(X instanceof i4&&X.isLikelyInvalidGrant())return A$(Z?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}G0();import{nanoid as yJ}from"nanoid";class TZ{ttlMs;maxEntries;entries=new Map;constructor($,Z){this.ttlMs=$;this.maxEntries=Z}get($,Z=Date.now()){this.pruneExpired(Z);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,Z,Q=Date.now(),W=this.ttlMs){this.pruneExpired(Q),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:Z,expiresAt:Q+W})}pruneExpired($){for(let[Z,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(Z)}}var Xf="a8331954c0cf48ba99b5dd223a14c6ea",Yf="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",jf="openid offline_access",qZ="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Vf="c1aba3deed5740659981a752714eba33",Hf="https://login-ext.identity.oraclecloud.com",Bf="openid offline_access",MZ="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm";var Gf="/auth/oca",Kf=Array.from({length:11},($,Z)=>48801+Z),Ff=300000,Af=30000,hJ=30000,ff=600000;class n4 extends Error{status;errorCode;constructor($,Z){super($);this.name="OcaOAuthTokenError",this.status=Z?.status,this.errorCode=Z?.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 h1={internal:{clientId:Xf,idcsUrl:Yf,scopes:jf,baseUrl:qZ},external:{clientId:Vf,idcsUrl:Hf,scopes:Bf,baseUrl:MZ}},W8=new Map,Uf=86400000,Df=300000,Lf=32,OZ=new TZ(Uf,Lf);function kJ($){if(typeof $==="function")return $();return $??"internal"}function IJ($){return{internal:{clientId:$?.internal?.clientId??h1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??h1.internal.idcsUrl,scopes:$?.internal?.scopes??h1.internal.scopes,baseUrl:$?.internal?.baseUrl??h1.internal.baseUrl},external:{clientId:$?.external?.clientId??h1.external.clientId,idcsUrl:$?.external?.idcsUrl??h1.external.idcsUrl,scopes:$?.external?.scopes??h1.external.scopes,baseUrl:$?.external?.baseUrl??h1.external.baseUrl}}}function _f($=Date.now()){let Z=$-ff;for(let[Q,W]of W8.entries())if(W.createdAt<Z)W8.delete(Q)}function zf($,Z,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let J=z0(Z)?.exp;if(typeof J==="number"&&J>0)return J*1000;let Y=z0(Q)?.exp;if(typeof Y==="number"&&Y>0)return Y*1000;return Date.now()+3600000}function xJ($,Z,Q){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let J=$.refresh_token??Q?.refresh;if(!J)throw Error("Token response did not include a refresh token");let X=z0($.id_token),Y=z0(W),j=X?.sub??Y?.sub,V=X?.email??Y?.email;return{access:W,refresh:J,expires:zf($,W,$.id_token),accountId:j??Q?.accountId,email:V??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:Z,subject:j,idToken:$.id_token}}}async function gJ($,Z){let Q=p4($),W=OZ.get(Q);if(W)return W;let J=`${Q}/.well-known/openid-configuration`,X=await fetch(J,{method:"GET",signal:AbortSignal.timeout(Z)});if(!X.ok){let V=`${Q}/oauth2/v1/token`;return OZ.set(Q,V,Date.now(),Df),V}let j=(await X.json()).token_endpoint||`${Q}/oauth2/v1/token`;return OZ.set(Q,j),j}function mJ($){return{code:$.error,message:$.error_description}}async function Tf($){let Z=W8.get($.state);if(!Z)throw Error("No PKCE verifier found for this state");W8.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,W=await gJ(Q.idcsUrl,$.requestTimeoutMs),J=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:Z.redirectUri,client_id:Q.clientId,code_verifier:Z.verifier}),X=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:J,signal:AbortSignal.timeout($.requestTimeoutMs)}),Y=await X.json();if(!X.ok){let V=mJ(Y);throw new n4(`Token exchange failed: ${X.status}${V.message?` - ${V.message}`:""}`,{status:X.status,errorCode:V.code})}let j=z0(Y.id_token);if(!Y.id_token||!j)throw Error("No ID token received from OCA");if(j.nonce!==Z.nonce)throw Error("OIDC nonce verification failed");return xJ(Y,$.mode)}function Of($){let Z=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${p4(Z.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",Z.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",Z.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function RZ($){C1($.telemetry,"oca");let Z=IJ($.config),Q=kJ($.mode),W=$.callbackPorts?.length?$.callbackPorts:Kf,J=$.callbackPath??Gf,X=$.requestTimeoutMs??hJ,Y=await H1({ports:W,callbackPath:J,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=Y.callbackUrl;if(!j)throw Error("Unable to bind local OAuth callback server");let V=yJ(16),H=yJ(16),{verifier:B,challenge:G}=await l4();_f(),W8.set(V,{verifier:B,nonce:H,mode:Q,redirectUri:j,createdAt:Date.now()});let K=Of({callbackUrl:j,mode:Q,state:V,nonce:H,challenge:G,config:Z});$.callbacks.onAuth({url:K,instructions:"Continue the authentication process in your browser."});try{let F=await j2({waitForCallback:Y.waitForCallback,cancelWait:Y.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),A=F.code,L=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(!L||L!==V)throw Error("State mismatch");let f=await Tf({code:A,state:L,mode:Q,config:Z,requestTimeoutMs:X});return P1($.telemetry,"oca"),b1($.telemetry,{id:f.accountId,email:f.email,provider:"oca"}),f}catch(F){throw S1($.telemetry,"oca",F instanceof Error?F.message:String(F)),F}finally{Y.close()}}async function vJ($,Z={}){let Q=IJ(Z.config),W=Z.requestTimeoutMs??hJ,J=$.metadata?.mode,X=J==="internal"||J==="external"?J:kJ(Z.mode),Y=X==="external"?Q.external:Q.internal,j=await gJ(Y.idcsUrl,W),V=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:Y.clientId}),H=await fetch(j,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:V,signal:AbortSignal.timeout(W)}),B=await H.json();if(!H.ok){let G=mJ(B);throw new n4(`Token refresh failed: ${H.status}${G.message?` - ${G.message}`:""}`,{status:H.status,errorCode:G.code})}return xJ(B,X,$)}async function EZ($,Z,Q){if(!$)return null;let W=Z?.refreshBufferMs??Q?.refreshBufferMs??Ff,J=Z?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??Af;if(Z?.forceRefresh!==!0&&!Y2($,W))return $;try{return await vJ($,Q)}catch(Y){if(Y instanceof n4&&Y.isLikelyInvalidGrant())return A$(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>J)return $;return null}}import{getClineEnvironmentConfig as cJ}from"@cline/shared";var a4="workos:";function qf($){let Z=$.trim();return Z.toLowerCase().startsWith(a4)?Z:`${a4}${Z}`}function Mf($){let Z=$.trim();return Z.toLowerCase().startsWith(a4)?Z.slice(a4.length):Z}function Rf($){let Q=z0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function Ef($,Z){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let W=Rf(Z);if(W)return W;return Date.now()-1}function Nf($,Z){let Q=$.auth?.accessToken?.trim(),W=$.auth?.refreshToken?.trim();if(!Q||!W)return null;let J=Z?.normalizeAccessToken?.(Q)??Q;if(!J)return null;return{access:J,refresh:W,expires:Ef($,J),accountId:$.auth?.accountId}}function wf($){let Z=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:Z,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},W={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(W,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return W}function NZ($){let Z=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:Z,getApiKey(Q){let W=Q?.auth?.accessToken?.trim();if(W)return $.formatAccessToken?.(W)??W;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return wf({...Q,storageProviderId:Z,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function uJ($){return NZ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:qf,normalizeStoredAccessToken:Mf,login:({settings:Z,callbacks:Q,telemetry:W})=>DZ({apiBaseUrl:Z?.baseUrl?.trim()||cJ().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:W}),refresh:({settings:Z,credentials:Q,forceRefresh:W,telemetry:J})=>LZ(Q,{apiBaseUrl:Z.baseUrl?.trim()||cJ().apiBaseUrl,telemetry:J},{forceRefresh:W})})}var Cf=[uJ({providerId:"cline"}),uJ({providerId:"cline-pass",storageProviderId:"cline"}),NZ({providerId:"oca",login:({settings:$,callbacks:Z,telemetry:Q})=>RZ({mode:$?.oca?.mode,callbacks:Z,telemetry:Q}),refresh:({settings:$,credentials:Z,forceRefresh:Q,telemetry:W})=>EZ(Z,{forceRefresh:Q,telemetry:W},{mode:$.oca?.mode,telemetry:W})}),NZ({providerId:"openai-codex",login:({callbacks:$,telemetry:Z})=>_Z({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:Z}),refresh:({credentials:$,forceRefresh:Z,telemetry:Q})=>zZ($,{forceRefresh:Z,telemetry:Q})})],Pf=new Map(Cf.map(($)=>[$.providerId,$]));function B0($){return Pf.get($.trim().toLowerCase())}function J8($){return B0($)!==void 0}function Sf($){return B0($)?.storageProviderId}function bf($,Z){let Q=B0(Z),W=Q?.storageProviderId??Z,J=$.getProviderSettings(W);return Q?.getApiKey(J)??s4(Z,J)}async function wZ($,Z,Q){let W=B0(Z);if(!W)throw Error(`Provider "${Z}" does not support OAuth login`);let J=$.getProviderSettings(W.storageProviderId),X=await W.login({settings:J,callbacks:Q.callbacks,telemetry:Q.telemetry});return W.saveCredentials({manager:$,settings:J,credentials:X})}function CZ($,Z){let Q=B0($);if(!Q)return null;return Nf(Z,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function X8($){let Z=B0($.providerId);if(!Z)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return Z.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function s4($,Z){let Q=B0($);if(Q)return Q.getApiKey(Z);return Z?.auth?.accessToken?.trim()||Z?.apiKey?.trim()||Z?.auth?.apiKey?.trim()||void 0}function yf($,Z){let Q=B0($);if(!Q)return Z.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:Z.access}})??Z.access}import*as S0 from"@cline/llms";import{z as R}from"zod";import*as i from"@cline/llms";function PZ($){if(!Array.isArray($))return[];return $.map((Z)=>{if(typeof Z==="string")return Z.trim();if(Z&&typeof Z==="object"){let Q=Z;for(let W of[Q.id,Q.name,Q.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((Z)=>Z.length>0)}function hf($,Z){let Q=PZ($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let W=$,J=PZ(W.data??W.models);if(J.length>0)return J;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let Y=Object.keys(W.models).filter((j)=>j.trim().length>0);if(Y.length>0)return Y}let X=W.providers?.[Z];if(X&&typeof X==="object"){let j=PZ(X.models??X);if(j.length>0)return j}return[]}async function o4($,Z){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return hf(await Q.json(),Z)}function dJ($){return $.replace(/\/+$/,"")}function t4($,Z,Q){let W=Q?.trim();if(!W)return;let J=$?.trim();if(!J||!Z?.trim())return W;try{let X=new URL(W),Y=new URL(Z),j=new URL(J);if(X.origin!==Y.origin)return W;let V=dJ(Y.pathname),H=dJ(j.pathname);if(V&&X.pathname.startsWith(`${V}/`)){let B=X.pathname.slice(V.length);j.pathname=`${H}${B}`}else j.pathname=X.pathname;return j.search=X.search,j.hash=X.hash,j.toString()}catch{return W}}function kf($){return Object.fromEntries(Object.entries($).map(([Z,Q])=>[Z,{...Q}]))}function If($){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 xf=Object.values(i.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:kf($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),rJ=Object.fromEntries(xf.map(($)=>[$.id,$]));function gf($){return rJ[$]}function mf(){return Object.fromEntries(Object.entries(rJ).filter(([,$])=>If($)))}function iJ($=[]){let Z=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return Z.length>0?Z:void 0}var nJ="https://models.dev/api.json",vf=600000,aJ=300000,cf=5000,$6=new Map,Y8=new Map,bZ=new Map,e4=new Map;async function uf(){return i.getGeneratedProviderModels()}async function df($,Z={},Q={},W={},J={},X={}){if($==="litellm")return i.sortModelsByReleaseDate(W);let Y=await uf(),j=i.resolveProviderModelCatalogKeys($),V=Object.assign({},...j.map((K)=>Y[K]??{})),H=Boolean(i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),B=Object.keys(J).length>0;if(H&&B)return i.sortModelsByReleaseDate({...J,...X});if($==="openai-codex")return i.sortModelsByReleaseDate({...Z,...i.filterOpenAICodexModels(Q),...J,...X});if($==="cline-pass"&&Object.keys(Q).length>0)return i.sortModelsByReleaseDate({...Q,...X});let G=i.sortModelsByReleaseDate({...V,...Z,...Q,...W,...J});if($==="cline")return i.sortModelsByReleaseDate({...i.preferCanonicalModelIds(G,i.VERCEL_OPENROUTER_MODEL_ID_ALIAS_RULES),...X});return i.sortModelsByReleaseDate({...G,...X})}function lf($,Z){let Q=i.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((W)=>Z[W]??{}))}function Z6($){let Z=$?.trim();return Z&&Z.length>0?Z:""}function yZ($){let Z=$.apiKey?.trim()||$.accessToken?.trim();return Z&&Z.length>0?Z:void 0}function pf($){let Z=2166136261;for(let Q=0;Q<$.length;Q+=1)Z^=$.charCodeAt(Q),Z+=(Z<<1)+(Z<<4)+(Z<<7)+(Z<<8)+(Z<<24);return(Z>>>0).toString(16)}function rf($,Z){return`${$}:${Z6(Z.baseUrl)}:${pf(yZ(Z)??"")}`}async function Q6($,Z,Q=cf){let W=new AbortController,J=setTimeout(()=>W.abort(),Q);try{return await fetch($,{...Z,signal:W.signal})}finally{clearTimeout(J)}}function D$($,Z,Q){if(Q&&!$.includes(Z))$.push(Z)}function W6($,Z){let Q=["streaming","tools"];return D$(Q,"images",Boolean(Z.supportsImages)),D$(Q,"prompt-cache",Boolean(Z.supportsPromptCache)),D$(Q,"reasoning",Boolean(Z.supportsReasoning)),{id:$,name:Z.name??$,contextWindow:Z.contextWindow,maxInputTokens:Z.maxInputTokens,maxTokens:Z.maxTokens,capabilities:Q,releaseDate:Z.releaseDate,status:"active"}}async function nf($,Z){let Q=await Q6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${Z}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let J=(await Q.json())?.data??[],X={};for(let Y of J){let j=Y.id?.trim();if(!j)continue;if(j.includes("whisper")||j.includes("tts")||j.includes("embedding"))continue;let V=Y.supported_features??[];X[j]=W6(j,{name:j,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,supportsReasoning:V.includes("reasoning")||V.includes("reasoning_effort"),supportsImages:!1})}return X}function lJ($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let Z=Number($);return Number.isFinite(Z)?Z:void 0}return}async function af($,Z){let Q=await Q6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":Z}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let J=(await Q.json())?.data??[],X={};for(let Y of J){let j=Y.id?.trim();if(!j)continue;X[j]=W6(j,{name:j,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return X}async function sf($,Z){let W=`${(Z6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,J=await Q6(W,{method:"GET",headers:{Authorization:`Bearer ${Z}`,accept:"application/json"}});if(!J.ok)throw Error(`Poolside model refresh failed: HTTP ${J.status}`);let Y=(await J.json())?.data??[],j={};for(let V of Y){let H=V.id?.trim();if(!H)continue;let B=V.supported_features??[],G=V.supported_sampling_parameters??[],K=V.input_modalities??[],F=["streaming"];D$(F,"tools",B.includes("tools")),D$(F,"reasoning",B.includes("reasoning")),D$(F,"temperature",G.includes("temperature")),D$(F,"images",K.includes("image"));let A={input:lJ(V.pricing?.prompt),output:lJ(V.pricing?.completion)};j[H]={id:H,name:V.name??H,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 j}function of($){let Z=Z6($).replace(/\/+$/,"");if(!Z)return"http://localhost:4000";return Z.endsWith("/v1")?Z.slice(0,-3):Z}function tf($){return[`${$}/v1/model/info`,`${$}/model/info`]}async function ef($){let Z=(await $.text().catch(()=>"")).replace(/\s+/g," ").trim(),Q=500,W=Z?`: ${Z.slice(0,500)}${Z.length>500?"...":""}`:"";return`HTTP ${$.status}${W}`}async function $U($,Z){let Q=of($.baseUrl),W=[],J=[["x-litellm-api-key",{"x-litellm-api-key":Z}],["Authorization",{Authorization:`Bearer ${Z}`}]];for(let X of tf(Q))for(let[Y,j]of J)try{let V=await Q6(X,{method:"GET",headers:{accept:"application/json",...j}});if(V.ok){let B=(await V.json())?.data??[],G={};for(let K of B){let F=K.model_name?.trim(),L=K.litellm_params?.model?.trim()||F;if(!L)continue;let f=K.model_info,D=W6(L,{name:F??L,maxTokens:f?.max_output_tokens??f?.max_tokens,maxInputTokens:f?.max_input_tokens??f?.max_tokens,supportsImages:f?.supports_vision,supportsPromptCache:f?.supports_prompt_caching,supportsReasoning:f?.supports_reasoning});if(G[L]=D,F)G[F]={...D,id:F,name:F}}return G}W.push(`${new URL(X).pathname} (${Y}): ${await ef(V)}`)}catch(V){let H=V instanceof Error?V.message:String(V);W.push(`${new URL(X).pathname} (${Y}): ${H}`)}throw Error(`LiteLLM model refresh failed. Attempts: ${W.join("; ")}`)}var sJ={baseten:nf,hicap:af,litellm:$U,poolside:sf},pJ=new Map,SZ=new Map;function ZU($,Z){return`${$}:${Z6(Z.baseUrl)}`}async function QU($,Z,Q){let W=i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],J=t4(Q.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!J)return{};let X=Z?.cacheTtlMs??aJ,Y=ZU($,Q),j=Date.now(),V=pJ.get(Y);if(V&&V.expiresAt>j)return V.data;let H=SZ.get(Y);if(H)return H;let B=o4(J,$).then((G)=>{let K=Object.fromEntries(G.map((F)=>[F,W6(F,{name:F})]));return pJ.set(Y,{data:K,expiresAt:j+X}),K}).finally(()=>{SZ.delete(Y)});return SZ.set(Y,B),B}async function WU($,Z){let Q=yZ(Z);if(!Q)return{};let W=sJ[$];if(!W)return{};return W(Z,Q)}function JU($,Z,Q){if(!Q)return!1;if(!sJ[$])return!1;if(Z?.loadPrivateOnAuth===!1)return!1;return Boolean(yZ(Q))}async function XU($,Z,Q){let W=Z?.cacheTtlMs??aJ,J=rf($,Q),X=Date.now(),Y=bZ.get(J);if(Y&&Y.expiresAt>X)return Y.data;let j=e4.get(J);if(j)return j;let V=WU($,Q).then((H)=>{return bZ.set(J,{data:H,expiresAt:X+W}),H}).finally(()=>{e4.delete(J)});return e4.set(J,V),V}async function YU($){return i.fetchLiveProviderModels($,globalThis.fetch)}async function J6($={}){let Z=$.url??nJ,Q=$.cacheTtlMs??vf,W=Date.now(),J=$6.get(Z);if(J&&J.expiresAt>W)return J.data;let X=Y8.get(Z);if(X)return X;let Y=YU(Z).then((j)=>{return $6.set(Z,{data:j,expiresAt:W+Q}),j}).finally(()=>{Y8.delete(Z)});return Y8.set(Z,Y),Y}function jU($){if($){$6.delete($),Y8.delete($);return}$6.clear(),Y8.clear()}function VU(){bZ.clear(),e4.clear()}function HU($){return Object.fromEntries(Object.entries($).map(([Z,Q])=>[Z,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:iJ(Q.capabilities)}]))}var hZ=HU(mf());function oJ($){let Z=gf($);if(!Z)return;return{baseUrl:Z.baseUrl||void 0,modelId:Z.modelId,knownModels:Z.knownModels,capabilities:iJ(Z.capabilities)}}async function kZ($,Z,Q){let W=oJ($);if(!W)return;try{let J=Z?.loadLatestOnInit?await J6(Z):void 0,X=J?lf($,J):{},Y=Q&&JU($,Z,Q)?await XU($,Z,Q):{},V=Boolean(i.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:Q,H=V?await QU($,Z,V).catch(()=>({})):{},B=await df($,W.knownModels,X,Y,H,Q?.knownModels);return{...W,knownModels:B}}catch(J){if(Z?.failOnError)throw J;if($==="litellm")return{...W,knownModels:{}};return W}}var IZ=S0.BUILT_IN_PROVIDER,BU=S0.BUILT_IN_PROVIDER_IDS,GU=S0.isBuiltInProviderId,X6=S0.normalizeProviderId,xZ=R.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),tJ=R.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),eJ=R.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),$X=R.object({apiKey:R.string().optional(),accessToken:R.string().optional(),refreshToken:R.string().optional(),expiresAt:R.number().int().positive().optional(),accountId:R.string().optional()}),KU=R.enum(["none","low","medium","high","xhigh"]),ZX=R.object({enabled:R.boolean().optional(),effort:KU.optional(),budgetTokens:R.number().int().positive().optional()}),QX=R.object({accessKey:R.string().optional(),secretKey:R.string().optional(),sessionToken:R.string().optional(),region:R.string().optional(),profile:R.string().optional(),authentication:R.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:R.boolean().optional(),useCrossRegionInference:R.boolean().optional(),useGlobalInference:R.boolean().optional(),endpoint:R.string().url().optional(),customModelBaseId:R.string().optional()}),WX=R.object({projectId:R.string().optional(),region:R.string().optional()}),JX=R.object({apiVersion:R.string().optional(),useIdentity:R.boolean().optional()}),XX=R.object({clientId:R.string().optional(),clientSecret:R.string().optional(),tokenUrl:R.string().url().optional(),resourceGroup:R.string().optional(),deploymentId:R.string().optional(),useOrchestrationMode:R.boolean().optional(),api:R.enum(["orchestration","foundation-models"]).optional(),defaultSettings:R.record(R.string(),R.unknown()).optional()}),YX=R.object({mode:R.enum(["internal","external"]).optional(),usePromptCache:R.boolean().optional()}),jX=R.object({loadLatestOnInit:R.boolean().optional(),loadPrivateOnAuth:R.boolean().optional(),url:R.string().url().optional(),cacheTtlMs:R.number().int().positive().optional(),failOnError:R.boolean().optional()}),H2=R.object({provider:xZ,apiKey:R.string().optional(),auth:$X.optional(),model:R.string().optional(),protocol:tJ.optional(),client:eJ.optional(),routingProviderId:xZ.optional(),maxTokens:R.number().int().positive().optional(),contextWindow:R.number().int().positive().optional(),baseUrl:R.string().url().optional(),headers:R.record(R.string(),R.string()).optional(),timeout:R.number().int().positive().optional(),reasoning:ZX.optional(),aws:QX.optional(),gcp:WX.optional(),azure:JX.optional(),sap:XX.optional(),oca:YX.optional(),region:R.string().optional(),apiLine:R.enum(["china","international"]).optional(),capabilities:R.array(R.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:jX.optional()});function VX($){return H2.parse($)}function HX($){return H2.safeParse($)}function FU($){return $.protocol==="openai-responses"||$.client==="openai"}function B1($,Z={}){let Q=$.provider,W=X6(Q),J=Z.includeKnownModels!==!1,X=$.reasoning?.effort||"none",Y=X==="none"?void 0:X,j=hZ[W],V=Object.assign({},...S0.resolveProviderModelCatalogKeys(W).map((L)=>S0.getGeneratedModelsForProvider(L))),H=Object.keys(V)[0],B=s4(W,$),G=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?qZ:MZ:j?.baseUrl),K=$.routingProviderId??(FU($)&&W!==IZ.OPENAI_NATIVE?IZ.OPENAI_NATIVE:void 0),F=J?j?.knownModels??(Object.keys(V).length>0?V:void 0):void 0,A={providerId:Q,clientType:$.client,routingProviderId:K,modelId:$.model??j?.modelId??H??"default",...J?{knownModels:F}:{},apiKey:B,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:G,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:Y,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??j?.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(([L,f])=>f!==void 0))}function AU($){let Z=VX($);return B1(Z)}function fU($){let Z=HX($);if(Z.success)return{success:!0,config:B1(Z.data)};return{success:!1,error:Z.error}}import{SESSION_STATUS_VALUES as UU}from"@cline/shared";var gZ=UU,DU=["idle","running","pending"];function LU($){return!DU.includes($)}function j0($){return!LU($)}var T0={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"};function BX($){if($===!0)return{};if(!$)return;return $}function GX($){if($==="user")return"global";return $}class mZ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let Z=this.getService().ingestEvent($);return{event:Z.event,duplicate:Z.duplicate,matchedSpecIds:Z.matchedSpecs.map((Q)=>Q.specId),queuedRuns:Z.queuedRuns,suppressions:Z.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function KX($){let{host:Z}=$;return{async startSession(Q){let W=(Q.cwd?.trim()||Q.workspaceRoot).trim(),J=await Z.startSession({source:Q.source?.trim()||T0.CLI,interactive:!1,config:{providerId:X6(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:W,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:TU(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Q,W){let J=await Z.runTurn({sessionId:Q,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((X)=>X.content),delivery:W.delivery});if(!J)throw Error("ClineCore automation runtime returned no result");return{result:zU(J)}},async abortSession(Q){return await Z.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}function Y6($){let Z=_U($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),J=$.context?.logger??$.logger,X=$.context?.telemetry??$.telemetry;if(!Z&&!Q&&!W&&!J&&!X)return $.context;return{...$.context??{},...Q?{client:Q}:{},...W?{user:W}:{},...J?{logger:J}:{},...X?{telemetry:X}:{},...Z?{automation:Z}:{}}}function _U($,Z){if(!$)return;return{ingestEvent:(Q)=>{Z.ingestEvent(Q)}}}function zU($){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((Z)=>({name:Z.name,input:Z.input,output:Z.output,error:Z.error,durationMs:Z.durationMs}))}}function TU($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as g8,readFileSync as OO}from"node:fs";import{basename as Y7,dirname as MV,extname as qO,isAbsolute as NV,join as MO,relative as wV,resolve as RV}from"node:path";import{createHash as OU}from"node:crypto";import{watch as qU}from"node:fs";import{readdir as MU,readFile as RU}from"node:fs/promises";import{join as EU}from"node:path";function NU($){return OU("sha1").update($).digest("hex")}function fX($){return Boolean($&&typeof $==="object"&&"code"in $)}function FX($){return fX($)&&$.code==="ENOENT"}function AX($){return fX($)&&($.code==="EACCES"||$.code==="EPERM")}class j8{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($,Z){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=Z?.debounceMs??75,this.emitParseErrors=Z?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let W of Q.directories){let J=this.baseTypesByDirectory.get(W);if(J)J.add(Q.type);else this.baseTypesByDirectory.set(W,new Set([Q.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 Z=this.definitionsByType.get($);if(!Z)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(Z)})}getSnapshot($){let Z=this.recordsByType.get($);return new Map([...Z?.entries()??[]].map(([Q,W])=>[Q,{...W}]))}getAllSnapshots(){let $=new Map;for(let[Z,Q]of this.recordsByType.entries())$.set(Z,new Map([...Q.entries()].map(([W,J])=>[W,{...J}])));return $}emit($){for(let Z of this.listeners)Z($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[Z,Q]of this.watchersByDirectory.entries()){if($.has(Z))continue;Q.close(),this.watchersByDirectory.delete(Z)}this.watchedTypesByDirectory=$;for(let Z of $.keys()){if(this.watchersByDirectory.has(Z))continue;try{let Q=qU(Z,()=>{let W=this.watchedTypesByDirectory.get(Z);if(!W)return;for(let J of W)this.pendingTypes.add(J);this.scheduleFlush()});this.watchersByDirectory.set(Z,Q),Q.on("error",(W)=>{let J=this.watchedTypesByDirectory.get(Z);if(!J)return;for(let X of J)this.emit({kind:"error",type:X,error:W,filePath:Z})})}catch(Q){if(!FX(Q)&&!AX(Q)){let W=$.get(Z);if(!W)continue;for(let J of W)this.emit({kind:"error",type:J,error:Q,filePath:Z})}}}}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 Z of $){let Q=this.definitionsByType.get(Z);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:Z,discoveredDirectories:Q}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[J,X]of W.entries()){if(Z.has(J))continue;this.emit({kind:"remove",type:$.type,id:J,filePath:X.filePath})}for(let[J,X]of Z.entries()){let Y=W.get(J);if(Y&&Y.filePath===X.filePath&&Y.fingerprint===X.fingerprint)continue;this.emit({kind:"upsert",record:{type:X.type,id:J,item:X.item,filePath:X.filePath}})}if(this.recordsByType.set($.type,Z),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let Z=new Map,Q=new Set;for(let W of $.directories){Q.add(W);let J=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let X of J){let{fileName:Y,filePath:j}=X;if(Q.add(X.directoryPath),$.includeFile&&!$.includeFile(Y,j))continue;try{let V=await RU(j,"utf8"),H={type:$.type,directoryPath:X.directoryPath,fileName:Y,filePath:j,content:V},B=$.parseFile(H),G=$.resolveId(B,H).trim();if(!G)continue;Z.set(G,{type:$.type,id:G,item:B,filePath:j,fingerprint:NU(V)})}catch(V){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:V,filePath:j})}}}return{records:Z,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[Z,Q]of this.baseTypesByDirectory.entries())$.set(Z,new Set(Q));for(let[Z,Q]of this.discoveredDirectoriesByType.entries())for(let W of Q){let J=$.get(W);if(J)J.add(Z);else $.set(W,new Set([Z]))}return $}async readDirectoryFileCandidates($){try{return(await MU($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:EU($,Q.name)})).sort((Q,W)=>Q.fileName.localeCompare(W.fileName))}catch(Z){if(FX(Z)||AX(Z))return[];throw Z}}}import{readdir as jQ,readFile as iD,stat as YQ}from"node:fs/promises";import{basename as F1,dirname as nD,extname as z6,join as E0,resolve as K8}from"node:path";import{AGENTS_RULES_FILE_NAME as lX,RULES_CONFIG_DIRECTORY_NAME as pX,resolveGlobalAgentsRulesPath as aD,resolveRulesConfigSearchPaths as sD,resolveSkillsConfigSearchPaths as oD,resolveWorkflowsConfigSearchPaths as tD,SKILLS_CONFIG_DIRECTORY_NAME as VQ,WORKFLOWS_CONFIG_DIRECTORY_NAME as HQ}from"@cline/shared/storage";import eD from"yaml";r0();import{existsSync as U6,readFileSync as hD,statSync as kD}from"node:fs";import{basename as ID,dirname as A6,join as D6,resolve as f6}from"node:path";import{discoverPluginModulePaths as xD,resolveConfiguredPluginModulePaths as mX,resolvePluginConfigSearchPaths as gD,SKILLS_CONFIG_DIRECTORY_NAME as mD}from"@cline/shared/storage";import{resolve as GD}from"node:path";import{normalizePluginManifest as KD}from"@cline/shared";import{existsSync as K0,readFileSync as G2}from"node:fs";import{builtinModules as rU,createRequire as iZ}from"node:module";import{dirname as I1,extname as H8,isAbsolute as iU,resolve as u}from"node:path";import{fileURLToPath as TX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as nU}from"@cline/shared";var OX=I1(TX(import.meta.url)),aU=iZ(import.meta.url),sU=u(OX,"..","..","..","..",".."),lZ=eU(sU),oU=["@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"],nZ=new Set(rU.flatMap(($)=>[$,$.replace(/^node:/,"")])),V8=new Set(nU),tU=["development","node","import","require","default"];function eU($){let Z={},Q={"@cline/sdk":u($,"packages/sdk/src/index.ts"),"@cline/agents":u($,"packages/agents/src/index.ts"),"@cline/core":u($,"packages/core/src/index.ts"),"@cline/llms":u($,"packages/llms/src/index.ts"),"@cline/shared":u($,"packages/shared/src/index.ts"),"@cline/shared/storage":u($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":u($,"packages/shared/src/db/index.ts")};for(let[W,J]of Object.entries(Q))if(K0(J))Z[W]=J;for(let W of["agents","core","llms","shared"]){let J=u($,"packages",W),X=u(J,"package.json");if(!K0(X))continue;try{let Y=JSON.parse(G2(X,"utf8"));if(typeof Y.name!=="string"||!Y.exports)continue;if(typeof Y.exports==="string"){let j=u(J,Y.exports);if(K0(j))Z[Y.name]=j;continue}if(typeof Y.exports!=="object")continue;for(let[j,V]of Object.entries(Y.exports)){let H=$D(J,V);if(!H)continue;let B=j==="."?Y.name:`${Y.name}/${j.replace(/^\.\//,"")}`;Z[B]=H}}catch{}}return Z}function $D($,Z){let Q=aZ(Z);if(!Q)return null;let W=qX($,Q);for(let J of W)if(K0(J))return J;return null}function aZ($,Z=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(Z.has($))return null;Z.add($);let Q=$;for(let W of tU){let J=aZ(Q[W],Z);if(J)return J}return null}function qX($,Z){let Q=Z.replace(/^\.\//,""),W=[u($,Z)];if(Q.startsWith("dist/")){let J=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[u($,`${J}.ts`),u($,`${J}.tsx`),u($,`${J}.mts`),u($,`${J}.cts`),...W]}return W}function ZD($){return Object.fromEntries(Object.entries($).sort(([Z],[Q])=>Q.length-Z.length))}function G6($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function B2($){if($.startsWith("@")){let[Z,Q]=$.split("/",3);return Q?`${Z}/${Q}`:$}return $.split("/",1)[0]??$}function QD($){let Z=B2($);if($===Z)return".";return`.${$.slice(Z.length)}`}function MX($){return B2($).startsWith("@cline/")}function pZ($,Z){let Q=B2(Z),W=I1($);while(!0){let J=u(W,"node_modules",Q);if(K0(J)||K0(u(J,"package.json")))return!0;let X=u(W,"..");if(X===W)return!1;W=X}}function zX($){return rZ($)!==null}function rZ($){try{return aU.resolve($)}catch{}return WD($)}function WD($){let Z=B2($),Q=RX(Z);if(!Q)return null;let W=u(Q,"package.json");try{let J=JSON.parse(G2(W,"utf8")),X=QD($),Y=X==="."&&typeof J.exports==="string"?J.exports:J.exports&&typeof J.exports==="object"&&Object.hasOwn(J.exports,X)?J.exports[X]:void 0,j=aZ(Y)??(X==="."&&typeof J.main==="string"?J.main:null);if(!j)return null;let V=u(Q,j),H=[V,...qX(Q,j).filter((B)=>B!==V)];for(let B of H)if(K0(B))return B;return null}catch{return null}}function JD(){let $=[OX],Z=process.env.CLINE_WRAPPER_PATH?.trim();if(Z)$.push(I1(I1(Z)));let Q=process.execPath?.trim();if(Q)$.push(I1(Q));return[...new Set($.map((W)=>u(W)))]}function XD($,Z){let Q=$;while(!0){let W=u(Q,"package.json");if(K0(W))try{if(JSON.parse(G2(W,"utf8")).name===Z)return Q}catch{}let J=u(Q,"node_modules",Z,"package.json");if(K0(J))return I1(J);let X=u(Q,"..");if(X===Q)return null;Q=X}}function RX($){for(let Z of JD()){let Q=XD(Z,$);if(Q)return Q}return null}function YD($){let Q=I1($);for(let W=0;W<4;W++){let J=u(Q,"package.json");if(K0(J))try{let Y=JSON.parse(G2(J,"utf8"));return Y!=null&&typeof Y==="object"&&"cline"in Y}catch{return!1}let X=u(Q,"..");if(X===Q)return!1;Q=X}return!1}function EX($,Z){let Q=Z.startsWith("file:")?TX(Z):iU(Z)?Z:u(I1($),Z);if(K0(Q)&&V8.has(H8(Q)))return Q;for(let W of V8){let J=`${Q}${W}`;if(K0(J))return J}for(let W of V8){let J=u(Q,`index${W}`);if(K0(J))return J}return null}function NX($){let Z=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let W of Q)for(let J of $.matchAll(W)){let X=J[1];if(X)Z.add(X)}return[...Z]}function jD($){return H8($)!==".ts"}function wX($,Z,Q=new Set){if(Q.has($)||!K0($))return;if(Q.add($),!V8.has(H8($)))return;let W=G2($,"utf8"),J=jD($);for(let X of NX(W)){if(X.startsWith("node:")||nZ.has(X))continue;if(G6(X)){if(!J)continue;if(Object.hasOwn(lZ,X)||Object.hasOwn(lZ,B2(X))||pZ($,X)||MX(X)&&zX(X)||Z&&zX(X))continue;throw Error(`Cannot find module '${B2(X)}'`)}let Y=EX($,X);if(Y)wX(Y,Z,Q)}}function CX($,Z=new Set,Q=new Set){if(Z.has($)||!K0($))return Q;if(Z.add($),!V8.has(H8($)))return Q;let W=G2($,"utf8");for(let J of NX(W)){if(Q.add(J),G6(J))continue;let X=EX($,J);if(X)CX(X,Z,Q)}return Q}function VD($,Z){let Q=iZ($),W={},J=CX($),X=new Set(oU);for(let[Y,j]of Object.entries(lZ)){try{Q.resolve(Y);continue}catch{}W[Y]=j}for(let Y of J)if(G6(Y)&&(MX(Y)||Z))X.add(Y);for(let Y of X){if(Object.hasOwn(W,Y)||pZ($,Y))continue;let j=rZ(Y);if(j)W[Y]=j}if(!Z)return W;for(let Y of J){if(!G6(Y)||Object.hasOwn(W,Y)||pZ($,Y)||Y.startsWith("node:")||nZ.has(Y))continue;let j=rZ(Y);if(j)W[Y]=j}return W}function HD($){let Z=H8($);return Z===".ts"||Z===".tsx"||Z===".mts"||Z===".cts"}var _$;function BD(){if(_$!==void 0)return _$;let $=RX("jiti");if(!$)return _$=null,null;let Z=u($,"dist","babel.cjs");if(!K0(Z))return _$=null,null;try{let W=iZ(Z)(Z);_$=typeof W==="function"?W:null}catch{_$=null}return _$}async function PX($,Z={}){let Q=!YD($);wX($,Q);let W=VD($,Q),J=ZD(W),X=await import("jiti"),Y=typeof X==="function"?X:typeof X.default==="function"?X.default:void 0;if(!Y)throw Error("Unable to load jiti");let j=Object.entries(J).filter(([,G])=>HD(G)).map(([G])=>G),V=BD(),H=V?(G)=>V({...G,interopDefault:!0}):void 0;return await Y($,{alias:J,cache:Z.useCache,requireCache:Z.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...nZ],transformModules:j,tryNative:!1,...H?{transform:H}:{}}).import($,{})}function SX($,Z){if(!$)return!0;if($.providerIds?.length){if(!Z?.providerId||!$.providerIds.includes(Z.providerId))return!1}if($.modelIds?.length){if(!Z?.modelId||!$.modelIds.includes(Z.modelId))return!1}return!0}function bX($){return typeof $==="object"&&$!==null}function sZ($){return Array.isArray($)&&$.every((Z)=>typeof Z==="string")}function FD($,Z){if(!bX($.manifest))throw Error(`Invalid plugin module at ${Z}: missing required "manifest"`);if(!sZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${Z}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${Z}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!sZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${Z}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!sZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${Z}: manifest.modelIds must be a string array when provided`)}function AD($,Z){if(!bX($))throw Error(`Invalid plugin module at ${Z}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${Z}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${Z}: missing required "manifest"`);FD($,Z)}async function oZ($,Z={}){let Q=GD(Z.cwd??process.cwd(),$),W=await PX(Q,{useCache:Z.useCache}),J=Z.exportName??"plugin",X=W.default??W[J];AD(X,Q);let Y=X,j=Y.setup,V=j?(H,B)=>{let G={...Z.session,...B.session},K={...B,session:Object.keys(G).length>0?G:void 0,client:Z.client??B.client,user:Z.user??B.user,workspaceInfo:Z.workspaceInfo??B.workspaceInfo,automation:Z.automation??B.automation,logger:Z.logger??B.logger,telemetry:Z.telemetry??B.telemetry};return j(H,K)}:void 0;return{...Y,manifest:KD(Y.manifest),setup:V}}async function yX($,Z={}){return(await B8($,Z)).plugins}async function B8($,Z={}){let Q=[],W=[],J=new Map,X=0;for(let j of $)try{let V=await oZ(j,Z);if(!SX(V.manifest,Z))continue;let H=J.get(V.name);if(H)W.push({type:"duplicate_plugin_override",pluginName:V.name,pluginPath:j,overriddenPluginPath:H.pluginPath,message:`Plugin "${V.name}" from ${j} overrides ${H.pluginPath}`});J.set(V.name,{plugin:V,pluginPath:j,order:X++})}catch(V){let H=V instanceof Error?V.message:String(V);Q.push({pluginPath:j,phase:"load",message:H,stack:V instanceof Error?V.stack:void 0})}let Y=[...J.values()].sort((j,V)=>j.order-V.order);return{plugins:Y.map((j)=>j.plugin),pluginPaths:Y.map((j)=>j.pluginPath),failures:Q,warnings:W}}import{existsSync as $Q}from"node:fs";import{createRequire as gX}from"node:module";import{dirname as F6,join as K2}from"node:path";import{fileURLToPath as TD}from"node:url";import{spawn as fD}from"node:child_process";import{basename as UD}from"node:path";import{augmentNodeCommandForDebug as DD,withResolvedClineBuildEnv as LD}from"@cline/shared";function hX($){if($ instanceof Error)return $;return Error(String($))}var _D="CLINE_JS_RUNTIME_PATH";function kX($){let Z=$?.trim();if(!Z)return!1;let Q=UD(Z).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function IX($={}){let Z=$.env??process.env,Q=$.runtimeExecutable?.trim()||Z[_D]?.trim();if(Q)return Q;let W=$.execPath?.trim()||process.execPath;if(kX(W))return W;for(let J of[Z.BUN_EXEC_PATH,Z.npm_node_execpath,Z.NODE]){let X=J?.trim();if(X&&kX(X))return X}return"node"}function zD($,Z={}){let Q=IX({env:Z.env,execPath:Z.execPath,runtimeExecutable:Z.runtimeExecutable});return DD([Q,...$],{env:Z.env,execArgv:Z.execArgv,debugRole:Z.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class K6{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let Z=this.pending.get($);if(!Z)return;if(this.pending.delete($),Z.timeout)clearTimeout(Z.timeout);return Z}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],Z=zD($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=fD(Z[0]??IX(this.options),Z.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:LD(process.env),windowsHide:!0});this.process=Q;let W="",J=(X)=>{let Y=W+X;W=Y.length>4000?Y.slice(-4000):Y};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(X)=>{J(X)}),Q.on("message",(X)=>{this.onMessage(X)}),Q.on("error",(X)=>{this.failPending(Error(`${this.processLabel} process error: ${hX(X).message}`))}),Q.on("exit",(X,Y)=>{this.process=null;let j=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(X)}, signal=${String(Y)})${j?`: ${j}`:""}`))})}async call($,Z,Q={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let J=`req_${++this.requestCounter}`,X={type:"call",id:J,method:$,args:Z};return await new Promise((Y,j)=>{let V={resolve:(H)=>Y(H),reject:j};if((Q.timeoutMs??0)>0)V.timeout=setTimeout(()=>{this.clearPendingRequest(J),this.shutdown().catch(()=>{}),j(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(J,V),W.send(X,(H)=>{if(!H)return;let B=this.clearPendingRequest(J);if(!B)return;B.reject(Error(`${this.processLabel} failed to send call "${$}": ${hX(H).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((Z)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}Z()},300);$.once("exit",()=>{clearTimeout(Q),Z()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),Z()}}),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 Z=this.clearPendingRequest($.id);if(!Z)return;if($.ok){Z.resolve($.result);return}Z.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[Z,Q]of this.pending.entries()){if(this.pending.delete(Z),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function OD($){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 G8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function qD(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function MD(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=gX($).resolve(`${qD()}/package.json`),W=K2(F6(Q),"extensions","plugin-sandbox-bootstrap.js");return $Q(W)?W:void 0}catch{return}}function RD(){let $=process.execPath?.trim();if(!$)return;let Z=K2(F6(F6($)),"extensions","plugin-sandbox-bootstrap.js");return $Q(Z)?Z:void 0}function ED(){let $=F6(TD(import.meta.url)),Z=gX(import.meta.url),Q=[K2($,"plugin-sandbox-bootstrap.js"),K2($,"extensions","plugin-sandbox-bootstrap.js"),K2($,"agents","plugin-sandbox-bootstrap.js"),MD(),RD()];for(let X of Q.filter((Y)=>typeof Y==="string"))if($Q(X))return{file:X};let W=K2($,"plugin-sandbox-bootstrap.ts"),J="jiti";try{J=Z.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(J)});`,`const jiti = createJiti(${JSON.stringify(W)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(W)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
46
+ `)}}var tZ=ED();function eZ($,Z,Q){if(typeof $==="number"&&$>0)return $;if(Q){let W=process.env[Q];if(W){let J=Number(W);if(Number.isInteger(J)&&J>0)return J}}return Z}async function F2($){let Z=new K6({name:"plugin-sandbox",..."file"in tZ?{bootstrapFile:tZ.file}:{bootstrapScript:tZ.script},onEvent:$.onEvent}),Q=eZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=eZ($.hookTimeoutMs,3000),J=eZ($.contributionTimeoutMs,60000),X={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},Y,j=()=>{return Y??=Z.call("initialize",X,{timeoutMs:Q}).finally(()=>{Y=void 0}),Y},V;try{V=await Z.call("initialize",X,{timeoutMs:Q})}catch(G){throw await Z.shutdown().catch(()=>{}),G}let H=V.plugins.map(OD);return{extensions:H.map((G)=>{let K={name:G.name,__clinePluginPath:G.pluginPath,manifest:G.manifest,setup:(F)=>{ND(F,Z,G,J,j),wD(F,Z,G,J,j),CD(F,Z,G,J,j),SD(F,Z,G,J,j),PD(F,G)}};return K.hooks=yD(Z,G,W,j),K}),failures:V.failures,pluginPaths:H.map((G)=>G.pluginPath),shutdown:async()=>{await Z.shutdown()},warnings:V.warnings}}function ND($,Z,Q,W,J){for(let X of Q.contributions?.tools??[]){let Y={name:X.name,description:X.description??"",inputSchema:X.inputSchema??{type:"object",properties:{}},timeoutMs:X.timeoutMs,retryable:X.retryable,execute:async(j,V)=>{try{return await Z.call("executeTool",{pluginId:Q.pluginId,contributionId:X.id,input:j,context:V},{timeoutMs:W})}catch(H){if(!G8(H))throw H;return await J(),await Z.call("executeTool",{pluginId:Q.pluginId,contributionId:X.id,input:j,context:V},{timeoutMs:W})}}};$.registerTool(Y)}}function wD($,Z,Q,W,J){for(let X of Q.contributions?.commands??[])$.registerCommand({name:X.name,description:X.description,handler:async(Y)=>{try{return await Z.call("executeCommand",{pluginId:Q.pluginId,contributionId:X.id,input:Y},{timeoutMs:W})}catch(j){if(!G8(j))throw j;return await J(),await Z.call("executeCommand",{pluginId:Q.pluginId,contributionId:X.id,input:Y},{timeoutMs:W})}}})}function CD($,Z,Q,W,J){for(let X of Q.contributions?.rules??[])$.registerRule({id:X.ruleId,source:X.source,content:X.hasContentHandler===!0?async()=>{try{return await Z.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:X.id},{timeoutMs:W})}catch(Y){if(!G8(Y))throw Y;return await J(),await Z.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:X.id},{timeoutMs:W})}}:X.content??""})}function PD($,Z){for(let Q of Z.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of Z.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of Z.contributions?.mcpServers??[])$.registerMcpServer(Q)}function SD($,Z,Q,W,J){for(let X of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:X.name,async build(Y){try{let j=await Z.call("buildMessages",{pluginId:Q.pluginId,contributionId:X.id,messages:Y},{timeoutMs:W});return xX(j)?j:Y}catch(j){if(!G8(j))throw j;await J();let V=await Z.call("buildMessages",{pluginId:Q.pluginId,contributionId:X.id,messages:Y},{timeoutMs:W});return xX(V)?V:Y}}})}function xX($){return Array.isArray($)&&$.every((Z)=>typeof Z==="object"&&Z!==null&&("role"in Z)&&("content"in Z))}function bD($,Z,Q,W,J){return async(X)=>{try{return await $.call("invokeHook",{pluginId:Z,hookName:Q,payload:X},{timeoutMs:W})}catch(Y){if(!G8(Y))throw Y;return await J(),await $.call("invokeHook",{pluginId:Z,hookName:Q,payload:X},{timeoutMs:W})}}}function yD($,Z,Q,W){let J={};for(let X of Z.hooks??[])J[X]=bD($,Z.pluginId,X,Q,W);return Object.keys(J).length>0?J:void 0}var QQ="package.json",vD="package";function WQ($){return gD($)}function JQ($){return xD($)}function cD($){try{return U6($)&&kD($).isDirectory()}catch{return!1}}function XQ($){let Z=[],Q=new Set;for(let W of $){let J=f6(W);if(Q.has(J))continue;Q.add(J),Z.push(J)}return Z}function vX($){let Z=XQ($);return uZ(Z)}function cX($){return WQ($).flatMap((Z)=>JQ(Z)).filter((Z)=>U6(Z))}function uD($,Z){let Q=[];for(let W of $)try{Q.push(...mX([W],Z))}catch{}return Q}function ZQ($){return typeof $==="object"&&$!==null}function dD($){try{let Z=JSON.parse(hD(D6($,QQ),"utf8"));if(!ZQ(Z)||!ZQ(Z.cline))return[];let Q=Z.cline.plugins;if(!Array.isArray(Q))return[];let W=[];for(let J of Q){if(typeof J==="string"){W.push(J);continue}if(!ZQ(J)||!Array.isArray(J.paths))continue;for(let X of J.paths)if(typeof X==="string")W.push(X)}return W}catch{return[]}}function uX($,Z){let Q=f6(Z);return dD($).some((W)=>f6($,W)===Q)}function lD($,Z){return ID($)===vD&&U6(D6(A6($),QQ))&&uX(A6($),Z)}function pD($){let Z=f6($),Q=[],W=A6(Z);while(!0){if(lD(W,Z)){Q.push(W);break}if(U6(D6(W,QQ))){if(uX(W,Z))Q.push(W);break}let J=A6(W);if(J===W)break;W=J}return XQ(Q)}function z$($={}){let Z=$.cwd??process.cwd(),Q=cX($.workspacePath),W=mX($.pluginPaths??[],Z);return vX([...W,...Q])}function rD($={}){let Z=$.cwd??process.cwd(),Q=cX($.workspacePath),W=uD($.pluginPaths??[],Z);return vX([...W,...Q])}function T$($){let Z=[];for(let Q of $)for(let W of pD(Q)){let J=D6(W,mD);if(cD(J))Z.push(J)}return XQ(Z)}function dX($={}){return T$(rD($))}async function L6($={}){let Z=z$($);if(Z.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await B8(Z,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:W.plugins,failures:W.failures,pluginPaths:W.pluginPaths,warnings:W.warnings}}let Q=await F2({pluginPaths:Z,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:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}var _6="SKILL.md",$L="managed.json",ZL=new Set([".md",".markdown",".txt"]);function BQ($){return $.trim().toLowerCase()}function A2($){let Z=$;return Z?.code==="ENOENT"||Z?.code==="EACCES"||Z?.code==="EPERM"||Z?.code==="ELOOP"}function T6($){return ZL.has(z6($).toLowerCase())}function rX($){let Z=[],Q=new Set;for(let W of $){let J=K8(W);if(Q.has(J))continue;Q.add(J),Z.push(W)}return Z}function QL($){let Z=[...$?.directories??UQ($?.workspacePath)];if($?.pluginSkillDirectories)Z.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)Z.push(...dX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return rX(Z)}async function GQ($){try{let Z=await jQ($,{withFileTypes:!0}),Q=[];for(let W of Z){if(!W.isDirectory())continue;let J=E0($,W.name),X=E0(J,$L);try{let Y=await iD(X,"utf8"),j=JSON.parse(Y);if(j&&typeof j==="object")Q.push(J)}catch(Y){if(A2(Y))continue;if(Y?.name==="SyntaxError")continue;throw Y}}return Q.sort((W,J)=>W.localeCompare(J))}catch(Z){if(A2(Z))return[];throw Z}}function KQ($){let Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(Z);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,W,J]=Q;try{let X=eD.parse(W);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:$,hadFrontmatter:!0,parseError:Y}}}function O6($,Z,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${Z}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${Z}' must be a string.`);let W=$.trim();if(!W&&Q)throw Error(`Frontmatter field '${Z}' cannot be empty.`);return W||void 0}function f2($,Z){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${Z}' must be a boolean.`);return $}function WL($,Z){if(F1($.filePath).toLowerCase()!==lX.toLowerCase())return F1($.filePath,z6($.filePath));if(Z&&K8($.filePath)===K8(Z,lX))return"Workspace AGENTS.md";if(K8($.filePath)===K8(aD()))return"Global AGENTS.md";return F1($.filePath,z6($.filePath))}function FQ($,Z){let{data:Q,body:W,parseError:J}=KQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in skill file.");let j=O6(Q.name,"name",!1)??Z.trim();if(!j)throw Error("Missing skill name.");return{name:j,description:O6(Q.description,"description",!1),disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function AQ($,Z){let{data:Q,body:W,parseError:J}=KQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in rule file.");let Y=O6(Q.name,"name",!1)??Z.trim();if(!Y)throw Error("Missing rule name.");return{name:Y,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function fQ($,Z){let{data:Q,body:W,parseError:J}=KQ($);if(J)throw Error(`Failed to parse YAML frontmatter: ${J}`);let X=W.trim();if(!X)throw Error("Missing instructions body in workflow file.");let Y=O6(Q.name,"name",!1)??Z.trim();if(!Y)throw Error("Missing workflow name.");return{name:Y,disabled:f2(Q.disabled,"disabled")??(f2(Q.enabled,"enabled")===!1?!0:void 0),instructions:X,frontmatter:Q}}function UQ($){return oD($)}function DQ($){return sD($)}function LQ($){return tD($)}async function iX($){if(F1($)===".cline"){let Z=await GQ($);return(await Promise.all(Z.map((W)=>iX(E0(W,VQ))))).flat()}try{let Z=await jQ($,{withFileTypes:!0}),Q=[];for(let W of Z){if(W.isFile()&&W.name===_6){Q.push({directoryPath:$,fileName:W.name,filePath:E0($,W.name)});continue}let J=E0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await YQ(J).then((Y)=>Y.isDirectory()).catch((Y)=>{if(A2(Y))return!1;throw Y}))Q.push({directoryPath:J,fileName:_6,filePath:E0(J,_6)})}return Q}catch(Z){if(A2(Z))return[];throw Z}}async function q6($){if(F1($)===".cline"){let Z=await GQ($);return(await Promise.all(Z.map((W)=>q6(E0(W,"rules.md"))))).flat()}try{if((await YQ($)).isFile())return[{directoryPath:nD($),fileName:F1($),filePath:$}]}catch(Z){if(!A2(Z))throw Z}try{let Q=(await jQ($,{withFileTypes:!0})).filter((J)=>J.isFile()&&T6(J.name)).map((J)=>({directoryPath:$,fileName:J.name,filePath:E0($,J.name)})),W=E0($,"AGENTS.md");try{if((await YQ(W)).isFile()){if(!Q.some((Y)=>Y.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return Q}catch(Z){if(A2(Z))return[];throw Z}}async function JL($){if(F1($)===".cline"){let Z=await GQ($);return(await Promise.all(Z.map((W)=>q6(E0(W,HQ))))).flat()}return q6($)}function _Q($){let Z=QL($),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?rX([...Z,Q]):Z,discoverFiles:iX,includeFile:(W)=>W===_6,parseFile:(W)=>FQ(W.content,F1(W.directoryPath)),resolveId:(W)=>BQ(W.name)}}function zQ($){let Z=$?.directories??DQ($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...Z,Q]:Z,discoverFiles:q6,includeFile:(W,J)=>W===".clinerules"||T6(W)||T6(J),parseFile:(W)=>AQ(W.content,WL(W,$?.workspacePath)),resolveId:(W)=>BQ(W.name)}}function TQ($){let Z=$?.directories??LQ($?.workspacePath),Q=$?.workspacePath?E0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...Z,Q]:Z,discoverFiles:JL,includeFile:(W)=>T6(W),parseFile:(W)=>fQ(W.content,F1(W.filePath,z6(W.filePath))),resolveId:(W)=>BQ(W.name)}}function nX($){let Z=[_Q($?.skills),zQ($?.rules),TQ($?.workflows)];return new j8(Z,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as aX}from"@cline/shared";function XL($,Z){if($.description?.trim())return aX($.description,".");if(Z==="workflow")return;return aX($.instructions,".")}function YL($){return $.disabled!==!0}function sX($,Z){return[...$.getSnapshot(Z).entries()].map(([Q,W])=>({id:Q,record:W})).filter(({record:Q})=>YL(Q.item)).map(({id:Q,record:W})=>({id:Q,name:W.item.name,instructions:W.item.instructions,description:XL(W.item,Z),kind:Z})).sort((Q,W)=>Q.name.localeCompare(W.name))}function F8($){let Z=new Map;for(let Q of[...sX($,"workflow"),...sX($,"skill")])if(!Z.has(Q.name))Z.set(Q.name,Q);return[...Z.values()].sort((Q,W)=>Q.name.localeCompare(W.name))}function oX($,Z){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let W=Q[1];if(!W)return $;let J=W.length+1,X=$.slice(J),Y=F8(Z).find((j)=>j.name===W);return Y?`${Y.instructions}${X}`:$}function tX($){return $.disabled!==!0}function M6($){if($.length===0)return"";return`
47
47
 
48
48
  # Rules
49
49
  ${$.map((Q)=>`## ${Q.name}
@@ -51,17 +51,17 @@ ${Q.instructions}`).join(`
51
51
 
52
52
  `)}`}function R6($,Z){let Q=$?.trim(),W=Z?.trim();if(Q&&W)return`${Q}
53
53
 
54
- ${W}`;return Q||W||void 0}function JL($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(tX).sort((Q,W)=>Q.name.localeCompare(W.name))}function eX($){return M6(JL($))}import{validateWithZod as Uv,zodToJsonSchema as Dv}from"@cline/shared";var D0={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"},U2=[D0.READ_FILES,D0.SEARCH_CODEBASE,D0.RUN_COMMANDS,D0.FETCH_WEB_CONTENT,D0.APPLY_PATCH,D0.EDITOR,D0.SKILLS,D0.ASK,D0.SUBMIT_AND_EXIT];G0();import{createTool as m1,validateWithZod as v1,zodToJsonSchema as A1}from"@cline/shared";var $Y="__clineInternalTelemetry";function ZY($){let Z=$?.__clineInternalTelemetry;return Z&&typeof Z==="object"&&"capture"in Z&&typeof Z.capture==="function"?Z:void 0}import{spawn as FY}from"node:child_process";import{StringDecoder as jL}from"node:string_decoder";import{getDefaultShell as VL,getShellArgs as HL}from"@cline/shared";import{validateWithZod as XL}from"@cline/shared";import{z as q}from"zod";var g1=6000,A8=q.string().describe("The absolute file path of a text file to read content from"),QY=q.object({start_line:q.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:q.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"),x1=q.object({path:A8,start_line:QY.shape.start_line,end_line:QY.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),E6=q.object({files:q.array(x1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. 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.")}),WY=q.union([E6,x1,q.array(x1),q.array(q.string()),q.string(),q.object({files:q.array(q.union([A8,x1]))}),q.object({files:x1}),q.object({files:A8}),q.object({file_paths:q.array(A8)}),q.object({file_paths:q.string()}),q.object({paths:q.array(q.union([A8,x1]))}),q.object({paths:x1}),q.object({paths:q.string()})]),N6=q.object({queries:q.array(q.string()).describe("Array of regex search queries to execute")}),JY=q.union([N6,q.array(q.string()),q.string(),q.object({queries:q.string()})]),TQ=q.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${g1*2} characters) to avoid timeouts.`),f8=q.object({command:q.string().min(1).describe("The executable to run directly without shell parsing."),args:q.array(q.string()).optional().describe("Optional argv list passed directly to the executable.")}),XY=q.union([TQ,f8]),w6=q.object({commands:q.array(XY).describe("Array of commands to execute. Prefer structured { command, args } entries for portability; plain strings are still supported and are interpreted by the active shell.")}),YY=q.union([w6,q.object({commands:XY}),q.array(f8),f8,q.object({command:TQ}),q.object({cmd:TQ}),q.array(q.string()),q.string()]),jY=q.object({url:q.string().describe("The URL to fetch"),prompt:q.string().min(2).describe("Analysis prompt for the fetched content")}),C6=q.object({requests:q.array(jY).describe("Array of the URLs for the web fetch requests")}),P6=q.object({path:q.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:q.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 ${g1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:q.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 ${g1} 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:q.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."),S6=q.object({input:q.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."),VY=q.union([S6,q.string()]),b6=q.object({skill:q.string().min(1).describe("Name of the skill to execute."),args:q.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),y6=q.object({question:q.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:q.array(q.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),h6=q.object({summary:q.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:q.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.
54
+ ${W}`;return Q||W||void 0}function jL($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(tX).sort((Q,W)=>Q.name.localeCompare(W.name))}function eX($){return M6(jL($))}import{validateWithZod as zv,zodToJsonSchema as Tv}from"@cline/shared";var L0={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"},U2=[L0.READ_FILES,L0.SEARCH_CODEBASE,L0.RUN_COMMANDS,L0.FETCH_WEB_CONTENT,L0.APPLY_PATCH,L0.EDITOR,L0.SKILLS,L0.ASK,L0.SUBMIT_AND_EXIT];G0();import{createTool as m1,validateWithZod as v1,zodToJsonSchema as f1}from"@cline/shared";var $Y="__clineInternalTelemetry";function ZY($){let Z=$?.__clineInternalTelemetry;return Z&&typeof Z==="object"&&"capture"in Z&&typeof Z.capture==="function"?Z:void 0}import{spawn as FY}from"node:child_process";import{StringDecoder as GL}from"node:string_decoder";import{getDefaultShell as KL,getShellArgs as FL}from"@cline/shared";import{validateWithZod as HL}from"@cline/shared";import{z as O}from"zod";var g1=6000,A8=O.string().describe("The absolute file path of a text file to read content from"),QY=O.object({start_line:O.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:O.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"),x1=O.object({path:A8,start_line:QY.shape.start_line,end_line:QY.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),N6=O.object({files:O.array(x1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. 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.")}),WY=O.union([N6,x1,O.array(x1),O.array(O.string()),O.string(),O.object({files:O.array(O.union([A8,x1]))}),O.object({files:x1}),O.object({files:A8}),O.object({file_paths:O.array(A8)}),O.object({file_paths:O.string()}),O.object({paths:O.array(O.union([A8,x1]))}),O.object({paths:x1}),O.object({paths:O.string()})]),w6=O.object({queries:O.array(O.string()).describe("Array of regex search queries to execute")}),JY=O.union([w6,O.array(O.string()),O.string(),O.object({queries:O.string()})]),E6=O.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${g1*2} characters) to avoid timeouts.`),f8=O.object({command:O.string().min(1).describe("The executable to run directly without shell parsing."),args:O.array(O.string()).optional().describe("Optional argv list passed directly to the executable.")}),XY=O.union([E6,f8]),C6=O.object({commands:O.array(E6).describe("Array of complete shell command strings to execute.")}),VL=O.object({commands:O.array(XY)}),YY=O.union([C6,VL,O.object({commands:XY}),O.array(f8),f8,O.object({command:E6}),O.object({cmd:E6}),O.array(O.string()),O.string()]),jY=O.object({url:O.string().describe("The URL to fetch"),prompt:O.string().min(2).describe("Analysis prompt for the fetched content")}),P6=O.object({requests:O.array(jY).describe("Array of the URLs for the web fetch requests")}),S6=O.object({path:O.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:O.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 ${g1} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:O.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 ${g1} 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:O.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."),b6=O.object({input:O.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."),VY=O.union([b6,O.string()]),y6=O.object({skill:O.string().min(1).describe("Name of the skill to execute."),args:O.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),h6=O.object({question:O.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:O.array(O.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),k6=O.object({summary:O.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:O.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.
55
55
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
56
- 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 T$($){if($ instanceof Error)return $.message;return String($)}function HY($){if(typeof $.old_text==="string"&&$.old_text.length>g1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${g1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>g1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${g1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class D2 extends Error{timeoutMs;constructor($,Z){super($);this.name="TimeoutError",this.timeoutMs=Z}}function F1($,Z,Q){return Promise.race([$,new Promise((W,J)=>{setTimeout(()=>J(new D2(Q,Z)),Z)})])}function k6($){let{path:Z,start_line:Q,end_line:W}=$;if(Q==null&&W==null)return Z;return`${Z}:${Q??1}-${W??"EOF"}`}function BY($){let{start_line:Z,end_line:Q}=$;if(Z==null||Q==null||Z<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${Z}, end_line: ${Q})`}function GY($){let Z=XL(YY,$);if(typeof Z==="string")return[Z];if(Array.isArray(Z))return Z;if("commands"in Z)return Array.isArray(Z.commands)?Z.commands:[Z.commands];if("command"in Z)return"args"in Z?[Z]:[Z.command];if("cmd"in Z)return[Z.cmd];return[Z]}function YL($){if(typeof $==="string")return $;let Z=$.args??[];if(Z.length===0)return $.command;let Q=Z.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${Q.join(" ")}`}var OQ=200;function KY($){let Z=YL($);if(Z.length<=OQ)return Z;let Q=Z.length-OQ;return`${Z.slice(0,OQ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var O$=48000;function U8($,Z={}){let Q=Z.maxChars??48000,W=Z.totalChars??$.length;if($.length<=Q&&W<=Q)return $;let J=Math.ceil(Q/2),X=Math.max(1,Q-J);return`${$.slice(0,J)}
56
+ 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 O$($){if($ instanceof Error)return $.message;return String($)}function HY($){if(typeof $.old_text==="string"&&$.old_text.length>g1)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${g1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>g1)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${g1}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class D2 extends Error{timeoutMs;constructor($,Z){super($);this.name="TimeoutError",this.timeoutMs=Z}}function A1($,Z,Q){return Promise.race([$,new Promise((W,J)=>{setTimeout(()=>J(new D2(Q,Z)),Z)})])}function I6($){let{path:Z,start_line:Q,end_line:W}=$;if(Q==null&&W==null)return Z;return`${Z}:${Q??1}-${W??"EOF"}`}function BY($){let{start_line:Z,end_line:Q}=$;if(Z==null||Q==null||Z<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${Z}, end_line: ${Q})`}function GY($){let Z=HL(YY,$);if(typeof Z==="string")return[Z];if(Array.isArray(Z))return Z;if("commands"in Z)return Array.isArray(Z.commands)?Z.commands:[Z.commands];if("command"in Z)return"args"in Z?[Z]:[Z.command];if("cmd"in Z)return[Z.cmd];return[Z]}function BL($){if(typeof $==="string")return $;let Z=$.args??[];if(Z.length===0)return $.command;let Q=Z.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${Q.join(" ")}`}var OQ=200;function KY($){let Z=BL($);if(Z.length<=OQ)return Z;let Q=Z.length-OQ;return`${Z.slice(0,OQ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var q$=48000;function U8($,Z={}){let Q=Z.maxChars??48000,W=Z.totalChars??$.length;if($.length<=Q&&W<=Q)return $;let J=Math.ceil(Q/2),X=Math.max(1,Q-J);return`${$.slice(0,J)}
57
57
  [... output truncated: ${W} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
58
- `+$.slice(-X)}var L2=2000,qQ=2000,I6=48000,_2=48000;class x6 extends Error{exitCode;output;constructor($,Z){super(`Command exited with code ${$}`);this.exitCode=$;this.output=Z;this.name="CommandExitError"}}function AY($){let Z=Math.ceil($/2),Q=Math.max(1,$-Z),W=new jL("utf8"),J="",X="",Y=0,j=(V)=>{if(!V)return;Y+=V.length;let H=Z-J.length;if(H>0){J+=V.slice(0,H),X=(X+V.slice(H)).slice(-Q);return}X=(X+V).slice(-Q)};return{append(V){j(W.write(V))},snapshot(){return j(W.end()),{text:J+X,totalChars:Y,dropped:Y>J.length+X.length}}}}function BL($,Z,Q,W,J){return new Promise((X,Y)=>{let j=process.platform==="win32",V=FY($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!j,windowsHide:!0}),H=V.pid,B=AY(W),G=AY(W),K=!1,F=!1,A=(O)=>{if(F)return;F=!0,O()},L=()=>{if(!H)return;if(j){FY("taskkill",["/pid",String(H),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-H,"SIGKILL")}catch{V.kill("SIGKILL")}},f=(O)=>{K=!0,L(),A(()=>Y(O))},D=setTimeout(()=>f(new D2(`Command timed out after ${Q}ms`,Q)),Q),U=()=>f(Error("Command was aborted"));if(Z.signal)Z.signal.addEventListener("abort",U);let T=()=>{clearTimeout(D),Z.signal?.removeEventListener("abort",U)};V.stdout?.on("data",(O)=>{B.append(O)}),V.stderr?.on("data",(O)=>{G.append(O)}),V.on("close",(O)=>{if(T(),K)return;let z=B.snapshot(),_=G.snapshot();if(O!==0){let M=O??1,E=J?z.text+(_.text?`
58
+ `+$.slice(-X)}var L2=2000,qQ=2000,x6=48000,_2=48000;class g6 extends Error{exitCode;output;constructor($,Z){super(`Command exited with code ${$}`);this.exitCode=$;this.output=Z;this.name="CommandExitError"}}function AY($){let Z=Math.ceil($/2),Q=Math.max(1,$-Z),W=new GL("utf8"),J="",X="",Y=0,j=(V)=>{if(!V)return;Y+=V.length;let H=Z-J.length;if(H>0){J+=V.slice(0,H),X=(X+V.slice(H)).slice(-Q);return}X=(X+V).slice(-Q)};return{append(V){j(W.write(V))},snapshot(){return j(W.end()),{text:J+X,totalChars:Y,dropped:Y>J.length+X.length}}}}function AL($,Z,Q,W,J){return new Promise((X,Y)=>{let j=process.platform==="win32",V=FY($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!j,windowsHide:!0}),H=V.pid,B=AY(W),G=AY(W),K=!1,F=!1,A=(q)=>{if(F)return;F=!0,q()},L=()=>{if(!H)return;if(j){FY("taskkill",["/pid",String(H),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-H,"SIGKILL")}catch{V.kill("SIGKILL")}},f=(q)=>{K=!0,L(),A(()=>Y(q))},D=setTimeout(()=>f(new D2(`Command timed out after ${Q}ms`,Q)),Q),U=()=>f(Error("Command was aborted"));if(Z.signal)Z.signal.addEventListener("abort",U);let T=()=>{clearTimeout(D),Z.signal?.removeEventListener("abort",U)};V.stdout?.on("data",(q)=>{B.append(q)}),V.stderr?.on("data",(q)=>{G.append(q)}),V.on("close",(q)=>{if(T(),K)return;let z=B.snapshot(),_=G.snapshot();if(q!==0){let M=q??1,E=J?z.text+(_.text?`
59
59
  [stderr]
60
60
  ${_.text}`:""):z.text,P=z.dropped||J&&_.dropped,c=J?z.totalChars+_.totalChars:z.totalChars;if(P||E.length>W)E=U8(E,{maxChars:W,totalChars:c});let n=E.length>0?`[Command exited with code ${M}]
61
- ${E}`:`[Command exited with code ${M}]`;A(()=>Y(new x6(M,n)))}else{let M=J?z.text+(_.text?`
61
+ ${E}`:`[Command exited with code ${M}]`;A(()=>Y(new g6(M,n)))}else{let M=J?z.text+(_.text?`
62
62
  [stderr]
63
- ${_.text}`:""):z.text;if(z.dropped||J&&_.dropped||M.length>W){let P=J?z.totalChars+_.totalChars:z.totalChars;M=U8(M,{maxChars:W,totalChars:P})}A(()=>X(M))}}),V.on("error",(O)=>{T(),A(()=>Y(Error(`Failed to execute command: ${O.message}`)))})})}function D8($={}){let{shell:Z=VL(process.platform),timeoutMs:Q=30000,env:W={},combineOutput:J=!0}=$,X=$.maxOutputChars??$.maxOutputBytes??O$;return(Y,j,V)=>{let H=typeof Y!=="string";return BL({executable:H?Y.command:Z,args:H?Y.args??[]:HL(Z,Y),cwd:j,env:W},V,Q,X,J)}}function fY($,Z){let Q=$.metadata?.[Z];return typeof Q==="string"?Q:void 0}function GL($,Z){TJ(ZY($.metadata),{tool_name:"run_commands",effective_timeout_ms:Z.effectiveTimeoutMs,timeout_source:Z.timeoutSource,command_count:Z.commandCount,duration_ms:Z.durationMs,ulid:$.sessionId,mode:fY($,"mode"),source:fY($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function KL($){let Z=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return Z?.[1]??Z?.[2]??Z?.[3]}function FL($){let Z=[];for(let Q=0;Q<$.length;Q+=1){let W=$[Q],J=KL(W);if(!J){Z.push(W);continue}let X=$.findIndex((j,V)=>V>Q&&j.trim()===J);if(X===-1){Z.push(W);continue}let Y=[W];while(Q<X){Q+=1;let j=$[Q];Y.push(j)}Z.push(Y.join(`
64
- `))}return Z}function AL($){let Z=[],Q=[],W=()=>{if(Q.length>0)Z.push(...FL(Q)),Q=[]};for(let J of $){if(typeof J==="string"){Q.push(J);continue}W(),Z.push(J)}return W(),Z}async function fL($,Z){let{executor:Q,cwd:W,context:J,timeoutMs:X,timeoutSource:Y}=Z;return Promise.all($.map(async(j)=>{let V=Date.now(),H=KY(j);try{let B=await F1(Q(j,W,J),X,`Command timed out after ${X}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof D2)GL(J,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Y,commandCount:$.length,durationMs:Date.now()-V});if(B instanceof x6)return{query:H,result:B.output,error:B.message,success:!1};let G=T$(B);return{query:H,result:"",error:`Command failed: ${G}`,success:!1}}}))}function DY($,Z={}){let Q=Z.fileReadTimeoutMs??1e4;return m1({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. 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 ${L2} lines / ~${Math.round(I6/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:A1(E6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,J)=>{let X=v1(WY,W),Y;if(typeof X==="string")Y=[{path:X}];else if(Array.isArray(X))Y=X.map((j)=>typeof j==="string"?{path:j}:j);else if("files"in X)Y=(Array.isArray(X.files)?X.files:[X.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in X)Y=(Array.isArray(X.file_paths)?X.file_paths:[X.file_paths]).map((V)=>({path:V}));else if("paths"in X)Y=(Array.isArray(X.paths)?X.paths:[X.paths]).map((V)=>typeof V==="string"?{path:V}:V);else Y=[X];return Promise.all(Y.map(async(j)=>{let V=BY(j);if(V)return{query:k6(j),result:"",error:`Invalid file range: ${V}`,success:!1};try{let H=await F1($(j,J),Q,`File read timed out after ${Q}ms`);return{query:k6(j),result:H,success:!0}}catch(H){let B=T$(H);return{query:k6(j),result:"",error:`Error reading file: ${B}`,success:!1}}}))}})}function LY($,Z={}){let Q=Z.searchTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({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(_2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:A1(N6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(J,X)=>{let Y=v1(JY,J),j=Array.isArray(Y)?Y:typeof Y==="object"?Array.isArray(Y.queries)?Y.queries:[Y.queries]:[Y];return Promise.all(j.map(async(V)=>{try{let H=await F1($(V,W,X),Q,`Search timed out after ${Q}ms`);return{query:V,result:H,success:!0}}catch(H){let B=T$(H);return{query:V,result:"",error:`Search failed: ${B}`,success:!1}}}))}})}var UY="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 MQ($,Z={}){let Q=Z.bashTimeoutMs??30000,W=Z.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=Z.cwd??process.cwd(),X=process.platform==="win32";return m1({name:"run_commands",description:X?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+UY+`Output beyond ~${Math.round(O$/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. 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. "+UY+`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(O$/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:A1(w6),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(Y,j)=>{let V=AL(GY(Y));return fL(V,{executor:$,cwd:J,context:j,timeoutMs:Q,timeoutSource:W})}})}function _Y($,Z={}){let Q=Z.webFetchTimeoutMs??30000;return m1({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:A1(C6),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(W,J)=>{let X=v1(C6,W);return Promise.all(X.requests.map(async(Y)=>{try{let j=await F1($(Y.url,Y.prompt,J),Q,`Web fetch timed out after ${Q}ms`);return{query:Y.url,result:j,success:!0}}catch(j){let V=T$(j);return{query:Y.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var UL=`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:
63
+ ${_.text}`:""):z.text;if(z.dropped||J&&_.dropped||M.length>W){let P=J?z.totalChars+_.totalChars:z.totalChars;M=U8(M,{maxChars:W,totalChars:P})}A(()=>X(M))}}),V.on("error",(q)=>{T(),A(()=>Y(Error(`Failed to execute command: ${q.message}`)))})})}function D8($={}){let{shell:Z=KL(process.platform),timeoutMs:Q=30000,env:W={},combineOutput:J=!0}=$,X=$.maxOutputChars??$.maxOutputBytes??q$;return(Y,j,V)=>{let H=typeof Y!=="string";return AL({executable:H?Y.command:Z,args:H?Y.args??[]:FL(Z,Y),cwd:j,env:W},V,Q,X,J)}}function fY($,Z){let Q=$.metadata?.[Z];return typeof Q==="string"?Q:void 0}function fL($,Z){TJ(ZY($.metadata),{tool_name:"run_commands",effective_timeout_ms:Z.effectiveTimeoutMs,timeout_source:Z.timeoutSource,command_count:Z.commandCount,duration_ms:Z.durationMs,ulid:$.sessionId,mode:fY($,"mode"),source:fY($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function UL($){let Z=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return Z?.[1]??Z?.[2]??Z?.[3]}function DL($){let Z=[];for(let Q=0;Q<$.length;Q+=1){let W=$[Q],J=UL(W);if(!J){Z.push(W);continue}let X=$.findIndex((j,V)=>V>Q&&j.trim()===J);if(X===-1){Z.push(W);continue}let Y=[W];while(Q<X){Q+=1;let j=$[Q];Y.push(j)}Z.push(Y.join(`
64
+ `))}return Z}function LL($){let Z=[],Q=[],W=()=>{if(Q.length>0)Z.push(...DL(Q)),Q=[]};for(let J of $){if(typeof J==="string"){Q.push(J);continue}W(),Z.push(J)}return W(),Z}async function _L($,Z){let{executor:Q,cwd:W,context:J,timeoutMs:X,timeoutSource:Y}=Z;return Promise.all($.map(async(j)=>{let V=Date.now(),H=KY(j);try{let B=await A1(Q(j,W,J),X,`Command timed out after ${X}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof D2)fL(J,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Y,commandCount:$.length,durationMs:Date.now()-V});if(B instanceof g6)return{query:H,result:B.output,error:B.message,success:!1};let G=O$(B);return{query:H,result:"",error:`Command failed: ${G}`,success:!1}}}))}function DY($,Z={}){let Q=Z.fileReadTimeoutMs??1e4;return m1({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. 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 ${L2} lines / ~${Math.round(x6/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:f1(N6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,J)=>{let X=v1(WY,W),Y;if(typeof X==="string")Y=[{path:X}];else if(Array.isArray(X))Y=X.map((j)=>typeof j==="string"?{path:j}:j);else if("files"in X)Y=(Array.isArray(X.files)?X.files:[X.files]).map((V)=>typeof V==="string"?{path:V}:V);else if("file_paths"in X)Y=(Array.isArray(X.file_paths)?X.file_paths:[X.file_paths]).map((V)=>({path:V}));else if("paths"in X)Y=(Array.isArray(X.paths)?X.paths:[X.paths]).map((V)=>typeof V==="string"?{path:V}:V);else Y=[X];return Promise.all(Y.map(async(j)=>{let V=BY(j);if(V)return{query:I6(j),result:"",error:`Invalid file range: ${V}`,success:!1};try{let H=await A1($(j,J),Q,`File read timed out after ${Q}ms`);return{query:I6(j),result:H,success:!0}}catch(H){let B=O$(H);return{query:I6(j),result:"",error:`Error reading file: ${B}`,success:!1}}}))}})}function LY($,Z={}){let Q=Z.searchTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({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(_2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:f1(w6),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(J,X)=>{let Y=v1(JY,J),j=Array.isArray(Y)?Y:typeof Y==="object"?Array.isArray(Y.queries)?Y.queries:[Y.queries]:[Y];return Promise.all(j.map(async(V)=>{try{let H=await A1($(V,W,X),Q,`Search timed out after ${Q}ms`);return{query:V,result:H,success:!0}}catch(H){let B=O$(H);return{query:V,result:"",error:`Search failed: ${B}`,success:!1}}}))}})}var UY="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 MQ($,Z={}){let Q=Z.bashTimeoutMs??30000,W=Z.bashTimeoutMs===void 0?"default_setting":"configured_setting",J=Z.cwd??process.cwd(),X=process.platform==="win32";return m1({name:"run_commands",description:X?"Run non-interactive shell commands from the root of the workspace in Windows environment. "+UY+`Output beyond ~${Math.round(q$/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. "+UY+`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(q$/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:f1(C6),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(Y,j)=>{let V=LL(GY(Y));return _L(V,{executor:$,cwd:J,context:j,timeoutMs:Q,timeoutSource:W})}})}function _Y($,Z={}){let Q=Z.webFetchTimeoutMs??30000;return m1({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:f1(P6),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(W,J)=>{let X=v1(P6,W);return Promise.all(X.requests.map(async(Y)=>{try{let j=await A1($(Y.url,Y.prompt,J),Q,`Web fetch timed out after ${Q}ms`);return{query:Y.url,result:j,success:!0}}catch(j){let V=O$(j);return{query:Y.url,result:"",error:`Error fetching web content: ${V}`,success:!1}}}))}})}var zL=`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:
65
65
 
66
66
  *** Begin Patch
67
67
  *** Update File: path/to/file.ts
@@ -97,48 +97,48 @@ Example:
97
97
  </div>
98
98
  );
99
99
  }
100
- *** End Patch`;function zY($,Z={}){let Q=Z.applyPatchTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({name:"apply_patch",description:UL,inputSchema:A1(S6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(J,X)=>{let Y=v1(VY,J),j=typeof Y==="string"?Y:Y.input;try{return{query:"apply_patch",result:await F1($({input:j},W,X),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${T$(V)}`,success:!1}}}})}function TY($,Z={}){let Q=Z.editorTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({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:A1(P6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(J,X)=>{let Y=v1(P6,J),j=Y.insert_line==null?"edit":"insert",V=HY(Y);if(V)return{query:`${j}:${Y.path}`,result:"",error:V,success:!1};try{let H=await F1($(Y,W,X),Q,`Editor operation timed out after ${Q}ms`);return{query:`${j}:${Y.path}`,result:H,success:!0}}catch(H){let B=T$(H);return{query:`${j}:${Y.path}`,result:"",error:`Editor operation failed: ${B}`,success:!1}}}})}function z2($,Z={}){let Q=Z.skillsTimeoutMs??15000,W='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=m1({name:"skills",description:W,inputSchema:A1(b6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let j=v1(b6,X);return F1($(j.skill,j.args||void 0,Y),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(J,"description",{get(){let X=$.configuredSkills?.filter((Y)=>!Y.disabled).map((Y)=>Y.name);if(X&&X.length>0)return`${W} Available skills: ${X.join(", ")}.`;return W},enumerable:!0,configurable:!0}),J}function OY($){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:A1(y6),retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let W=v1(y6,Z);return $(W.question,W.options,Q)}}}function qY($,Z={}){let Q=Z.submitTimeoutMs??15000;return m1({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:A1(h6),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,J)=>{let X=v1(h6,W);return F1($(X.summary,X.verified,J),Q,`submit_and_exit timed out after ${Q}ms`)}})}function T2($){let{executors:Z,enableReadFiles:Q=!0,enableSearch:W=!0,enableBash:J=!0,enableWebFetch:X=!0,enableApplyPatch:Y=!1,enableEditor:j=!0,enableSkills:V=!0,enableAskQuestion:H=!0,enableSubmitAndExit:B=!1,...G}=$,K=[];if(Q&&Z.readFile)K.push(DY(Z.readFile,G));if(W&&Z.search)K.push(LY(Z.search,G));if(J&&Z.bash)K.push(MQ(Z.bash,G));if(X&&Z.webFetch)K.push(_Y(Z.webFetch,G));if(j&&Z.editor)K.push(TY(Z.editor,G));else if(Y&&Z.applyPatch)K.push(zY(Z.applyPatch,G));if(V&&Z.skills)K.push(z2(Z.skills,G));let F=B?Z.submit:void 0;if(H&&Z.askQuestion&&!F)K.push(OY(Z.askQuestion));if(F)K.push(qY(F,G));return K}import*as y0 from"node:fs/promises";import*as h0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},RY=["%%bash","apply_patch","EOF","```"];class J0 extends Error{constructor($){super($);this.name="DiffError"}}function b0($){let Z={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>Z[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class RQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,Z){this.lines=$;this.currentFiles=Z}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(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new J0(`Unknown line while parsing: ${$}`)}checkDuplicate($,Z){if($ in this.patch.actions)throw new J0(`Duplicate ${Z} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let Z=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new J0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",W=this.parseUpdateFile(Q,$);W.movePath=Z,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,Z){let Q={type:"update",chunks:[]},W=$.split(`
100
+ *** End Patch`;function zY($,Z={}){let Q=Z.applyPatchTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({name:"apply_patch",description:zL,inputSchema:f1(b6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(J,X)=>{let Y=v1(VY,J),j=typeof Y==="string"?Y:Y.input;try{return{query:"apply_patch",result:await A1($({input:j},W,X),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(V){return{query:"apply_patch",result:"",error:`apply_patch failed: ${O$(V)}`,success:!1}}}})}function TY($,Z={}){let Q=Z.editorTimeoutMs??30000,W=Z.cwd??process.cwd();return m1({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:f1(S6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(J,X)=>{let Y=v1(S6,J),j=Y.insert_line==null?"edit":"insert",V=HY(Y);if(V)return{query:`${j}:${Y.path}`,result:"",error:V,success:!1};try{let H=await A1($(Y,W,X),Q,`Editor operation timed out after ${Q}ms`);return{query:`${j}:${Y.path}`,result:H,success:!0}}catch(H){let B=O$(H);return{query:`${j}:${Y.path}`,result:"",error:`Editor operation failed: ${B}`,success:!1}}}})}function z2($,Z={}){let Q=Z.skillsTimeoutMs??15000,W='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=m1({name:"skills",description:W,inputSchema:f1(y6),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(X,Y)=>{let j=v1(y6,X);return A1($(j.skill,j.args||void 0,Y),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(J,"description",{get(){let X=$.configuredSkills?.filter((Y)=>!Y.disabled).map((Y)=>Y.name);if(X&&X.length>0)return`${W} Available skills: ${X.join(", ")}.`;return W},enumerable:!0,configurable:!0}),J}function OY($){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:f1(h6),retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let W=v1(h6,Z);return $(W.question,W.options,Q)}}}function qY($,Z={}){let Q=Z.submitTimeoutMs??15000;return m1({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:f1(k6),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,J)=>{let X=v1(k6,W);return A1($(X.summary,X.verified,J),Q,`submit_and_exit timed out after ${Q}ms`)}})}function T2($){let{executors:Z,enableReadFiles:Q=!0,enableSearch:W=!0,enableBash:J=!0,enableWebFetch:X=!0,enableApplyPatch:Y=!1,enableEditor:j=!0,enableSkills:V=!0,enableAskQuestion:H=!0,enableSubmitAndExit:B=!1,...G}=$,K=[];if(Q&&Z.readFile)K.push(DY(Z.readFile,G));if(W&&Z.search)K.push(LY(Z.search,G));if(J&&Z.bash)K.push(MQ(Z.bash,G));if(X&&Z.webFetch)K.push(_Y(Z.webFetch,G));if(j&&Z.editor)K.push(TY(Z.editor,G));else if(Y&&Z.applyPatch)K.push(zY(Z.applyPatch,G));if(V&&Z.skills)K.push(z2(Z.skills,G));let F=B?Z.submit:void 0;if(H&&Z.askQuestion&&!F)K.push(OY(Z.askQuestion));if(F)K.push(qY(F,G));return K}import*as y0 from"node:fs/promises";import*as h0 from"node:path";var v={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},RY=["%%bash","apply_patch","EOF","```"];class J0 extends Error{constructor($){super($);this.name="DiffError"}}function b0($){let Z={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>Z[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class RQ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,Z){this.lines=$;this.currentFiles=Z}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(v.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(v.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(v.UPDATE)){this.parseUpdate($.substring(v.UPDATE.length).trim());return}if($?.startsWith(v.DELETE)){this.parseDelete($.substring(v.DELETE.length).trim());return}if($?.startsWith(v.ADD)){this.parseAdd($.substring(v.ADD.length).trim());return}throw new J0(`Unknown line while parsing: ${$}`)}checkDuplicate($,Z){if($ in this.patch.actions)throw new J0(`Duplicate ${Z} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let Z=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new J0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",W=this.parseUpdateFile(Q,$);W.movePath=Z,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,Z){let Q={type:"update",chunks:[]},W=$.split(`
101
101
  `),J=0,X=[v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(!X.some((Y)=>this.lines[this.index]?.startsWith(Y.trim()))){let Y=this.lines[this.index],j=Y?.startsWith("@@ ")?Y.substring(3):void 0;if(j!==void 0||(Y==="@@"?Y:void 0)!==void 0)this.index++;else if(J!==0)throw new J0(`Invalid Line:
102
- ${this.lines[this.index]}`);if(j?.trim()){let f=b0(j.trim());for(let D=J;D<W.length;D++){let U=W[D];if(U&&(b0(U)===f||b0(U.trim())===f)){if(J=D+1,b0(U.trim())===f&&b0(U)!==f)this.fuzz++;break}}}let[H,B,G,K]=_L(this.lines,this.index),[F,A,L]=LL(W,H,J,K);if(F===-1){let f=H.join(`
102
+ ${this.lines[this.index]}`);if(j?.trim()){let f=b0(j.trim());for(let D=J;D<W.length;D++){let U=W[D];if(U&&(b0(U)===f||b0(U.trim())===f)){if(J=D+1,b0(U.trim())===f&&b0(U)!==f)this.fuzz++;break}}}let[H,B,G,K]=qL(this.lines,this.index),[F,A,L]=OL(W,H,J,K);if(F===-1){let f=H.join(`
103
103
  `);this.addWarning({path:this.currentPath||Z,chunkIndex:Q.chunks.length,message:`Could not find matching context (similarity: ${L.toFixed(2)}). Chunk skipped.`,context:f.length>200?`${f.substring(0,200)}...`:f}),this.index=G}else{this.fuzz+=A;for(let f of B)f.origIndex+=F,Q.chunks.push(f);J=F+H.length,this.index=G}}return Q}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new J0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new J0(`Add File Error: File already exists: ${$}`);this.index++;let Z=[],Q=[v.END,v.UPDATE,v.DELETE,v.ADD];while(this.hasMoreLines()&&!Q.some((W)=>this.lines[this.index]?.startsWith(W.trim()))){let W=this.lines[this.index++];if(W===void 0)break;if(!W.startsWith("+"))throw new J0(`Invalid Add File line (missing '+'): ${W}`);Z.push(W.substring(1))}this.patch.actions[$]={type:"add",newFile:Z.join(`
104
- `),chunks:[]}}}function MY($,Z){let Q=$.length>Z.length?$:Z,W=$.length>Z.length?Z:$;if(Q.length===0)return 1;let J=DL(W,Q);return(Q.length-J)/Q.length}function DL($,Z){let Q=Z.length+1,W=$.length+1,J=Array(Q*W).fill(0),X=(j,V)=>J[j*W+V]??0,Y=(j,V,H)=>{J[j*W+V]=H};for(let j=0;j<=Z.length;j++)Y(j,0,j);for(let j=0;j<=$.length;j++)Y(0,j,j);for(let j=1;j<=Z.length;j++)for(let V=1;V<=$.length;V++)if(Z[j-1]===$[V-1])Y(j,V,X(j-1,V-1));else Y(j,V,1+Math.min(X(j-1,V-1),X(j,V-1),X(j-1,V)));return X(Z.length,$.length)}function LL($,Z,Q,W){if(Z.length===0)return[Q,0,1];let J=0,X=(Y)=>{let j=b0(Z.join(`
104
+ `),chunks:[]}}}function MY($,Z){let Q=$.length>Z.length?$:Z,W=$.length>Z.length?Z:$;if(Q.length===0)return 1;let J=TL(W,Q);return(Q.length-J)/Q.length}function TL($,Z){let Q=Z.length+1,W=$.length+1,J=Array(Q*W).fill(0),X=(j,V)=>J[j*W+V]??0,Y=(j,V,H)=>{J[j*W+V]=H};for(let j=0;j<=Z.length;j++)Y(j,0,j);for(let j=0;j<=$.length;j++)Y(0,j,j);for(let j=1;j<=Z.length;j++)for(let V=1;V<=$.length;V++)if(Z[j-1]===$[V-1])Y(j,V,X(j-1,V-1));else Y(j,V,1+Math.min(X(j-1,V-1),X(j,V-1),X(j-1,V)));return X(Z.length,$.length)}function OL($,Z,Q,W){if(Z.length===0)return[Q,0,1];let J=0,X=(Y)=>{let j=b0(Z.join(`
105
105
  `));for(let H=Y;H<$.length;H++){let B=b0($.slice(H,H+Z.length).join(`
106
106
  `));if(B===j)return[H,0,1];let G=MY(B,j);if(G>J)J=G}for(let H=Y;H<$.length;H++){let B=b0($.slice(H,H+Z.length).map((K)=>K.trimEnd()).join(`
107
107
  `)),G=b0(Z.map((K)=>K.trimEnd()).join(`
108
108
  `));if(B===G)return[H,1,1]}for(let H=Y;H<$.length;H++){let B=b0($.slice(H,H+Z.length).map((K)=>K.trim()).join(`
109
109
  `)),G=b0(Z.map((K)=>K.trim()).join(`
110
110
  `));if(B===G)return[H,100,1]}let V=0.66;for(let H=Y;H<$.length;H++){let B=b0($.slice(H,H+Z.length).join(`
111
- `)),G=MY(B,j);if(G>=V)return[H,1000,G];if(G>J)J=G}return[-1,0,J]};if(W){let[Y,j,V]=X($.length-Z.length);if(Y!==-1)return[Y,j,V];return[Y,j,V]=X(Q),[Y,j+1e4,V]}return X(Q)}function _L($,Z){let Q=Z,W=[],J=[],X=[],Y=[],j="keep",V=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(Q<$.length){let H=$[Q];if(!H||V.some((K)=>H.startsWith(K.trim())))break;if(H==="***")break;if(H.startsWith("***"))throw new J0(`Invalid line: ${H}`);Q++;let B=j,G=H;if(G[0]==="+")j="add";else if(G[0]==="-")j="delete";else if(G[0]===" ")j="keep";else j="keep",G=` ${G}`;if(G=G.slice(1),j==="keep"&&B!==j){if(X.length||J.length)Y.push({origIndex:W.length-J.length,delLines:J,insLines:X});J=[],X=[]}if(j==="delete")J.push(G),W.push(G);else if(j==="add")X.push(G);else W.push(G)}if(X.length||J.length)Y.push({origIndex:W.length-J.length,delLines:J,insLines:X});if(Q<$.length&&$[Q]===v.END_FILE)return Q++,[W,Y,Q,!0];return[W,Y,Q,!1]}function EQ($,Z,Q){let W=h0.isAbsolute(Z),J=W?h0.normalize(Z):h0.resolve($,Z);if(!Q||W)return J;let X=h0.relative($,J);if(X.startsWith("..")||h0.isAbsolute(X))throw new J0(`Path must stay within cwd: ${Z}`);return J}function zL($){return $.split(`
112
- `).map((Z)=>Z.replace(/\r$/,""))}function EY($){if($.trim()==="")return!1;return RY.some((Z)=>$.startsWith(Z))}function TL($){let Z=0,Q=$.length;while(Z<Q&&EY($[Z]??""))Z++;while(Q>Z&&EY($[Q-1]??""))Q--;return $.slice(Z,Q)}function OL($){let Z=zL($),Q=Z.findIndex((Y)=>Y.startsWith(v.BEGIN)),W=-1;for(let Y=Z.length-1;Y>=0;Y--)if(Z[Y]?.startsWith(v.END)){W=Y;break}if(Q!==-1||W!==-1){if(Q===-1||W===-1||W<Q)throw new J0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:Z.slice(Q,W+1)}}let J=TL(Z);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[v.BEGIN,...J,v.END]}}function qL($,Z){let Q=new Set;for(let W of $)for(let J of Z)if(W.startsWith(J)){Q.add(W.substring(J.length).trim());break}return[...Q]}function ML($,Z,Q){if(Z.length===0)return $;let W=$.split(`
111
+ `)),G=MY(B,j);if(G>=V)return[H,1000,G];if(G>J)J=G}return[-1,0,J]};if(W){let[Y,j,V]=X($.length-Z.length);if(Y!==-1)return[Y,j,V];return[Y,j,V]=X(Q),[Y,j+1e4,V]}return X(Q)}function qL($,Z){let Q=Z,W=[],J=[],X=[],Y=[],j="keep",V=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(Q<$.length){let H=$[Q];if(!H||V.some((K)=>H.startsWith(K.trim())))break;if(H==="***")break;if(H.startsWith("***"))throw new J0(`Invalid line: ${H}`);Q++;let B=j,G=H;if(G[0]==="+")j="add";else if(G[0]==="-")j="delete";else if(G[0]===" ")j="keep";else j="keep",G=` ${G}`;if(G=G.slice(1),j==="keep"&&B!==j){if(X.length||J.length)Y.push({origIndex:W.length-J.length,delLines:J,insLines:X});J=[],X=[]}if(j==="delete")J.push(G),W.push(G);else if(j==="add")X.push(G);else W.push(G)}if(X.length||J.length)Y.push({origIndex:W.length-J.length,delLines:J,insLines:X});if(Q<$.length&&$[Q]===v.END_FILE)return Q++,[W,Y,Q,!0];return[W,Y,Q,!1]}function EQ($,Z,Q){let W=h0.isAbsolute(Z),J=W?h0.normalize(Z):h0.resolve($,Z);if(!Q||W)return J;let X=h0.relative($,J);if(X.startsWith("..")||h0.isAbsolute(X))throw new J0(`Path must stay within cwd: ${Z}`);return J}function ML($){return $.split(`
112
+ `).map((Z)=>Z.replace(/\r$/,""))}function EY($){if($.trim()==="")return!1;return RY.some((Z)=>$.startsWith(Z))}function RL($){let Z=0,Q=$.length;while(Z<Q&&EY($[Z]??""))Z++;while(Q>Z&&EY($[Q-1]??""))Q--;return $.slice(Z,Q)}function EL($){let Z=ML($),Q=Z.findIndex((Y)=>Y.startsWith(v.BEGIN)),W=-1;for(let Y=Z.length-1;Y>=0;Y--)if(Z[Y]?.startsWith(v.END)){W=Y;break}if(Q!==-1||W!==-1){if(Q===-1||W===-1||W<Q)throw new J0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:Z.slice(Q,W+1)}}let J=RL(Z);while(J.length>0&&J[0]==="")J.shift();while(J.length>0&&J[J.length-1]==="")J.pop();return{lines:[v.BEGIN,...J,v.END]}}function NL($,Z){let Q=new Set;for(let W of $)for(let J of Z)if(W.startsWith(J)){Q.add(W.substring(J.length).trim());break}return[...Q]}function wL($,Z,Q){if(Z.length===0)return $;let W=$.split(`
113
113
  `),J=[],X=0;for(let Y of Z){if(Y.origIndex>W.length)throw new J0(`${Q}: chunk.origIndex ${Y.origIndex} > lines.length ${W.length}`);if(X>Y.origIndex)throw new J0(`${Q}: currentIndex ${X} > chunk.origIndex ${Y.origIndex}`);J.push(...W.slice(X,Y.origIndex)),J.push(...Y.insLines),X=Y.origIndex+Y.delLines.length}return J.push(...W.slice(X)),J.join(`
114
- `)}async function RL($,Z,Q,W){let J=qL($,[v.UPDATE,v.DELETE]),X={};for(let Y of J){let j=EQ(Z,Y,W),V;try{V=await y0.readFile(j,Q)}catch{throw new J0(`File not found: ${Y}`)}X[Y]=V.replace(/\r\n/g,`
115
- `)}return X}function EL($,Z){let Q={};for(let[W,J]of Object.entries($.actions))switch(J.type){case"delete":Q[W]={type:"delete",oldContent:Z[W]};break;case"add":if(J.newFile===void 0)throw new J0("ADD action without file content");Q[W]={type:"add",newContent:J.newFile};break;case"update":Q[W]={type:"update",oldContent:Z[W],newContent:ML(Z[W]??"",J.chunks,W),movePath:J.movePath};break}return Q}function NL($){let Z=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let W=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(Z.push(`${Q.path}: hunk ${W}: ${Q.message}`),Q.context)Z.push(`Context:
114
+ `)}async function CL($,Z,Q,W){let J=NL($,[v.UPDATE,v.DELETE]),X={};for(let Y of J){let j=EQ(Z,Y,W),V;try{V=await y0.readFile(j,Q)}catch{throw new J0(`File not found: ${Y}`)}X[Y]=V.replace(/\r\n/g,`
115
+ `)}return X}function PL($,Z){let Q={};for(let[W,J]of Object.entries($.actions))switch(J.type){case"delete":Q[W]={type:"delete",oldContent:Z[W]};break;case"add":if(J.newFile===void 0)throw new J0("ADD action without file content");Q[W]={type:"add",newContent:J.newFile};break;case"update":Q[W]={type:"update",oldContent:Z[W],newContent:wL(Z[W]??"",J.chunks,W),movePath:J.movePath};break}return Q}function SL($){let Z=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let W=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(Z.push(`${Q.path}: hunk ${W}: ${Q.message}`),Q.context)Z.push(`Context:
116
116
  ${Q.context}`)}return Z.join(`
117
- `)}async function wL($,Z,Q,W){let J=[];for(let[X,Y]of Object.entries($)){let j=EQ(Z,X,W);switch(Y.type){case"delete":await y0.rm(j,{force:!0}),J.push(`${X}: [deleted]`);break;case"add":if(Y.newContent===void 0)throw new J0(`Cannot create ${X} with no content`);await y0.mkdir(h0.dirname(j),{recursive:!0}),await y0.writeFile(j,Y.newContent,{encoding:Q}),J.push(X);break;case"update":{if(Y.newContent===void 0)throw new J0(`UPDATE change for ${X} has no new content`);if(Y.movePath){let V=EQ(Z,Y.movePath,W);await y0.mkdir(h0.dirname(V),{recursive:!0}),await y0.writeFile(V,Y.newContent,{encoding:Q}),await y0.rm(j,{force:!0}),J.push(`${X} -> ${Y.movePath}`)}else await y0.writeFile(j,Y.newContent,{encoding:Q}),J.push(X);break}}}return J}function g6($={}){let{encoding:Z="utf-8",restrictToCwd:Q=!0}=$;return async(W,J,X)=>{let Y=OL(W.input),j=await RL(Y.lines,J,Z,Q),V=new RQ(Y.lines,j),{patch:H,fuzz:B}=V.parse();if(H.warnings&&H.warnings.length>0)throw new J0(NL(H.warnings));let G=EL(H,j),K=await wL(G,J,Z,Q),F=["Successfully applied patch to the following files:"];for(let A of K)F.push(A);if(B>0)F.push(`Note: Patch applied with fuzz factor ${B}`);return F.join(`
118
- `)}}import*as n0 from"node:fs/promises";import*as i0 from"node:path";function CL($,Z,Q){let W=i0.isAbsolute(Z),J=W?i0.normalize(Z):i0.resolve($,Z);if(!Q)return J;if(W)return J;let X=i0.relative($,J);if(X.startsWith("..")||i0.isAbsolute(X))throw Error(`Path must stay within cwd: ${Z}`);return J}function PL($,Z){if(Z.length===0)return 0;return $.split(Z).length-1}function SL($,Z,Q){let W=$.split(`
117
+ `)}async function bL($,Z,Q,W){let J=[];for(let[X,Y]of Object.entries($)){let j=EQ(Z,X,W);switch(Y.type){case"delete":await y0.rm(j,{force:!0}),J.push(`${X}: [deleted]`);break;case"add":if(Y.newContent===void 0)throw new J0(`Cannot create ${X} with no content`);await y0.mkdir(h0.dirname(j),{recursive:!0}),await y0.writeFile(j,Y.newContent,{encoding:Q}),J.push(X);break;case"update":{if(Y.newContent===void 0)throw new J0(`UPDATE change for ${X} has no new content`);if(Y.movePath){let V=EQ(Z,Y.movePath,W);await y0.mkdir(h0.dirname(V),{recursive:!0}),await y0.writeFile(V,Y.newContent,{encoding:Q}),await y0.rm(j,{force:!0}),J.push(`${X} -> ${Y.movePath}`)}else await y0.writeFile(j,Y.newContent,{encoding:Q}),J.push(X);break}}}return J}function m6($={}){let{encoding:Z="utf-8",restrictToCwd:Q=!0}=$;return async(W,J,X)=>{let Y=EL(W.input),j=await CL(Y.lines,J,Z,Q),V=new RQ(Y.lines,j),{patch:H,fuzz:B}=V.parse();if(H.warnings&&H.warnings.length>0)throw new J0(SL(H.warnings));let G=PL(H,j),K=await bL(G,J,Z,Q),F=["Successfully applied patch to the following files:"];for(let A of K)F.push(A);if(B>0)F.push(`Note: Patch applied with fuzz factor ${B}`);return F.join(`
118
+ `)}}import*as n0 from"node:fs/promises";import*as i0 from"node:path";function yL($,Z,Q){let W=i0.isAbsolute(Z),J=W?i0.normalize(Z):i0.resolve($,Z);if(!Q)return J;if(W)return J;let X=i0.relative($,J);if(X.startsWith("..")||i0.isAbsolute(X))throw Error(`Path must stay within cwd: ${Z}`);return J}function hL($,Z){if(Z.length===0)return 0;return $.split(Z).length-1}function kL($,Z,Q){let W=$.split(`
119
119
  `),J=Z.split(`
120
120
  `),X=Math.max(W.length,J.length),Y=["```diff"],j=0;for(let V=0;V<X;V++){if(j>=Q){Y.push("... diff truncated ...");break}let H=W[V],B=J[V];if(H===B)continue;let G=V+1;if(H!==void 0)Y.push(`-${G}: ${H}`),j++;if(B!==void 0&&j<Q)Y.push(`+${G}: ${B}`),j++}return Y.push("```"),Y.join(`
121
- `)}async function bL($,Z,Q){return await n0.mkdir(i0.dirname($),{recursive:!0}),await n0.writeFile($,Z,{encoding:Q}),`File created successfully at: ${$}`}async function yL($){try{return await n0.access($),!0}catch{return!1}}async function hL($,Z,Q,W,J){let X=await n0.readFile($,W),Y=PL(X,Z);if(Y===0)throw Error(`No replacement performed: text not found in ${$}.`);if(Y>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let j=X.replace(Z,Q??"");await n0.writeFile($,j,{encoding:W});let V=SL(X,j,J);return`Edited ${$}
122
- ${V}`}async function kL($,Z,Q,W){let X=(await n0.readFile($,W)).split(`
121
+ `)}async function IL($,Z,Q){return await n0.mkdir(i0.dirname($),{recursive:!0}),await n0.writeFile($,Z,{encoding:Q}),`File created successfully at: ${$}`}async function xL($){try{return await n0.access($),!0}catch{return!1}}async function gL($,Z,Q,W,J){let X=await n0.readFile($,W),Y=hL(X,Z);if(Y===0)throw Error(`No replacement performed: text not found in ${$}.`);if(Y>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let j=X.replace(Z,Q??"");await n0.writeFile($,j,{encoding:W});let V=kL(X,j,J);return`Edited ${$}
122
+ ${V}`}async function mL($,Z,Q,W){let X=(await n0.readFile($,W)).split(`
123
123
  `),Y=X.length+1;if(Z<1||Z>Y)throw Error(`Invalid insert_line: ${Z}. insert_line must be a positive one-based boundary line in the range 1-${Y}. Use ${Y} to append at EOF.`);let j=Z-1;return X.splice(j,0,...Q.split(`
124
124
  `)),await n0.writeFile($,X.join(`
125
- `),{encoding:W}),`Inserted content at line ${Z} in ${$}.`}function m6($={}){let{encoding:Z="utf-8",restrictToCwd:Q=!0,maxDiffLines:W=200}=$;return async(J,X,Y)=>{let j=CL(X,J.path,Q);if(J.insert_line!=null)return kL(j,J.insert_line,J.new_text,Z);if(!await yL(j))return bL(j,J.new_text,Z);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return hL(j,J.old_text,J.new_text,Z,W)}}import{createReadStream as IL}from"node:fs";import*as v6 from"node:fs/promises";import*as c1 from"node:path";import{createInterface as xL}from"node:readline";import{resolveExistingFilePath as gL}from"@cline/shared/storage";var mL=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),vL={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},NY=1e8,cL=50000;function wY($){let{reason:Z}=$;if(Z instanceof Error)return Z;if(Z!==void 0)return Error(String(Z));return Error("File read was aborted")}async function uL($,Z,Q,W,J,X){if(X?.aborted)throw wY(X);let Y=Math.max(W??1,1),j=J??Number.POSITIVE_INFINITY,V=Number.isFinite(j),H=V?j:Y+cL-1,B=[],G=0,K=0,F=!1,A=!1,L=Number.isFinite(j)?Math.min(j,Y+L2-1):Y+L2-1,f=Q?String(L).length+3:0,D=IL($,{encoding:Z}),U=xL({input:D,crlfDelay:Number.POSITIVE_INFINITY}),T=X?()=>D.destroy(wY(X)):void 0;if(X&&T)X.addEventListener("abort",T,{once:!0});try{for await(let P of U){if(K+=1,K>j){K=j;break}if(!V&&F&&K>=H){A=!0;break}if(K<Y||F)continue;if(B.length>=L2){F=!0;continue}let c=P;if(c.length>qQ)c=`${c.slice(0,qQ)} [line truncated]`;let n=G+c.length+f+1;if(n>I6&&B.length>0){F=!0;continue}B.push({lineNumber:K,text:c}),G=n}}finally{if(X&&T)X.removeEventListener("abort",T);U.close(),D.destroy()}let O=String(B[B.length-1]?.lineNumber??K).length,z=B.map(({lineNumber:P,text:c})=>Q?`${String(P).padStart(O," ")} | ${c}`:c).join(`
125
+ `),{encoding:W}),`Inserted content at line ${Z} in ${$}.`}function v6($={}){let{encoding:Z="utf-8",restrictToCwd:Q=!0,maxDiffLines:W=200}=$;return async(J,X,Y)=>{let j=yL(X,J.path,Q);if(J.insert_line!=null)return mL(j,J.insert_line,J.new_text,Z);if(!await xL(j))return IL(j,J.new_text,Z);if(J.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return gL(j,J.old_text,J.new_text,Z,W)}}import{createReadStream as vL}from"node:fs";import*as c6 from"node:fs/promises";import*as c1 from"node:path";import{createInterface as cL}from"node:readline";import{resolveExistingFilePath as uL}from"@cline/shared/storage";var dL=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),lL={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},NY=1e8,pL=50000;function wY($){let{reason:Z}=$;if(Z instanceof Error)return Z;if(Z!==void 0)return Error(String(Z));return Error("File read was aborted")}async function rL($,Z,Q,W,J,X){if(X?.aborted)throw wY(X);let Y=Math.max(W??1,1),j=J??Number.POSITIVE_INFINITY,V=Number.isFinite(j),H=V?j:Y+pL-1,B=[],G=0,K=0,F=!1,A=!1,L=Number.isFinite(j)?Math.min(j,Y+L2-1):Y+L2-1,f=Q?String(L).length+3:0,D=vL($,{encoding:Z}),U=cL({input:D,crlfDelay:Number.POSITIVE_INFINITY}),T=X?()=>D.destroy(wY(X)):void 0;if(X&&T)X.addEventListener("abort",T,{once:!0});try{for await(let P of U){if(K+=1,K>j){K=j;break}if(!V&&F&&K>=H){A=!0;break}if(K<Y||F)continue;if(B.length>=L2){F=!0;continue}let c=P;if(c.length>qQ)c=`${c.slice(0,qQ)} [line truncated]`;let n=G+c.length+f+1;if(n>x6&&B.length>0){F=!0;continue}B.push({lineNumber:K,text:c}),G=n}}finally{if(X&&T)X.removeEventListener("abort",T);U.close(),D.destroy()}let q=String(B[B.length-1]?.lineNumber??K).length,z=B.map(({lineNumber:P,text:c})=>Q?`${String(P).padStart(q," ")} | ${c}`:c).join(`
126
126
  `),_=B[B.length-1]?.lineNumber;if(_===void 0)return z;let M=Math.min(j,K);if(_>=M)return z;let E=A?`${K}+ lines`:M;return`${z}
127
127
 
128
- [Showing lines ${Y}-${_} of ${E}. Use start_line/end_line to read other sections.]`}function c6($={}){let{maxFileSizeBytes:Z,encoding:Q,includeLineNumbers:W}={...vL,...$};return async(J,X)=>{let{path:Y,start_line:j,end_line:V}=J,H=c1.isAbsolute(Y)?c1.normalize(Y):c1.resolve(process.cwd(),Y),B=gL(H)??H,G=c1.extname(B).toLowerCase(),K=mL.get(G),F=await v6.stat(B);if(!F.isFile())throw Error(`Path is not a file: ${B}`);if(K){if(F.size>Z)throw Error(`Image file too large: ${F.size} bytes (max: ${Z} bytes).`);if(X.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await v6.readFile(B);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>NY)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${NY} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return uL(B,Q,W,j,V,X.signal)}}import{spawn as IY}from"node:child_process";import*as xY from"node:fs/promises";import*as l6 from"node:path";import{spawn as dL}from"node:child_process";import{readdir as lL}from"node:fs/promises";import wQ from"node:path";import{isMainThread as SY,parentPort as CY,Worker as pL}from"node:worker_threads";var rL=15000,iL=600000,nL=1000,aL=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function PY($){let Z=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return Z==="EACCES"||Z==="EPERM"||Z==="ENOENT"}var O2=new Map;function sL(){if(!SY)return!1;return!0}function oL($){if(O2.size<=1)return;for(let[Z,Q]of O2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>iL)O2.delete(Z)}}function tL($,Z){return wQ.relative($,Z).split(wQ.sep).join("/")}async function eL($){let Q=(await new Promise((W,J)=>{let X=dL("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",j="";X.stdout.on("data",(V)=>{Y+=V.toString()}),X.stderr.on("data",(V)=>{j+=V.toString()}),X.on("error",J),X.on("close",(V)=>{if(V===0){W(Y);return}J(Error(j||`rg exited with code ${V}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(Q)}async function bY($,Z,Q){let W;try{W=await lL(Z,{withFileTypes:!0})}catch(J){if(PY(J))return;throw J}for(let J of W){let X=wQ.join(Z,J.name);if(J.isDirectory()){if(aL.has(J.name))continue;try{await bY($,X,Q)}catch(Y){if(PY(Y))continue;throw Y}continue}if(J.isFile())Q.add(tL($,X))}}async function $_($){let Z=new Set;return await bY($,$,Z),Z}async function u6($){try{return await eL($)}catch{return $_($)}}function Z_(){if(SY||!CY)return;let $=CY;$.on("message",(Z)=>{if(Z.type!=="index")return;u6(Z.cwd).then((Q)=>{let W={type:"indexResult",requestId:Z.requestId,files:Array.from(Q)};$.postMessage(W)}).catch((Q)=>{let W={type:"indexResult",requestId:Z.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(W)})})}class yY{worker=new pL(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let Z=this.pending.get($.requestId);if(!Z)return;if(this.pending.delete($.requestId),$.error){Z.reject(Error($.error));return}Z.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 Z=++this.nextRequestId,Q=new Promise((J,X)=>{let Y=setTimeout(()=>{this.pending.delete(Z),J(null)},nL);Y.unref(),this.pending.set(Z,{resolve:(j)=>{clearTimeout(Y),J(j)},reject:(j)=>{clearTimeout(Y),X(j)}})}),W={type:"index",requestId:Z,cwd:$};return this.worker.postMessage(W),Q}flushPending($){for(let[Z,Q]of this.pending.entries())Q.reject($),this.pending.delete(Z)}}Z_();var NQ;function Q_(){if(!sL())return null;if(NQ===void 0)NQ=new yY;return NQ}async function W_($){let Z=Q_();if(!Z)return u6($);try{let Q=await Z.requestIndex($);if(Q===null)return u6($);return new Set(Q)}catch{return u6($)}}async function q$($,Z={}){let Q=Z.ttlMs??rL,W=Date.now();oL(W);let J=O2.get($);if(J&&Q>0&&W-J.lastBuiltAt<=Q&&J.files.size>0)return J.lastAccessedAt=W,J.files;if(J?.pending)return J.lastAccessedAt=W,J.pending;let X=W_($).then((Y)=>{return O2.set($,{files:Y,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Y});return O2.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:W,pending:X}),X}async function hY($,Z={}){await q$($,{...Z,ttlMs:0})}import{stat as J_}from"node:fs/promises";import M$ from"node:path";var X_=/[),.:;!?`'"]+$/,Y_=/^[(`'"]+/;function j_($){let Z=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let W of Z){let J=(W[2]??"").trim();if(J.length===0)continue;let X=J.replace(Y_,"").replace(X_,"");if(X.length===0||X.includes("@"))continue;Q.push(X)}return Array.from(new Set(Q))}function V_($,Z){let Q=$.replace(/\\/g,"/"),W=M$.isAbsolute(Q)?M$.resolve(Q):M$.resolve(Z,Q),J=M$.relative(Z,W);if(J.startsWith("..")||M$.isAbsolute(J))return;return J.split(M$.sep).join("/")}async function d6($,Z,Q={}){let W=j_($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:X,maxTotalBytes:Y}=Q,j=await q$(Z,{ttlMs:Q.ttlMs}),V=[],H=[],B=[],G=0;for(let K of W){if(J&&B.length>=J){H.push(K);continue}let F=V_(K,Z);if(!F||!j.has(F)){H.push(K);continue}if(!X||!Y){V.push(F);continue}let A=M$.join(Z,F);try{if(!(await J_(A)).isFile()){H.push(K);continue}let f=G+X;if(f>Y){H.push(K);continue}G=f,V.push(F)}catch{H.push(K)}}return{prompt:$,mentions:W,matchedFiles:V,ignoredMentions:H}}var H_=["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"],B_=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],R$=null;function G_(){if(R$!==null)return Promise.resolve(R$);return new Promise(($)=>{let Z=IY("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});Z.on("close",(Q)=>{R$=Q===0,$(R$)}),Z.on("error",()=>{R$=!1,$(!1)}),setTimeout(()=>{if(!Z.killed)Z.kill("SIGTERM");if(R$===null)R$=!1,$(!1)},1000)})}function K_($,Z,Q,W,J=5000,X){return new Promise((Y)=>{let j=IY("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:Z,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",H=!1,B=()=>{if(!j.killed)j.kill("SIGTERM")},G=setTimeout(()=>{if(!H)H=!0,B(),Y(null)},J),K=(F)=>{if(!H)H=!0,clearTimeout(G),B(),Y(F)};if(X?.aborted){B(),Y(null);return}X?.addEventListener("abort",()=>{K(null)}),j.stdout.on("data",(F)=>{V+=F.toString()}),j.stderr.on("data",()=>{}),j.on("close",(F)=>{if(F===0||F===1){try{let A=[],L=V.split(`
129
- `).filter((f)=>f.trim());for(let f of L){if(A.length>=Q)break;let D=JSON.parse(f);if(D.type==="match"){let U=D.data,T=[];if(D.data.submatches&&D.data.submatches.length>0){let O=D.data.submatches[0];A.push({file:U.path.text,line:U.line_number,column:(O?.start??0)+1,match:O?.match?.text??"",context:T})}}else if(D.type==="context"&&A.length>0){let U=A[A.length-1],T=D.data.line_number===U.line?">":" ";U.context.push(`${T} ${D.data.line_number}: ${D.data.lines?.text??D.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),j.on("error",()=>{K(null)})})}function F_($,Z,Q,W){let J=$.split("/"),X=J[J.length-1]??"";if(J.length-1>W)return!1;for(let V=0;V<J.length-1;V++)if(Z.has(J[V]??""))return!1;let j=l6.posix.extname(X).slice(1).toLowerCase();return Q.has(j)||!j&&!X.startsWith(".")}function p6($={}){let{includeExtensions:Z=H_,excludeDirs:Q=B_,maxResults:W=100,contextLines:J=2,maxDepth:X=20}=$,Y=new Set(Q),j=new Set(Z.map((V)=>V.toLowerCase()));return async(V,H,B)=>{if(B.signal?.aborted)throw Error("Search operation aborted");let G=await G_(),K=null;if(G)K=await K_(V,H,W,J,5000,B.signal);if(K){let U=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let T of K)U.push(`${T.file}:${T.line}:${T.column}`),U.push(...T.context),U.push("");if(K.length>=W)U.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return kY(U.join(`
130
- `))}let F;try{F=new RegExp(V,"gim")}catch(U){throw Error(`Invalid regex pattern: ${V}. ${U instanceof Error?U.message:""}`)}let A=[],L=0,f=await q$(H);for(let U of f){if(B.signal?.aborted)throw Error("Search operation aborted");if(!F_(U,Y,j,X))continue;if(A.length>=W)break;L++;let T=l6.join(H,U);try{let z=(await xY.readFile(T,"utf-8")).split(`
128
+ [Showing lines ${Y}-${_} of ${E}. Use start_line/end_line to read other sections.]`}function u6($={}){let{maxFileSizeBytes:Z,encoding:Q,includeLineNumbers:W}={...lL,...$};return async(J,X)=>{let{path:Y,start_line:j,end_line:V}=J,H=c1.isAbsolute(Y)?c1.normalize(Y):c1.resolve(process.cwd(),Y),B=uL(H)??H,G=c1.extname(B).toLowerCase(),K=dL.get(G),F=await c6.stat(B);if(!F.isFile())throw Error(`Path is not a file: ${B}`);if(K){if(F.size>Z)throw Error(`Image file too large: ${F.size} bytes (max: ${Z} bytes).`);if(X.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let A=await c6.readFile(B);return[{type:"text",text:"Successfully read image"},{type:"image",data:A.toString("base64"),mediaType:K}]}if(F.size>NY)throw Error(`Text file too large to stream safely: ${F.size} bytes (max: ${NY} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return rL(B,Q,W,j,V,X.signal)}}import{spawn as IY}from"node:child_process";import*as xY from"node:fs/promises";import*as p6 from"node:path";import{spawn as iL}from"node:child_process";import{readdir as nL}from"node:fs/promises";import wQ from"node:path";import{isMainThread as SY,parentPort as CY,Worker as aL}from"node:worker_threads";var sL=15000,oL=600000,tL=1000,eL=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function PY($){let Z=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return Z==="EACCES"||Z==="EPERM"||Z==="ENOENT"}var O2=new Map;function $_(){if(!SY)return!1;return!0}function Z_($){if(O2.size<=1)return;for(let[Z,Q]of O2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>oL)O2.delete(Z)}}function Q_($,Z){return wQ.relative($,Z).split(wQ.sep).join("/")}async function W_($){let Q=(await new Promise((W,J)=>{let X=iL("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",j="";X.stdout.on("data",(V)=>{Y+=V.toString()}),X.stderr.on("data",(V)=>{j+=V.toString()}),X.on("error",J),X.on("close",(V)=>{if(V===0){W(Y);return}J(Error(j||`rg exited with code ${V}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(Q)}async function bY($,Z,Q){let W;try{W=await nL(Z,{withFileTypes:!0})}catch(J){if(PY(J))return;throw J}for(let J of W){let X=wQ.join(Z,J.name);if(J.isDirectory()){if(eL.has(J.name))continue;try{await bY($,X,Q)}catch(Y){if(PY(Y))continue;throw Y}continue}if(J.isFile())Q.add(Q_($,X))}}async function J_($){let Z=new Set;return await bY($,$,Z),Z}async function d6($){try{return await W_($)}catch{return J_($)}}function X_(){if(SY||!CY)return;let $=CY;$.on("message",(Z)=>{if(Z.type!=="index")return;d6(Z.cwd).then((Q)=>{let W={type:"indexResult",requestId:Z.requestId,files:Array.from(Q)};$.postMessage(W)}).catch((Q)=>{let W={type:"indexResult",requestId:Z.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(W)})})}class yY{worker=new aL(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let Z=this.pending.get($.requestId);if(!Z)return;if(this.pending.delete($.requestId),$.error){Z.reject(Error($.error));return}Z.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 Z=++this.nextRequestId,Q=new Promise((J,X)=>{let Y=setTimeout(()=>{this.pending.delete(Z),J(null)},tL);Y.unref(),this.pending.set(Z,{resolve:(j)=>{clearTimeout(Y),J(j)},reject:(j)=>{clearTimeout(Y),X(j)}})}),W={type:"index",requestId:Z,cwd:$};return this.worker.postMessage(W),Q}flushPending($){for(let[Z,Q]of this.pending.entries())Q.reject($),this.pending.delete(Z)}}X_();var NQ;function Y_(){if(!$_())return null;if(NQ===void 0)NQ=new yY;return NQ}async function j_($){let Z=Y_();if(!Z)return d6($);try{let Q=await Z.requestIndex($);if(Q===null)return d6($);return new Set(Q)}catch{return d6($)}}async function M$($,Z={}){let Q=Z.ttlMs??sL,W=Date.now();Z_(W);let J=O2.get($);if(J&&Q>0&&W-J.lastBuiltAt<=Q&&J.files.size>0)return J.lastAccessedAt=W,J.files;if(J?.pending)return J.lastAccessedAt=W,J.pending;let X=j_($).then((Y)=>{return O2.set($,{files:Y,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),Y});return O2.set($,{files:J?.files??new Set,lastBuiltAt:J?.lastBuiltAt??0,lastAccessedAt:W,pending:X}),X}async function hY($,Z={}){await M$($,{...Z,ttlMs:0})}import{stat as V_}from"node:fs/promises";import R$ from"node:path";var H_=/[),.:;!?`'"]+$/,B_=/^[(`'"]+/;function G_($){let Z=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let W of Z){let J=(W[2]??"").trim();if(J.length===0)continue;let X=J.replace(B_,"").replace(H_,"");if(X.length===0||X.includes("@"))continue;Q.push(X)}return Array.from(new Set(Q))}function K_($,Z){let Q=$.replace(/\\/g,"/"),W=R$.isAbsolute(Q)?R$.resolve(Q):R$.resolve(Z,Q),J=R$.relative(Z,W);if(J.startsWith("..")||R$.isAbsolute(J))return;return J.split(R$.sep).join("/")}async function l6($,Z,Q={}){let W=G_($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:J,maxFileBytes:X,maxTotalBytes:Y}=Q,j=await M$(Z,{ttlMs:Q.ttlMs}),V=[],H=[],B=[],G=0;for(let K of W){if(J&&B.length>=J){H.push(K);continue}let F=K_(K,Z);if(!F||!j.has(F)){H.push(K);continue}if(!X||!Y){V.push(F);continue}let A=R$.join(Z,F);try{if(!(await V_(A)).isFile()){H.push(K);continue}let f=G+X;if(f>Y){H.push(K);continue}G=f,V.push(F)}catch{H.push(K)}}return{prompt:$,mentions:W,matchedFiles:V,ignoredMentions:H}}var F_=["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"],A_=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],E$=null;function f_(){if(E$!==null)return Promise.resolve(E$);return new Promise(($)=>{let Z=IY("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});Z.on("close",(Q)=>{E$=Q===0,$(E$)}),Z.on("error",()=>{E$=!1,$(!1)}),setTimeout(()=>{if(!Z.killed)Z.kill("SIGTERM");if(E$===null)E$=!1,$(!1)},1000)})}function U_($,Z,Q,W,J=5000,X){return new Promise((Y)=>{let j=IY("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:Z,stdio:["ignore","pipe","pipe"],windowsHide:!0}),V="",H=!1,B=()=>{if(!j.killed)j.kill("SIGTERM")},G=setTimeout(()=>{if(!H)H=!0,B(),Y(null)},J),K=(F)=>{if(!H)H=!0,clearTimeout(G),B(),Y(F)};if(X?.aborted){B(),Y(null);return}X?.addEventListener("abort",()=>{K(null)}),j.stdout.on("data",(F)=>{V+=F.toString()}),j.stderr.on("data",()=>{}),j.on("close",(F)=>{if(F===0||F===1){try{let A=[],L=V.split(`
129
+ `).filter((f)=>f.trim());for(let f of L){if(A.length>=Q)break;let D=JSON.parse(f);if(D.type==="match"){let U=D.data,T=[];if(D.data.submatches&&D.data.submatches.length>0){let q=D.data.submatches[0];A.push({file:U.path.text,line:U.line_number,column:(q?.start??0)+1,match:q?.match?.text??"",context:T})}}else if(D.type==="context"&&A.length>0){let U=A[A.length-1],T=D.data.line_number===U.line?">":" ";U.context.push(`${T} ${D.data.line_number}: ${D.data.lines?.text??D.data.line?.text??""}`)}}K(A.length>0?A:null)}catch{K(null)}return}K(null)}),j.on("error",()=>{K(null)})})}function D_($,Z,Q,W){let J=$.split("/"),X=J[J.length-1]??"";if(J.length-1>W)return!1;for(let V=0;V<J.length-1;V++)if(Z.has(J[V]??""))return!1;let j=p6.posix.extname(X).slice(1).toLowerCase();return Q.has(j)||!j&&!X.startsWith(".")}function r6($={}){let{includeExtensions:Z=F_,excludeDirs:Q=A_,maxResults:W=100,contextLines:J=2,maxDepth:X=20}=$,Y=new Set(Q),j=new Set(Z.map((V)=>V.toLowerCase()));return async(V,H,B)=>{if(B.signal?.aborted)throw Error("Search operation aborted");let G=await f_(),K=null;if(G)K=await U_(V,H,W,J,5000,B.signal);if(K){let U=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${V}`,""];for(let T of K)U.push(`${T.file}:${T.line}:${T.column}`),U.push(...T.context),U.push("");if(K.length>=W)U.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return kY(U.join(`
130
+ `))}let F;try{F=new RegExp(V,"gim")}catch(U){throw Error(`Invalid regex pattern: ${V}. ${U instanceof Error?U.message:""}`)}let A=[],L=0,f=await M$(H);for(let U of f){if(B.signal?.aborted)throw Error("Search operation aborted");if(!D_(U,Y,j,X))continue;if(A.length>=W)break;L++;let T=p6.join(H,U);try{let z=(await xY.readFile(T,"utf-8")).split(`
131
131
  `);for(let _=0;_<z.length;_++){let M=z[_];F.lastIndex=0;let E=F.exec(M);while(E!==null){if(A.length>=W)break;let P=Math.max(0,_-J),c=Math.min(z.length-1,_+J),n=[];for(let a=P;a<=c;a++){let t=a===_?">":" ";n.push(`${t} ${a+1}: ${z[a]}`)}if(A.push({file:U,line:_+1,column:E.index+1,match:E[0],context:n}),E.index===F.lastIndex)F.lastIndex++;E=F.exec(M)}}}catch{}}if(A.length===0)return`No results found for pattern: ${V}
132
132
  Searched ${L} files.`;let D=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${V}`,`Searched ${L} files.`,""];for(let U of A)D.push(`${U.file}:${U.line}:${U.column}`),D.push(...U.context),D.push("");if(A.length>=W)D.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return kY(D.join(`
133
133
  `))}}function kY($){if($.length<=_2)return $;let Z=Math.ceil(_2/2),Q=Math.max(1,_2-Z);return`${$.slice(0,Z)}
134
134
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
135
- `+$.slice(-Q)}function A_($){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,`
135
+ `+$.slice(-Q)}function L_($){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,`
136
136
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(Z,Q)=>String.fromCharCode(parseInt(Q,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
137
137
  `).replace(/\n{3,}/g,`
138
138
 
139
- `).trim()}function r6($={}){let{timeoutMs:Z=30000,maxResponseBytes:Q=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:X=!0}=$;return async(Y,j,V)=>{let H;try{H=new URL(Y)}catch{throw Error(`Invalid URL: ${Y}`)}if(!["http:","https:"].includes(H.protocol))throw Error(`Invalid protocol: ${H.protocol}. Only http and https are supported.`);let B=new AbortController,G=setTimeout(()=>B.abort(),Z),K;if(V.signal)K=()=>B.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(Y,{method:"GET",headers:{"User-Agent":W,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:X?"follow":"manual",signal:B.signal});if(clearTimeout(G),!X&&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")||"",L=F.body?.getReader();if(!L)throw Error("Failed to read response body");let f=[],D=0;while(!0){let{done:M,value:E}=await L.read();if(M)break;if(D+=E.length,D>Q)throw L.cancel(),Error(`Response too large: exceeded ${Q} bytes`);f.push(E)}let U=new Uint8Array(D),T=0;for(let M of f)U.set(M,T),T+=M.length;let O=new TextDecoder("utf-8").decode(U),z;if(A.includes("text/html")||A.includes("application/xhtml"))z=A_(O);else if(A.includes("application/json"))try{let M=JSON.parse(O);z=JSON.stringify(M,null,2)}catch{z=O}else z=O;let _=[`URL: ${Y}`,`Content-Type: ${A}`,`Size: ${D} bytes`,"","--- Content ---",z.slice(0,50000)];if(z.length>50000)_.push(`
139
+ `).trim()}function i6($={}){let{timeoutMs:Z=30000,maxResponseBytes:Q=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:J={},followRedirects:X=!0}=$;return async(Y,j,V)=>{let H;try{H=new URL(Y)}catch{throw Error(`Invalid URL: ${Y}`)}if(!["http:","https:"].includes(H.protocol))throw Error(`Invalid protocol: ${H.protocol}. Only http and https are supported.`);let B=new AbortController,G=setTimeout(()=>B.abort(),Z),K;if(V.signal)K=()=>B.abort(),V.signal.addEventListener("abort",K);try{let F=await fetch(Y,{method:"GET",headers:{"User-Agent":W,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:X?"follow":"manual",signal:B.signal});if(clearTimeout(G),!X&&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")||"",L=F.body?.getReader();if(!L)throw Error("Failed to read response body");let f=[],D=0;while(!0){let{done:M,value:E}=await L.read();if(M)break;if(D+=E.length,D>Q)throw L.cancel(),Error(`Response too large: exceeded ${Q} bytes`);f.push(E)}let U=new Uint8Array(D),T=0;for(let M of f)U.set(M,T),T+=M.length;let q=new TextDecoder("utf-8").decode(U),z;if(A.includes("text/html")||A.includes("application/xhtml"))z=L_(q);else if(A.includes("application/json"))try{let M=JSON.parse(q);z=JSON.stringify(M,null,2)}catch{z=q}else z=q;let _=[`URL: ${Y}`,`Content-Type: ${A}`,`Size: ${D} bytes`,"","--- Content ---",z.slice(0,50000)];if(z.length>50000)_.push(`
140
140
  [Content truncated: showing first 50000 of ${z.length} characters]`);return _.push("","--- Analysis Request ---",`Prompt: ${j}`),_.join(`
141
- `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${Z}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function CQ($={}){return D8($)}function i6($={}){return{readFile:c6($.fileRead),search:p6($.search),bash:CQ($.bash),webFetch:r6($.webFetch),applyPatch:g6($.applyPatch),editor:m6($.editor)}}var f_={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"},L8=[{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 gY($,Z){if(!Z||Z.length===0)return!0;let Q=$.toLowerCase();return Z.some((W)=>Q.includes(W.toLowerCase()))}function U_($,Z,Q,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return gY(Z,$.providerIdIncludes)&&gY(Q,$.modelIdIncludes)}function _8($,Z,Q,W){if(!W||W.length===0)return{};let J=new Map;for(let Y of W){if(!U_(Y,$,Z,Q))continue;for(let j of Y.disableTools??[])J.set(j,!1);for(let j of Y.enableTools??[])J.set(j,!0)}let X={};for(let[Y,j]of J.entries())X[f_[Y]]=j;return X}var e0={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 u1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function mY($){if($!=="yolo")return{};let Z={enabled:!0,autoApprove:!0},Q={"*":Z};for(let W of U2)Q[W]=Z;return Q}function vY($,Z){let Q=e0[$],{enableSpawnAgent:W,enableAgentTeams:J,...X}=Q;return T2({...X,...Z})}import{createTool as Sz,zodToJsonSchema as bz}from"@cline/shared";import{z as cQ}from"zod";r0();import{createAgentRuntime as _z}from"@cline/agents";import{createContributionRegistry as zz,mergeModelOptions as Yj}from"@cline/shared";import{createGateway as E_,createHandlerAsync as N_,hasRegisteredHandler as w_,MODEL_COLLECTIONS_BY_PROVIDER_ID as C_,normalizeProviderId as P_}from"@cline/llms";import{EMPTY_CONTENT_TEXT as D_}from"@cline/shared";function L_($){let Z=z_($.content),Q=[],W=$.id??q_(),J=0,X=[],Y=()=>{if(X.length===0)return;let j=J===0?W:`${W}_part_${J}`;J+=1,Q.push({id:j,role:$.role,content:X.map(T_),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:cY($.metrics)}),X=[]};if(Z.length===0)return Q.push({id:W,role:$.role,content:[{type:"text",text:D_}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:cY($.metrics)}),Q;for(let j of Z){if(j.type!=="tool_result"){X.push(j);continue}Y(),Q.push({id:`${W}_tool_${j.tool_use_id}`,role:"tool",content:[dY(j)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return Y(),Q}function n6($){return $.flatMap(L_)}function __($){let Z=$.content.map(lY).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:Z,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:O_($.metrics)}}function q2($){return $.map(__)}function a6($){let Z=[];for(let Q of $){let W=Q.content.map(lY).filter((Y)=>Y!==void 0),J=Q.role==="tool"?"user":Q.role,X=Z[Z.length-1];if(J==="user"&&W.length>0&&W.every((Y)=>Y.type==="tool_result")&&X?.role==="user"&&Array.isArray(X.content)&&X.content.every((Y)=>Y.type==="tool_result")){X.content.push(...W);continue}Z.push({role:J,content:W})}return Z}function z_($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function T_($){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 dY($)}}function dY($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function lY($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let Z=$.metadata;return{type:"thinking",thinking:$.text,signature:Z?.signature,details:Z?.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 Z=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:Z?.thoughtSignature??Z?.signature}}case"tool-result":{let Z=$.output,Q=typeof Z==="string"?Z:Array.isArray(Z)?Z:JSON.stringify(Z);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function cY($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function O_($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var uY=0;function q_(){return uY+=1,`msg_${Date.now().toString(36)}_${uY.toString(36)}`}function M_($){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 Z=$.tool_call.function,Q=Z.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??Z.id,toolName:Z.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.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:R_($),error:$.error}];default:return[]}}function R_($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function pY($){return{async*stream(Z){let Q=!1,W=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(Z.signal);let X=a6(Z.messages),Y=Z.tools.map((j)=>({name:j.name,description:j.description,inputSchema:j.inputSchema}));for await(let j of J.createMessage(Z.systemPrompt??"",X,Y))for(let V of M_(j)){if(V.type==="finish")Q=!0;else if(V.type==="tool-call-delta")W=!0;yield V}if(!Q)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(J){if(!Q)yield{type:"finish",reason:Z.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function S_($){let Z=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(Z).length>0?Z:void 0}function b_($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function y_($){let Z={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(b_($))Object.assign(Z,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(Z,{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 Q=$.gcp?.region??$.region;Object.assign(Z,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}if($.providerId==="sapaicore")Object.assign(Z,$.sap);return S_(Z)}function PQ($){let Z=$.providerConfig;if(Z?.knownModels)return Z.knownModels;if($.knownModels)return $.knownModels;return C_[$.providerId]?.models??void 0}function h_($){if(!$?.length)return;let Z=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":Z.add(Q);break;case"structured_output":Z.add("structured-output");break;default:Z.add("text")}return Z.add("text"),[...Z]}function k_($,Z){return{id:$,name:Z.name??$,description:Z.description,contextWindow:Z.contextWindow,maxInputTokens:Z.maxInputTokens,maxOutputTokens:Z.maxTokens,capabilities:h_(Z.capabilities),metadata:{family:Z.family,pricing:Z.pricing,status:Z.status,releaseDate:Z.releaseDate}}}function rY($,Z,Q){let W=$.providerConfig,J=W?.providerId===$.providerId?W:void 0,X={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:PQ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:Z,extensionContext:$.extensionContext};if(w_(P_(X.providerId)))return pY(()=>N_(X));return E_({fetch:X.fetch,providerConfigs:[{providerId:X.providerId,apiKey:X.apiKey,baseUrl:X.baseUrl,headers:X.headers,fetch:X.fetch,options:y_(X),models:X.knownModels?Object.entries(X.knownModels).map(([Y,j])=>k_(Y,j)):void 0}],logger:Z,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:X.providerId,modelId:X.modelId},{maxTokens:X.maxOutputTokens})}import{createMediaBudgetState as I_,IMAGE_OMITTED_PLACEHOLDER as iY,normalizeUserInput as nY,resolveMediaBudget as x_,validateAndReserveImageMedia as g_}from"@cline/shared";var m_=8000,v_=50000,c_=6000000,u_=200000,d_=12000,l_=65536,T8=2000,aY=40000,p_=8,SQ={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},r_=new Set(["read","read_files"]),E$="[outdated - see the latest file content]",sY="Tool execution was interrupted before a result was produced.",oY=($)=>`
141
+ `)}catch(F){if(clearTimeout(G),F instanceof Error){if(F.name==="AbortError")throw Error(`Request timed out after ${Z}ms`);throw F}throw Error(`Fetch failed: ${String(F)}`)}finally{if(V.signal&&K)V.signal.removeEventListener("abort",K)}}}function CQ($={}){return D8($)}function n6($={}){return{readFile:u6($.fileRead),search:r6($.search),bash:CQ($.bash),webFetch:i6($.webFetch),applyPatch:m6($.applyPatch),editor:v6($.editor)}}var __={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"},L8=[{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 gY($,Z){if(!Z||Z.length===0)return!0;let Q=$.toLowerCase();return Z.some((W)=>Q.includes(W.toLowerCase()))}function z_($,Z,Q,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return gY(Z,$.providerIdIncludes)&&gY(Q,$.modelIdIncludes)}function _8($,Z,Q,W){if(!W||W.length===0)return{};let J=new Map;for(let Y of W){if(!z_(Y,$,Z,Q))continue;for(let j of Y.disableTools??[])J.set(j,!1);for(let j of Y.enableTools??[])J.set(j,!0)}let X={};for(let[Y,j]of J.entries())X[__[Y]]=j;return X}var e0={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 u1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function mY($){if($!=="yolo")return{};let Z={enabled:!0,autoApprove:!0},Q={"*":Z};for(let W of U2)Q[W]=Z;return Q}function vY($,Z){let Q=e0[$],{enableSpawnAgent:W,enableAgentTeams:J,...X}=Q;return T2({...X,...Z})}import{createTool as kz,zodToJsonSchema as Iz}from"@cline/shared";import{z as cQ}from"zod";r0();import{createAgentRuntime as qz}from"@cline/agents";import{createContributionRegistry as Mz,mergeModelOptions as Yj}from"@cline/shared";import{createGateway as P_,createHandlerAsync as S_,hasRegisteredHandler as b_,MODEL_COLLECTIONS_BY_PROVIDER_ID as y_,normalizeProviderId as h_}from"@cline/llms";import{EMPTY_CONTENT_TEXT as T_}from"@cline/shared";function O_($){let Z=M_($.content),Q=[],W=$.id??N_(),J=0,X=[],Y=()=>{if(X.length===0)return;let j=J===0?W:`${W}_part_${J}`;J+=1,Q.push({id:j,role:$.role,content:X.map(R_),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:cY($.metrics)}),X=[]};if(Z.length===0)return Q.push({id:W,role:$.role,content:[{type:"text",text:T_}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:cY($.metrics)}),Q;for(let j of Z){if(j.type!=="tool_result"){X.push(j);continue}Y(),Q.push({id:`${W}_tool_${j.tool_use_id}`,role:"tool",content:[dY(j)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return Y(),Q}function a6($){return $.flatMap(O_)}function q_($){let Z=$.content.map(lY).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:Z,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:E_($.metrics)}}function q2($){return $.map(q_)}function s6($){let Z=[];for(let Q of $){let W=Q.content.map(lY).filter((Y)=>Y!==void 0),J=Q.role==="tool"?"user":Q.role,X=Z[Z.length-1];if(J==="user"&&W.length>0&&W.every((Y)=>Y.type==="tool_result")&&X?.role==="user"&&Array.isArray(X.content)&&X.content.every((Y)=>Y.type==="tool_result")){X.content.push(...W);continue}Z.push({role:J,content:W})}return Z}function M_($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function R_($){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 dY($)}}function dY($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function lY($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let Z=$.metadata;return{type:"thinking",thinking:$.text,signature:Z?.signature,details:Z?.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 Z=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:Z?.thoughtSignature??Z?.signature}}case"tool-result":{let Z=$.output,Q=typeof Z==="string"?Z:Array.isArray(Z)?Z:JSON.stringify(Z);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function cY($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function E_($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var uY=0;function N_(){return uY+=1,`msg_${Date.now().toString(36)}_${uY.toString(36)}`}function w_($){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 Z=$.tool_call.function,Q=Z.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??Z.id,toolName:Z.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.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:C_($),error:$.error}];default:return[]}}function C_($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function pY($){return{async*stream(Z){let Q=!1,W=!1;try{let J=typeof $==="function"?await $():$;J.setAbortSignal?.(Z.signal);let X=s6(Z.messages),Y=Z.tools.map((j)=>({name:j.name,description:j.description,inputSchema:j.inputSchema}));for await(let j of J.createMessage(Z.systemPrompt??"",X,Y))for(let V of w_(j)){if(V.type==="finish")Q=!0;else if(V.type==="tool-call-delta")W=!0;yield V}if(!Q)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(J){if(!Q)yield{type:"finish",reason:Z.signal?.aborted?"aborted":"error",error:J instanceof Error?J.message:String(J)}}}}}function k_($){let Z=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(Z).length>0?Z:void 0}function I_($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function x_($){let Z={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(I_($))Object.assign(Z,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(Z,{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 Q=$.gcp?.region??$.region;Object.assign(Z,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}if($.providerId==="sapaicore")Object.assign(Z,$.sap);return k_(Z)}function PQ($){let Z=$.providerConfig;if(Z?.knownModels)return Z.knownModels;if($.knownModels)return $.knownModels;return y_[$.providerId]?.models??void 0}function g_($){if(!$?.length)return;let Z=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":Z.add(Q);break;case"structured_output":Z.add("structured-output");break;default:Z.add("text")}return Z.add("text"),[...Z]}function m_($,Z){return{id:$,name:Z.name??$,description:Z.description,contextWindow:Z.contextWindow,maxInputTokens:Z.maxInputTokens,maxOutputTokens:Z.maxTokens,capabilities:g_(Z.capabilities),metadata:{family:Z.family,pricing:Z.pricing,status:Z.status,releaseDate:Z.releaseDate}}}function rY($,Z,Q){let W=$.providerConfig,J=W?.providerId===$.providerId?W:void 0,X={...J??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??J?.apiKey,baseUrl:$.baseUrl??J?.baseUrl,headers:$.headers??J?.headers,knownModels:PQ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:Z,extensionContext:$.extensionContext};if(b_(h_(X.providerId)))return pY(()=>S_(X));return P_({fetch:X.fetch,providerConfigs:[{providerId:X.providerId,apiKey:X.apiKey,baseUrl:X.baseUrl,headers:X.headers,fetch:X.fetch,options:x_(X),models:X.knownModels?Object.entries(X.knownModels).map(([Y,j])=>m_(Y,j)):void 0}],logger:Z,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:X.providerId,modelId:X.modelId},{maxTokens:X.maxOutputTokens})}import{createMediaBudgetState as v_,IMAGE_OMITTED_PLACEHOLDER as iY,normalizeUserInput as nY,resolveMediaBudget as c_,validateAndReserveImageMedia as u_}from"@cline/shared";var d_=8000,l_=50000,p_=6000000,r_=200000,i_=12000,n_=65536,T8=2000,aY=40000,a_=8,SQ={maxToolResultChars:"CLINE_MESSAGE_BUILDER_MAX_TOOL_RESULT_CHARS",maxTotalTextBytes:"CLINE_MESSAGE_BUILDER_MAX_TOTAL_TEXT_BYTES",minOutdatedRewriteBytes:"CLINE_MESSAGE_BUILDER_MIN_OUTDATED_REWRITE_BYTES"},s_=new Set(["read","read_files"]),N$="[outdated - see the latest file content]",sY="Tool execution was interrupted before a result was produced.",oY=($)=>`
142
142
 
143
143
  ...[truncated ${$} chars]...
144
144
 
@@ -146,7 +146,7 @@ Searched ${L} files.`;let D=[`Found ${A.length} result${A.length===1?"":"s"} for
146
146
 
147
147
  ...[truncated ${$} chars to fit provider request budget]...
148
148
 
149
- `,i_=($)=>`
149
+ `,o_=($)=>`
150
150
 
151
151
  ...[assistant text truncated: omitted ${$} chars]...
152
152
 
@@ -154,16 +154,16 @@ Searched ${L} files.`;let D=[`Found ${A.length} result${A.length===1?"":"s"} for
154
154
 
155
155
  ...[assistant text truncated: omitted ${$} chars to fit provider request budget]...
156
156
 
157
- `,n_=($)=>`
157
+ `,t_=($)=>`
158
158
 
159
159
  ...[assistant text truncated: omitted ${$} chars due to repeated tool-call markup]...
160
160
 
161
- `;function Zj($=process.env){return{maxToolResultChars:$j($[SQ.maxToolResultChars]),maxTotalTextBytes:$j($[SQ.maxTotalTextBytes]),minOutdatedRewriteBytes:s_($[SQ.minOutdatedRewriteBytes])}}class yQ{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=z8($.maxToolResultChars,m_),this.maxFileContentChars=z8($.maxFileContentChars,v_),this.maxTotalTextBytes=z8($.maxTotalTextBytes,c_),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=z8($.maxAssistantTextChars,u_),this.maxAssistantToolMarkupChars=z8($.maxAssistantToolMarkupChars,d_),this.minOutdatedRewriteBytes=o_($.minOutdatedRewriteBytes,l_)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Q=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let j=nY(J.content);if(j!==J.content)return{...J,content:j}}if(J.role==="assistant"&&typeof J.content==="string"){let j=this.truncateAssistantText(J.content);if(j!==J.content)return{...J,content:j}}return J}let X=!1,Y=J.content.map((j)=>{let V=this.transformBlock(j,J.role);if(V!==j)X=!0;return V});return X?{...J,content:Y}:J}),W=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(W)}transformBlock($,Z){if(Z==="user"&&$.type==="text"&&typeof $.text==="string"){let J=nY($.text);if(J!==$.text)return{...$,text:J};return $}if(Z==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=M2($.content,this.maxFileContentChars,oY);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Q=this.resolveToolName($),W=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let Y=this.getReadLocators($).filter((j)=>J.has(this.toReadLocatorKey(j))&&this.isOutdatedReadLocator(j,$.tool_use_id));if(Y.length>0)W=this.replaceOutdatedReadContent(W,Y)}}return W=this.truncateToolResultContent(W),W===$.content?$:{...$,content:W}}reindex($){let Z=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!Z)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let W=$[Q];if(!Array.isArray(W.content))continue;for(let J=0;J<W.content.length;J++){let X=W.content[J];if(X.type==="file")this.latestFullContentOwnerByPathCache.set(X.path,`file:${Q}:${J}`);else if(X.type==="tool_use"){let Y=X.name.toLowerCase();if(this.toolNameByIdCache.set(X.id,Y),this.isReadTool(Y)){let j=this.extractLocatorsFromReadToolInput(X.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(X.id,j)}}else if(X.type==="tool_result"){let Y=this.resolveToolName(X);if(!this.isReadTool(Y)||X.is_error===!0)continue;let j=this.getReadLocators(X);for(let V of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),X.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,X.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let Z=new Map,Q=new Set,W=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let X of J.content){if(X.type!=="tool_result"||X.is_error===!0)continue;let Y=this.resolveToolName(X);if(!this.isReadTool(Y))continue;Q.add(X.tool_use_id);let j=this.committedOutdatedRewrites.get(X.tool_use_id),V=new Set,H=new Set;for(let G of this.getReadLocators(X)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,X.tool_use_id))continue;if(H.add(K),!j?.has(K))V.add(K)}if(j){for(let G of j)if(!H.has(G))j.delete(G);if(j.size===0)this.committedOutdatedRewrites.delete(X.tool_use_id)}if(V.size===0)continue;let B=Z.get(X.tool_use_id);if(!B)B=new Set,Z.set(X.tool_use_id,B);for(let G of V)B.add(G);W+=this.estimateOutdatedReclaimBytes(X.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Q.has(J))this.committedOutdatedRewrites.delete(J);if(Z.size===0||W<this.minOutdatedRewriteBytes)return;for(let[J,X]of Z){let Y=this.committedOutdatedRewrites.get(J);if(!Y)Y=new Set,this.committedOutdatedRewrites.set(J,Y);for(let j of X)Y.add(j)}}estimateOutdatedReclaimBytes($,Z){let Q=this.extractReadLocatorsFromToolResultContent($),W=Q.length>0&&Q.every((V)=>Z.has(this.toReadLocatorKey(V))),J=(V)=>{let H;try{H=JSON.parse(V)}catch{return W||Q.length===0?e(this.truncateMiddle(V)):0}let B=Array.isArray(H)?H:[H],G=0;for(let K of B){let F=this.extractLocatorFromResultEntry(K);if(F&&Z.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let X=new Set(Z),Y=0;for(let V of $)if(V.type==="text")Y+=this.countOutdatedImageEntries(V.text,X);let j=0;for(let V of $)if(V.type==="text")j+=J(V.text);else if(V.type==="image"){if(Y>0)Y-=1,j+=e(V.data)}else if(d1(V)){let H=this.extractLocatorFromResultEntry(V);if(H&&Z.has(this.toReadLocatorKey(H)))j+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(Z.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))j+=e(this.truncateMiddle(V.content))}return j}providerBoundEntryBytes($){let Z=this.truncateNestedStrings($);return e(JSON.stringify(Z))}addMissingToolResults($){let Z=this.collectToolResultIds($),Q=[],W=new Map,J=!1,X=()=>{if(W.size===0)return;Y(this.createMissingToolResultMessage(W)),W.clear(),J=!0},Y=(j)=>{let V=Q.at(-1);if(this.shouldMergeUserAfterToolResults(V,j)){Q[Q.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(j.content)]},J=!0;return}Q.push(j)};for(let j of $){if(this.isToolResultOnlyMessage(j)){if(Y(this.appendMissingToolResults(j,W)),W.size>0)W.clear(),J=!0;continue}if(Array.isArray(j.content)){let V=j.content.filter((B)=>B.type==="tool_result"),H=j.content.filter((B)=>B.type!=="tool_result");if(V.length>0){let B=this.appendMissingToolResults({...j,role:"user",content:V},W);if(Y(B),W.size>0)W.clear();J=!0}if(H.length>0||V.length===0){if(V.length===0)X();let B=V.length>0?{...j,content:H}:j;if(Y(B),B.role==="assistant")this.trackMissingToolCalls(B,Z,W)}continue}X(),Y(j)}return X(),J?Q:$}appendMissingToolResults($,Z){if(Z.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(Z)]}}shouldMergeUserAfterToolResults($,Z){return $?.role==="user"&&Z.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(Z.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let Z=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let W of Q.content)if(W.type==="tool_result")Z.add(W.tool_use_id)}return Z}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((Z)=>Z.type==="tool_result")}trackMissingToolCalls($,Z,Q){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||Z.has(W.id))continue;Q.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([Z,Q])=>({type:"tool_result",tool_use_id:Z,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${sY} Tool: ${$}.`:sY}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 Z=$,Q=this.readResultLocatorCache.get(Z);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(Z,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let Z=$,Q=[],W=this.extractLocatorFromReadRequest(Z);if(W)Q.push(W);if(Array.isArray(Z.files))for(let J of Z.files){let X=this.extractLocatorFromReadRequest(J);if(X)Q.push(X)}if(Array.isArray(Z.file_paths)){for(let J of Z.file_paths)if(typeof J==="string"&&J.length>0)Q.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let Z=[];for(let Q of $){if(Q.type==="text"){Z.push(...this.tryParseReadLocators(Q.text));continue}if(d1(Q)){let W=this.extractLocatorFromResultEntry(Q);if(W)Z.push(W)}}return this.dedupeReadLocators(Z)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let W of $){let J=this.extractLocatorFromResultEntry(W);if(J)Q.push(J)}return this.dedupeReadLocators(Q)}let Z=this.extractLocatorFromResultEntry($);return Z?[Z]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let Z=$,Q=this.extractPath(Z);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(Z.start_line),endLine:this.extractLineNumber(Z.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let Z=$,Q=this.extractPath(Z);if(Q)return{path:Q,startLine:this.extractLineNumber(Z.start_line),endLine:this.extractLineNumber(Z.end_line)};if(typeof Z.query==="string"&&Z.query.length>0)return this.parseReadQuery(Z.query);return}extractPath($){let Z=[$.path,$.file_path,$.filePath];for(let Q of Z)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let Z=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!Z)return{path:$,startLine:null,endLine:null};return{path:Z[1],startLine:Number(Z[2]),endLine:Z[3]==="EOF"?null:Number(Z[3])}}dedupeReadLocators($){let Z=new Map;for(let Q of $)Z.set(this.toReadLocatorKey(Q),Q);return Array.from(Z.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,Z){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==Z)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==Z}replaceOutdatedReadContent($,Z){let Q=new Set(Z.map((X)=>this.toReadLocatorKey(X))),W=new Set(Z.map((X)=>X.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??E$;let J=0;for(let X of $)if(X.type==="text")J+=this.countOutdatedImageEntries(X.text,Q);return $.map((X)=>{if(X.type==="file"){if(!W.has(X.path))return X;return{...X,content:E$}}if(X.type==="image"){if(J===0)return X;return J-=1,{type:"text",text:E$}}if(d1(X))return this.replaceOutdatedReadEntry(X,Q);if(X.type!=="text")return X;let Y=this.replaceOutdatedInString(X.text,Q);if(Y===null)return{...X,text:E$};return Y===X.text?X:{...X,text:Y}})}countOutdatedImageEntries($,Z){let Q;try{Q=JSON.parse($)}catch{return 0}let W=Array.isArray(Q)?Q:[Q],J=0;for(let X of W){if(!X||typeof X!=="object")continue;let Y=X,j=this.extractLocatorFromResultEntry(Y);if(!j)continue;if(!Z.has(this.toReadLocatorKey(j)))continue;if(Y.result==="Successfully read image"||Y.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,Z){let Q;try{Q=JSON.parse($)}catch{return null}let W=Array.isArray(Q)?Q.map((J)=>this.replaceOutdatedReadEntry(J,Z)):this.replaceOutdatedReadEntry(Q,Z);return JSON.stringify(W)}replaceOutdatedReadEntry($,Z){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!Z.has(this.toReadLocatorKey(Q)))return $;let W={...$};if(typeof W.result==="string")W.result=E$;else if(typeof W.content==="string")W.content=E$;else W.result=E$;return W}isReadTool($){return!!$&&r_.has($)}resolveToolName($){let Z=this.toolNameByIdCache.get($.tool_use_id);if(Z!==void 0)return Z;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((Z)=>{if(Z.type==="file"){let Q=this.truncateMiddle(Z.content);return Q===Z.content?Z:{...Z,content:Q}}if(Z.type==="text"){let Q=this.truncateMiddle(Z.text);return Q===Z.text?Z:{...Z,text:Q}}if(d1(Z))return this.truncateNestedStrings(Z);return Z})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let Z=!1,Q=$.map((W)=>{let J=this.truncateNestedStrings(W);if(J!==W)Z=!0;return J});return Z?Q:$}if($!==null&&typeof $==="object"){if(hQ($))return $;let Z=!1,Q={};for(let[W,J]of Object.entries($)){let X=this.truncateNestedStrings(J);if(X!==J)Z=!0;Q[W]=X}return Z?Q:$}return $}truncateMiddle($){return M2($,this.maxToolResultChars,oY)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return M2($,this.maxAssistantToolMarkupChars,n_);return M2($,this.maxAssistantTextChars,i_)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let Z=0;for(let Q of $.matchAll(a_))if(Z+=1,Z>=p_)return!0;return!1}truncateToTotalTextBudget($){let Z=this.countMessageTextBytes($);if(Z<=this.maxTotalTextBytes)return $;let Q=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((X)=>e_(X))}}),W=this.collectTruncationCandidates(Q);for(let J of W){if(Z<=this.maxTotalTextBytes)break;let X=J.byteLength;if(X<=J.minBytes)continue;let Y=Z-this.maxTotalTextBytes,j=Math.max(J.minBytes,X-Y),V=t_(J.get(),j,J.makeMarker);J.set(V),Z-=X-e(V)}return Q}countMessageTextBytes($){let Z=0;for(let Q of $){if(typeof Q.content==="string"){Z+=e(Q.content);continue}for(let W of Q.content)if(W.type==="text")Z+=e(W.text);else if(W.type==="thinking")Z+=e(W.thinking);else if(W.type==="file")Z+=e(W.content);else if(W.type==="tool_use")Z+=s6(W.input);else if(W.type==="tool_result"){if(typeof W.content==="string")Z+=e(W.content);else for(let J of W.content)if(J.type==="text")Z+=e(J.text);else if(J.type==="file")Z+=e(J.content);else if(d1(J))Z+=s6(J)}}return Z}collectTruncationCandidates($){let Z=[],Q=[];for(let W of $){if(W.role==="assistant"&&typeof W.content==="string"){Z.push({byteLength:e(W.content),minBytes:aY,makeMarker:tY,get:()=>W.content,set:(J)=>{W.content=J}});continue}if(!Array.isArray(W.content))continue;for(let J of W.content){if(J.type==="tool_use"){o6(J.input,Q);continue}if(W.role==="assistant"&&J.type==="text"){Z.push({byteLength:e(J.text),minBytes:aY,makeMarker:tY,get:()=>J.text,set:(X)=>{J.text=X}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){Z.push({byteLength:e(J.content),minBytes:T8,makeMarker:O8,get:()=>J.content,set:(X)=>{J.content=X}});continue}for(let X of J.content)if(X.type==="text")Z.push({byteLength:e(X.text),minBytes:T8,makeMarker:O8,get:()=>X.text,set:(Y)=>{X.text=Y}});else if(X.type==="file")Z.push({byteLength:e(X.content),minBytes:T8,makeMarker:O8,get:()=>X.content,set:(Y)=>{X.content=Y}});else if(d1(X))o6(X,Z)}}return Z.sort((W,J)=>J.byteLength-W.byteLength),Q.sort((W,J)=>J.byteLength-W.byteLength),[...Z,...Q]}applyMediaBudget($){let Z=this.resolveMediaBudget();if(Z.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&Z.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&Z.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=I_(),W=!1,J=$.map((X)=>{if(!Array.isArray(X.content))return X;let Y=!1,j=X.content.map((V)=>{let H=this.applyMediaBudgetToBlock(V,Z,Q);if(H!==V)Y=!0;return H});if(!Y)return X;return W=!0,{...X,content:j}});return W?J:$}resolveMediaBudget(){return x_(this.mediaBudget)}applyMediaBudgetToBlock($,Z,Q){if(bQ($))return this.limitImageContent($,Z,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let W=!1,J=$.content.map((X)=>{let Y=this.applyMediaBudgetToToolResultEntry(X,Z,Q);if(Y!==X)W=!0;return Y});return W?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,Z,Q){if(bQ($))return this.limitImageContent($,Z,Q);if(d1($))return this.limitNestedMedia($,Z,Q);return $}limitNestedMedia($,Z,Q){if(bQ($)){let W=this.limitImageContent($,Z,Q);return W.type==="text"?W.text:W}if(Array.isArray($)){let W=!1,J=$.map((X)=>{let Y=this.limitNestedMedia(X,Z,Q);if(Y!==X)W=!0;return Y});return W?J:$}if($!==null&&typeof $==="object"){let W=!1,J={};for(let[X,Y]of Object.entries($)){let j=this.limitNestedMedia(Y,Z,Q);if(j!==Y)W=!0;J[X]=j}return W?J:$}return $}limitImageContent($,Z,Q){if(!Qj($))return{type:"text",text:iY};let W=g_($.mediaType,$.data,{maxImageEncodedBytes:Z.maxImageEncodedBytes,maxImageDecodedBytes:Z.maxImageDecodedBytes,maxTotalMediaBytes:Z.maxTotalMediaBytes},Q);if(!W.ok)return{type:"text",text:iY};return{...$,data:W.base64,mediaType:W.mediaType}}}var eY=String.raw`[\|\uFF5C]`,a_=new RegExp(String.raw`<\s*(?:${eY}\s*)?DSML\s*(?:${eY}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function e($){return Buffer.byteLength($,"utf8")}function $j($){if($===void 0)return;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:void 0}function s_($){if($===void 0)return;let Z=$.trim().toLowerCase();if(Z==="infinity"||Z==="disable")return Number.POSITIVE_INFINITY;let Q=Number.parseInt($,10);return Number.isFinite(Q)&&Q>=0?Q:void 0}function z8($,Z){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):Z}function o_($,Z){if(typeof $!=="number"||Number.isNaN($)||$<0)return Z;return Number.isFinite($)?Math.floor($):$}function M2($,Z,Q){if($.length<=Z)return $;let W=Q($.length-Z),J=Math.max(0,Math.floor((Z-W.length)/2)),X=Math.max(0,$.length-J*2),Y=Q(X),j=Math.max(0,Math.floor((Z-Y.length)/2)),V=$.slice(0,j),H=j>0?$.slice(-j):"";return`${V}${Y}${H}`}function t_($,Z,Q){if(e($)<=Z)return $;let W=0,J=$.length,X=M2($,0,Q);while(W<=J){let Y=W+J>>>1,j=M2($,Y,Q);if(e(j)<=Z)X=j,W=Y+1;else J=Y-1}return X}function e_($){if($.type==="tool_use")return{...$,input:t6($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((Z)=>d1(Z)?t6(Z):{...Z})}}function d1($){if($===null||typeof $!=="object")return!1;let Z=$.type;return Z!=="text"&&Z!=="image"&&Z!=="file"}function bQ($){return $!==null&&typeof $==="object"&&$.type==="image"}function Qj($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function hQ($){return Qj($)}function s6($){if(typeof $==="string")return e($);if(Array.isArray($)){let Z=0;for(let Q of $)Z+=s6(Q);return Z}if($!==null&&typeof $==="object"){if(hQ($))return 0;let Z=0;for(let Q of Object.values($))Z+=s6(Q);return Z}return 0}function o6($,Z){if(Array.isArray($)){$.forEach((Q,W)=>{if(typeof Q==="string")Z.push({byteLength:e(Q),minBytes:T8,makeMarker:O8,get:()=>$[W],set:(J)=>{$[W]=J}});else o6(Q,Z)});return}if($!==null&&typeof $==="object"){if(hQ($))return;let Q=$;for(let W of Object.keys(Q)){let J=Q[W];if(typeof J==="string")Z.push({byteLength:e(J),minBytes:T8,makeMarker:O8,get:()=>Q[W],set:(X)=>{Q[W]=X}});else o6(J,Z)}}}function t6($){if(Array.isArray($))return $.map(t6);if($!==null&&typeof $==="object"){let Z={};for(let[Q,W]of Object.entries($))Z[Q]=t6(W);return Z}return $}function kQ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class IQ{messages=[];conversationId=kQ();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=kQ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=kQ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function Wj($){let{agentConfig:Z}=$,Q=$z(Z),W=Zz(Z),J=$.hooks,X=Qz(Z.maxParallelToolCalls);return{sessionId:$.sessionId??Z.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??Z.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:Q,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:Z.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??Z.logger,telemetry:$.telemetry??Z.telemetry,initialMessages:$.initialMessages,completionPolicy:Z.completionPolicy,maxIterations:Z.maxIterations,toolExecution:X,toolPolicies:Z.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:Z.requestToolApproval}}function $z($){let Z={};if($.thinking!==void 0)Z.thinking=$.thinking;if($.reasoningEffort!==void 0)Z.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)Z.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)Z.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)Z.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(Z).length>0?Z:void 0}function Zz($){let Z=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:Z}}function Qz($){if($===void 0)return;return $>=2?"parallel":"sequential"}function Wz(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function Jz($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function xQ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(xQ);let Z={};for(let Q of Object.keys($).sort())Z[Q]=xQ($[Q]);return Z}function Xz($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(xQ($))}catch{return String($)}}function Yz($,Z,Q,W){if(Z===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=Z,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var Jj={softThreshold:3,hardThreshold:5};class gQ{config;state=Wz();constructor($){this.config={softThreshold:$?.softThreshold??Jj.softThreshold,hardThreshold:$?.hardThreshold??Jj.hardThreshold}}inspect($){let Z=Xz($.input),Q=Yz(this.state,$.name,Z,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){Jz(this.state)}}class mQ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let Z=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&Z?Z:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let W=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(W),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:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!Z||Q<Z)return{action:"continue"};let J=await Vz({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:Z,reason:$.reason,details:$.details},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:jz({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:Z,reason:$.reason,details:$.details,stopReason:J.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function jz($){let Z=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)Z.push(`Error: ${Q}`);let W=$.stopReason?.trim();if(W)Z.push(`Decision: ${W}`);return Z.push("Session state was preserved. Send a new prompt to resume from the latest state."),Z.join(" ")}async function Vz($,Z){if(!Z)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await Z($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function Hz($){let Z=$.content.filter((Q)=>Q.type==="text");if(Z.length===0)return;return Z.map((Q)=>Q.text).join("")}function Bz($){let Z=$.content.filter((Q)=>Q.type==="reasoning");if(Z.length===0)return;return{reasoning:Z.map((Q)=>Q.text).join(""),redacted:Z.some((Q)=>Q.redacted===!0)}}function Gz($){return $.content.find((Z)=>Z.type==="tool-result")}function Kz($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function Fz($){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 vQ{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:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,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 Z=[],Q=Hz($);if(Q!==void 0)Z.push({type:"content_end",contentType:"text",text:Q});let W=Bz($);if(W!==void 0)Z.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return Z}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 Z=this.toolStartedAt.get($.toolCall.toolCallId),Q=Z===void 0?void 0:Date.now()-Z;this.toolStartedAt.delete($.toolCall.toolCallId);let W=Gz($.message),J=W?.output,X=Fz(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:X,durationMs:Q}]}translateUsage($){let Z=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,X=this.lastUsage.totalCost??0,j=($.totalCost??0)-X;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,Z),outputTokens:Math.max(0,Q),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:j===0?void 0:j,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let Z={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:Kz($.status),text:$.outputText,iterations:$.iterations,usage:Z}]}}function Tz($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function Oz($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function qz($,Z){let Q=$.trim(),W=Z.map((J)=>J.trim()).filter(Boolean).join(`
161
+ `;function Zj($=process.env){return{maxToolResultChars:$j($[SQ.maxToolResultChars]),maxTotalTextBytes:$j($[SQ.maxTotalTextBytes]),minOutdatedRewriteBytes:$z($[SQ.minOutdatedRewriteBytes])}}class yQ{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=z8($.maxToolResultChars,d_),this.maxFileContentChars=z8($.maxFileContentChars,l_),this.maxTotalTextBytes=z8($.maxTotalTextBytes,p_),this.mediaBudget=$.mediaBudget??{},this.maxAssistantTextChars=z8($.maxAssistantTextChars,r_),this.maxAssistantToolMarkupChars=z8($.maxAssistantToolMarkupChars,i_),this.minOutdatedRewriteBytes=Zz($.minOutdatedRewriteBytes,n_)}resetConversationState(){this.resetIndexes(),this.committedOutdatedRewrites.clear()}buildForApi($){this.reindex($),this.commitOutdatedRewrites($);let Q=this.addMissingToolResults($).map((J)=>{if(!Array.isArray(J.content)){if(J.role==="user"&&typeof J.content==="string"){let j=nY(J.content);if(j!==J.content)return{...J,content:j}}if(J.role==="assistant"&&typeof J.content==="string"){let j=this.truncateAssistantText(J.content);if(j!==J.content)return{...J,content:j}}return J}let X=!1,Y=J.content.map((j)=>{let V=this.transformBlock(j,J.role);if(V!==j)X=!0;return V});return X?{...J,content:Y}:J}),W=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(W)}transformBlock($,Z){if(Z==="user"&&$.type==="text"&&typeof $.text==="string"){let J=nY($.text);if(J!==$.text)return{...$,text:J};return $}if(Z==="assistant"&&$.type==="text"&&typeof $.text==="string"){let J=this.truncateAssistantText($.text);return J===$.text?$:{...$,text:J}}if($.type==="file"){let J=M2($.content,this.maxFileContentChars,oY);return J===$.content?$:{...$,content:J}}if($.type!=="tool_result")return $;let Q=this.resolveToolName($),W=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let J=this.committedOutdatedRewrites.get($.tool_use_id);if(J&&J.size>0){let Y=this.getReadLocators($).filter((j)=>J.has(this.toReadLocatorKey(j))&&this.isOutdatedReadLocator(j,$.tool_use_id));if(Y.length>0)W=this.replaceOutdatedReadContent(W,Y)}}return W=this.truncateToolResultContent(W),W===$.content?$:{...$,content:W}}reindex($){let Z=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!Z)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let W=$[Q];if(!Array.isArray(W.content))continue;for(let J=0;J<W.content.length;J++){let X=W.content[J];if(X.type==="file")this.latestFullContentOwnerByPathCache.set(X.path,`file:${Q}:${J}`);else if(X.type==="tool_use"){let Y=X.name.toLowerCase();if(this.toolNameByIdCache.set(X.id,Y),this.isReadTool(Y)){let j=this.extractLocatorsFromReadToolInput(X.input);if(j.length>0)this.readLocatorsByToolUseIdCache.set(X.id,j)}}else if(X.type==="tool_result"){let Y=this.resolveToolName(X);if(!this.isReadTool(Y)||X.is_error===!0)continue;let j=this.getReadLocators(X);for(let V of j)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(V),X.tool_use_id),this.isFullFileRead(V))this.latestFullContentOwnerByPathCache.set(V.path,X.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}commitOutdatedRewrites($){let Z=new Map,Q=new Set,W=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let X of J.content){if(X.type!=="tool_result"||X.is_error===!0)continue;let Y=this.resolveToolName(X);if(!this.isReadTool(Y))continue;Q.add(X.tool_use_id);let j=this.committedOutdatedRewrites.get(X.tool_use_id),V=new Set,H=new Set;for(let G of this.getReadLocators(X)){let K=this.toReadLocatorKey(G);if(!this.isOutdatedReadLocator(G,X.tool_use_id))continue;if(H.add(K),!j?.has(K))V.add(K)}if(j){for(let G of j)if(!H.has(G))j.delete(G);if(j.size===0)this.committedOutdatedRewrites.delete(X.tool_use_id)}if(V.size===0)continue;let B=Z.get(X.tool_use_id);if(!B)B=new Set,Z.set(X.tool_use_id,B);for(let G of V)B.add(G);W+=this.estimateOutdatedReclaimBytes(X.content,V)}}for(let J of this.committedOutdatedRewrites.keys())if(!Q.has(J))this.committedOutdatedRewrites.delete(J);if(Z.size===0||W<this.minOutdatedRewriteBytes)return;for(let[J,X]of Z){let Y=this.committedOutdatedRewrites.get(J);if(!Y)Y=new Set,this.committedOutdatedRewrites.set(J,Y);for(let j of X)Y.add(j)}}estimateOutdatedReclaimBytes($,Z){let Q=this.extractReadLocatorsFromToolResultContent($),W=Q.length>0&&Q.every((V)=>Z.has(this.toReadLocatorKey(V))),J=(V)=>{let H;try{H=JSON.parse(V)}catch{return W||Q.length===0?e(this.truncateMiddle(V)):0}let B=Array.isArray(H)?H:[H],G=0;for(let K of B){let F=this.extractLocatorFromResultEntry(K);if(F&&Z.has(this.toReadLocatorKey(F)))G+=this.providerBoundEntryBytes(K)}return G};if(typeof $==="string")return J($);let X=new Set(Z),Y=0;for(let V of $)if(V.type==="text")Y+=this.countOutdatedImageEntries(V.text,X);let j=0;for(let V of $)if(V.type==="text")j+=J(V.text);else if(V.type==="image"){if(Y>0)Y-=1,j+=e(V.data)}else if(d1(V)){let H=this.extractLocatorFromResultEntry(V);if(H&&Z.has(this.toReadLocatorKey(H)))j+=this.providerBoundEntryBytes(V)}else if(V.type==="file"){if(Z.has(this.toReadLocatorKey({path:V.path,startLine:null,endLine:null})))j+=e(this.truncateMiddle(V.content))}return j}providerBoundEntryBytes($){let Z=this.truncateNestedStrings($);return e(JSON.stringify(Z))}addMissingToolResults($){let Z=this.collectToolResultIds($),Q=[],W=new Map,J=!1,X=()=>{if(W.size===0)return;Y(this.createMissingToolResultMessage(W)),W.clear(),J=!0},Y=(j)=>{let V=Q.at(-1);if(this.shouldMergeUserAfterToolResults(V,j)){Q[Q.length-1]={...V,content:[...V.content,...this.contentBlocksForUserMerge(j.content)]},J=!0;return}Q.push(j)};for(let j of $){if(this.isToolResultOnlyMessage(j)){if(Y(this.appendMissingToolResults(j,W)),W.size>0)W.clear(),J=!0;continue}if(Array.isArray(j.content)){let V=j.content.filter((B)=>B.type==="tool_result"),H=j.content.filter((B)=>B.type!=="tool_result");if(V.length>0){let B=this.appendMissingToolResults({...j,role:"user",content:V},W);if(Y(B),W.size>0)W.clear();J=!0}if(H.length>0||V.length===0){if(V.length===0)X();let B=V.length>0?{...j,content:H}:j;if(Y(B),B.role==="assistant")this.trackMissingToolCalls(B,Z,W)}continue}X(),Y(j)}return X(),J?Q:$}appendMissingToolResults($,Z){if(Z.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(Z)]}}shouldMergeUserAfterToolResults($,Z){return $?.role==="user"&&Z.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(Z.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let Z=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let W of Q.content)if(W.type==="tool_result")Z.add(W.tool_use_id)}return Z}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((Z)=>Z.type==="tool_result")}trackMissingToolCalls($,Z,Q){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||Z.has(W.id))continue;Q.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([Z,Q])=>({type:"tool_result",tool_use_id:Z,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${sY} Tool: ${$}.`:sY}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 Z=$,Q=this.readResultLocatorCache.get(Z);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(Z,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let Z=$,Q=[],W=this.extractLocatorFromReadRequest(Z);if(W)Q.push(W);if(Array.isArray(Z.files))for(let J of Z.files){let X=this.extractLocatorFromReadRequest(J);if(X)Q.push(X)}if(Array.isArray(Z.file_paths)){for(let J of Z.file_paths)if(typeof J==="string"&&J.length>0)Q.push({path:J,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);let Z=[];for(let Q of $){if(Q.type==="text"){Z.push(...this.tryParseReadLocators(Q.text));continue}if(d1(Q)){let W=this.extractLocatorFromResultEntry(Q);if(W)Z.push(W)}}return this.dedupeReadLocators(Z)}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let W of $){let J=this.extractLocatorFromResultEntry(W);if(J)Q.push(J)}return this.dedupeReadLocators(Q)}let Z=this.extractLocatorFromResultEntry($);return Z?[Z]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let Z=$,Q=this.extractPath(Z);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(Z.start_line),endLine:this.extractLineNumber(Z.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let Z=$,Q=this.extractPath(Z);if(Q)return{path:Q,startLine:this.extractLineNumber(Z.start_line),endLine:this.extractLineNumber(Z.end_line)};if(typeof Z.query==="string"&&Z.query.length>0)return this.parseReadQuery(Z.query);return}extractPath($){let Z=[$.path,$.file_path,$.filePath];for(let Q of Z)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let Z=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!Z)return{path:$,startLine:null,endLine:null};return{path:Z[1],startLine:Number(Z[2]),endLine:Z[3]==="EOF"?null:Number(Z[3])}}dedupeReadLocators($){let Z=new Map;for(let Q of $)Z.set(this.toReadLocatorKey(Q),Q);return Array.from(Z.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,Z){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==Z)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==Z}replaceOutdatedReadContent($,Z){let Q=new Set(Z.map((X)=>this.toReadLocatorKey(X))),W=new Set(Z.map((X)=>X.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??N$;let J=0;for(let X of $)if(X.type==="text")J+=this.countOutdatedImageEntries(X.text,Q);return $.map((X)=>{if(X.type==="file"){if(!W.has(X.path))return X;return{...X,content:N$}}if(X.type==="image"){if(J===0)return X;return J-=1,{type:"text",text:N$}}if(d1(X))return this.replaceOutdatedReadEntry(X,Q);if(X.type!=="text")return X;let Y=this.replaceOutdatedInString(X.text,Q);if(Y===null)return{...X,text:N$};return Y===X.text?X:{...X,text:Y}})}countOutdatedImageEntries($,Z){let Q;try{Q=JSON.parse($)}catch{return 0}let W=Array.isArray(Q)?Q:[Q],J=0;for(let X of W){if(!X||typeof X!=="object")continue;let Y=X,j=this.extractLocatorFromResultEntry(Y);if(!j)continue;if(!Z.has(this.toReadLocatorKey(j)))continue;if(Y.result==="Successfully read image"||Y.content==="Successfully read image")J+=1}return J}replaceOutdatedInString($,Z){let Q;try{Q=JSON.parse($)}catch{return null}let W=Array.isArray(Q)?Q.map((J)=>this.replaceOutdatedReadEntry(J,Z)):this.replaceOutdatedReadEntry(Q,Z);return JSON.stringify(W)}replaceOutdatedReadEntry($,Z){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!Z.has(this.toReadLocatorKey(Q)))return $;let W={...$};if(typeof W.result==="string")W.result=N$;else if(typeof W.content==="string")W.content=N$;else W.result=N$;return W}isReadTool($){return!!$&&s_.has($)}resolveToolName($){let Z=this.toolNameByIdCache.get($.tool_use_id);if(Z!==void 0)return Z;return typeof $.name==="string"&&$.name.length>0?$.name.toLowerCase():void 0}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((Z)=>{if(Z.type==="file"){let Q=this.truncateMiddle(Z.content);return Q===Z.content?Z:{...Z,content:Q}}if(Z.type==="text"){let Q=this.truncateMiddle(Z.text);return Q===Z.text?Z:{...Z,text:Q}}if(d1(Z))return this.truncateNestedStrings(Z);return Z})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let Z=!1,Q=$.map((W)=>{let J=this.truncateNestedStrings(W);if(J!==W)Z=!0;return J});return Z?Q:$}if($!==null&&typeof $==="object"){if(hQ($))return $;let Z=!1,Q={};for(let[W,J]of Object.entries($)){let X=this.truncateNestedStrings(J);if(X!==J)Z=!0;Q[W]=X}return Z?Q:$}return $}truncateMiddle($){return M2($,this.maxToolResultChars,oY)}truncateAssistantText($){if(this.hasRepeatedToolCallMarkup($))return M2($,this.maxAssistantToolMarkupChars,t_);return M2($,this.maxAssistantTextChars,o_)}hasRepeatedToolCallMarkup($){if($.length<=this.maxAssistantToolMarkupChars)return!1;let Z=0;for(let Q of $.matchAll(e_))if(Z+=1,Z>=a_)return!0;return!1}truncateToTotalTextBudget($){let Z=this.countMessageTextBytes($);if(Z<=this.maxTotalTextBytes)return $;let Q=$.map((J)=>{if(!Array.isArray(J.content))return{...J};return{...J,content:J.content.map((X)=>Wz(X))}}),W=this.collectTruncationCandidates(Q);for(let J of W){if(Z<=this.maxTotalTextBytes)break;let X=J.byteLength;if(X<=J.minBytes)continue;let Y=Z-this.maxTotalTextBytes,j=Math.max(J.minBytes,X-Y),V=Qz(J.get(),j,J.makeMarker);J.set(V),Z-=X-e(V)}return Q}countMessageTextBytes($){let Z=0;for(let Q of $){if(typeof Q.content==="string"){Z+=e(Q.content);continue}for(let W of Q.content)if(W.type==="text")Z+=e(W.text);else if(W.type==="thinking")Z+=e(W.thinking);else if(W.type==="file")Z+=e(W.content);else if(W.type==="tool_use")Z+=o6(W.input);else if(W.type==="tool_result"){if(typeof W.content==="string")Z+=e(W.content);else for(let J of W.content)if(J.type==="text")Z+=e(J.text);else if(J.type==="file")Z+=e(J.content);else if(d1(J))Z+=o6(J)}}return Z}collectTruncationCandidates($){let Z=[],Q=[];for(let W of $){if(W.role==="assistant"&&typeof W.content==="string"){Z.push({byteLength:e(W.content),minBytes:aY,makeMarker:tY,get:()=>W.content,set:(J)=>{W.content=J}});continue}if(!Array.isArray(W.content))continue;for(let J of W.content){if(J.type==="tool_use"){t6(J.input,Q);continue}if(W.role==="assistant"&&J.type==="text"){Z.push({byteLength:e(J.text),minBytes:aY,makeMarker:tY,get:()=>J.text,set:(X)=>{J.text=X}});continue}if(J.type!=="tool_result")continue;if(typeof J.content==="string"){Z.push({byteLength:e(J.content),minBytes:T8,makeMarker:O8,get:()=>J.content,set:(X)=>{J.content=X}});continue}for(let X of J.content)if(X.type==="text")Z.push({byteLength:e(X.text),minBytes:T8,makeMarker:O8,get:()=>X.text,set:(Y)=>{X.text=Y}});else if(X.type==="file")Z.push({byteLength:e(X.content),minBytes:T8,makeMarker:O8,get:()=>X.content,set:(Y)=>{X.content=Y}});else if(d1(X))t6(X,Z)}}return Z.sort((W,J)=>J.byteLength-W.byteLength),Q.sort((W,J)=>J.byteLength-W.byteLength),[...Z,...Q]}applyMediaBudget($){let Z=this.resolveMediaBudget();if(Z.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&Z.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&Z.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=v_(),W=!1,J=$.map((X)=>{if(!Array.isArray(X.content))return X;let Y=!1,j=X.content.map((V)=>{let H=this.applyMediaBudgetToBlock(V,Z,Q);if(H!==V)Y=!0;return H});if(!Y)return X;return W=!0,{...X,content:j}});return W?J:$}resolveMediaBudget(){return c_(this.mediaBudget)}applyMediaBudgetToBlock($,Z,Q){if(bQ($))return this.limitImageContent($,Z,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let W=!1,J=$.content.map((X)=>{let Y=this.applyMediaBudgetToToolResultEntry(X,Z,Q);if(Y!==X)W=!0;return Y});return W?{...$,content:J}:$}applyMediaBudgetToToolResultEntry($,Z,Q){if(bQ($))return this.limitImageContent($,Z,Q);if(d1($))return this.limitNestedMedia($,Z,Q);return $}limitNestedMedia($,Z,Q){if(bQ($)){let W=this.limitImageContent($,Z,Q);return W.type==="text"?W.text:W}if(Array.isArray($)){let W=!1,J=$.map((X)=>{let Y=this.limitNestedMedia(X,Z,Q);if(Y!==X)W=!0;return Y});return W?J:$}if($!==null&&typeof $==="object"){let W=!1,J={};for(let[X,Y]of Object.entries($)){let j=this.limitNestedMedia(Y,Z,Q);if(j!==Y)W=!0;J[X]=j}return W?J:$}return $}limitImageContent($,Z,Q){if(!Qj($))return{type:"text",text:iY};let W=u_($.mediaType,$.data,{maxImageEncodedBytes:Z.maxImageEncodedBytes,maxImageDecodedBytes:Z.maxImageDecodedBytes,maxTotalMediaBytes:Z.maxTotalMediaBytes},Q);if(!W.ok)return{type:"text",text:iY};return{...$,data:W.base64,mediaType:W.mediaType}}}var eY=String.raw`[\|\uFF5C]`,e_=new RegExp(String.raw`<\s*(?:${eY}\s*)?DSML\s*(?:${eY}\s*)?(?:tool_calls|invoke)\b[^>]*>|<\s*/?\s*(?:tool_calls?|tool_call|function_calls?|function_call|invoke)\b[^>]*>`,"gi");function e($){return Buffer.byteLength($,"utf8")}function $j($){if($===void 0)return;let Z=Number.parseInt($,10);return Number.isFinite(Z)&&Z>0?Z:void 0}function $z($){if($===void 0)return;let Z=$.trim().toLowerCase();if(Z==="infinity"||Z==="disable")return Number.POSITIVE_INFINITY;let Q=Number.parseInt($,10);return Number.isFinite(Q)&&Q>=0?Q:void 0}function z8($,Z){return typeof $==="number"&&Number.isFinite($)&&$>0?Math.floor($):Z}function Zz($,Z){if(typeof $!=="number"||Number.isNaN($)||$<0)return Z;return Number.isFinite($)?Math.floor($):$}function M2($,Z,Q){if($.length<=Z)return $;let W=Q($.length-Z),J=Math.max(0,Math.floor((Z-W.length)/2)),X=Math.max(0,$.length-J*2),Y=Q(X),j=Math.max(0,Math.floor((Z-Y.length)/2)),V=$.slice(0,j),H=j>0?$.slice(-j):"";return`${V}${Y}${H}`}function Qz($,Z,Q){if(e($)<=Z)return $;let W=0,J=$.length,X=M2($,0,Q);while(W<=J){let Y=W+J>>>1,j=M2($,Y,Q);if(e(j)<=Z)X=j,W=Y+1;else J=Y-1}return X}function Wz($){if($.type==="tool_use")return{...$,input:e6($.input)};if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((Z)=>d1(Z)?e6(Z):{...Z})}}function d1($){if($===null||typeof $!=="object")return!1;let Z=$.type;return Z!=="text"&&Z!=="image"&&Z!=="file"}function bQ($){return $!==null&&typeof $==="object"&&$.type==="image"}function Qj($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function hQ($){return Qj($)}function o6($){if(typeof $==="string")return e($);if(Array.isArray($)){let Z=0;for(let Q of $)Z+=o6(Q);return Z}if($!==null&&typeof $==="object"){if(hQ($))return 0;let Z=0;for(let Q of Object.values($))Z+=o6(Q);return Z}return 0}function t6($,Z){if(Array.isArray($)){$.forEach((Q,W)=>{if(typeof Q==="string")Z.push({byteLength:e(Q),minBytes:T8,makeMarker:O8,get:()=>$[W],set:(J)=>{$[W]=J}});else t6(Q,Z)});return}if($!==null&&typeof $==="object"){if(hQ($))return;let Q=$;for(let W of Object.keys(Q)){let J=Q[W];if(typeof J==="string")Z.push({byteLength:e(J),minBytes:T8,makeMarker:O8,get:()=>Q[W],set:(X)=>{Q[W]=X}});else t6(J,Z)}}}function e6($){if(Array.isArray($))return $.map(e6);if($!==null&&typeof $==="object"){let Z={};for(let[Q,W]of Object.entries($))Z[Q]=e6(W);return Z}return $}function kQ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class IQ{messages=[];conversationId=kQ();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=kQ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=kQ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function Wj($){let{agentConfig:Z}=$,Q=Jz(Z),W=Xz(Z),J=$.hooks,X=Yz(Z.maxParallelToolCalls);return{sessionId:$.sessionId??Z.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??Z.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:Q,tools:$.tools,hooks:J,prepareTurn:$.prepareTurn,consumePendingUserMessage:Z.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??Z.logger,telemetry:$.telemetry??Z.telemetry,initialMessages:$.initialMessages,completionPolicy:Z.completionPolicy,maxIterations:Z.maxIterations,toolExecution:X,toolPolicies:Z.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:Z.requestToolApproval}}function Jz($){let Z={};if($.thinking!==void 0)Z.thinking=$.thinking;if($.reasoningEffort!==void 0)Z.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)Z.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)Z.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)Z.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(Z).length>0?Z:void 0}function Xz($){let Z=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:Z}}function Yz($){if($===void 0)return;return $>=2?"parallel":"sequential"}function jz(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function Vz($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function xQ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(xQ);let Z={};for(let Q of Object.keys($).sort())Z[Q]=xQ($[Q]);return Z}function Hz($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(xQ($))}catch{return String($)}}function Bz($,Z,Q,W){if(Z===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=Z,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var Jj={softThreshold:3,hardThreshold:5};class gQ{config;state=jz();constructor($){this.config={softThreshold:$?.softThreshold??Jj.softThreshold,hardThreshold:$?.hardThreshold??Jj.hardThreshold}}inspect($){let Z=Hz($.input),Q=Bz(this.state,$.name,Z,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){Vz(this.state)}}class mQ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let Z=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&Z?Z:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let W=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(W),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:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!Z||Q<Z)return{action:"continue"};let J=await Kz({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:Z,reason:$.reason,details:$.details},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:Gz({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:Z,reason:$.reason,details:$.details,stopReason:J.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function Gz($){let Z=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)Z.push(`Error: ${Q}`);let W=$.stopReason?.trim();if(W)Z.push(`Decision: ${W}`);return Z.push("Session state was preserved. Send a new prompt to resume from the latest state."),Z.join(" ")}async function Kz($,Z){if(!Z)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await Z($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function Fz($){let Z=$.content.filter((Q)=>Q.type==="text");if(Z.length===0)return;return Z.map((Q)=>Q.text).join("")}function Az($){let Z=$.content.filter((Q)=>Q.type==="reasoning");if(Z.length===0)return;return{reasoning:Z.map((Q)=>Q.text).join(""),redacted:Z.some((Q)=>Q.redacted===!0)}}function fz($){return $.content.find((Z)=>Z.type==="tool-result")}function Uz($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function Dz($){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 vQ{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:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,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 Z=[],Q=Fz($);if(Q!==void 0)Z.push({type:"content_end",contentType:"text",text:Q});let W=Az($);if(W!==void 0)Z.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return Z}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 Z=this.toolStartedAt.get($.toolCall.toolCallId),Q=Z===void 0?void 0:Date.now()-Z;this.toolStartedAt.delete($.toolCall.toolCallId);let W=fz($.message),J=W?.output,X=Dz(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:J,error:X,durationMs:Q}]}translateUsage($){let Z=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,J=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,X=this.lastUsage.totalCost??0,j=($.totalCost??0)-X;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,Z),outputTokens:Math.max(0,Q),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:J===0?void 0:Math.max(0,J),cost:j===0?void 0:j,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let Z={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:Uz($.status),text:$.outputText,iterations:$.iterations,usage:Z}]}}function Rz($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function Ez($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function Nz($,Z){let Q=$.trim(),W=Z.map((J)=>J.trim()).filter(Boolean).join(`
162
162
 
163
163
  `);if(Q&&W)return`${Q}
164
164
 
165
- ${W}`;return Q||W}function Mz($,Z){let Q=Z?.["*"]??{},W=Z?.[$]??{};return{...Q,...W}.enabled!==!1}function Rz($,Z){return $.filter((Q)=>Mz(Q.name,Z))}function Ez($,Z){return k1(Rz($,Z))}function Nz($){let Z=$.filter((Q)=>Q!==void 0);if(Z.length===0)return{};return{beforeRun:async(Q)=>{for(let W of Z){let J=await W.beforeRun?.(Q);if(J?.stop)return J}return},afterRun:async(Q)=>{for(let W of Z)await W.afterRun?.(Q)},beforeModel:async(Q)=>{let W=Q.request,J;for(let X of Z){let Y=await X.beforeModel?.({...Q,request:W});if(!Y)continue;if(Y.stop)return Y;J={...J,...Y,options:Yj(J?.options,Y.options)},W={...W,...Y.messages?{messages:Y.messages}:{},...Y.tools?{tools:Y.tools}:{},...Y.options?{options:Yj(W.options,Y.options)}:{}}}return J},afterModel:async(Q)=>{for(let W of Z){let J=await W.afterModel?.(Q);if(J?.stop)return J}return},beforeTool:async(Q)=>{let W=Q.input,J;for(let X of Z){let Y=await X.beforeTool?.({...Q,input:W});if(!Y)continue;if(Y.stop||Y.skip)return Y;if(J={...J,...Y},Object.hasOwn(Y,"input"))W=Y.input}return J},afterTool:async(Q)=>{let W=Q.result,J;for(let X of Z){let Y=await X.afterTool?.({...Q,result:W});if(!Y)continue;if(Y.stop)return Y;if(J={...J,...Y},Y.result)W=Y.result}return J},onEvent:async(Q)=>{for(let W of Z)await W.onEvent?.(Q)}}}class l1{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 vQ;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($,Z={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=Z.logger??$.logger,this.telemetry=Z.telemetry??$.telemetry,this.createAgentRuntimeImpl=Z.createAgentRuntimeImpl??_z,this.conversation=new IQ($.initialMessages),this.messageBuilder=new yQ(Zj()),this.contributionRegistry=zz({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 Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new mQ({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(X)=>this.emitLegacyEvent(X),log:(X,Y,j)=>wz(this.logger,X,Y,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(X,Y)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:X}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let J=W===!1||W===void 0?void 0:W;this.loopTracker=new gQ(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 Z=new Set(this.config.tools.map((W)=>W.name)),Q=[...this.config.tools];for(let W of $)if(!Z.has(W.name))Q.push(W),Z.add(W.name);this.config={...this.config,tools:Q}}updateConnection($){let Z={...this.config};if($.providerId!==void 0)Z.providerId=$.providerId;if($.modelId!==void 0)Z.modelId=$.modelId;if($.apiKey!==void 0)Z.apiKey=$.apiKey;if($.baseUrl!==void 0)Z.baseUrl=$.baseUrl;if($.headers!==void 0)Z.headers=$.headers;if($.providerConfig!==void 0)Z.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)Z.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)Z.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)Z.thinkingBudgetTokens=$.thinkingBudgetTokens;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 Z=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=Z,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(Z)}async shutdown($,Z){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($,Z,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:Z,userFiles:Q,isContinue:!1})}continue($,Z,Q){return this.executeRun({userMessage:$,userImages:Z,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let Z of this.contributionRegistry.getRegisteredRules()){let Q=await Oz(Z);if(Q)$.push(Q)}return qz(this.config.systemPrompt,$)}executeRun($){let Z;return Z=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===Z)this.activeRunPromise=null}),this.activeRunPromise=Z,Z}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 Z=new Date,Q=$.userMessage;if(Q!==void 0){let U=await Pz(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),J=rY(this.config,this.logger,this.telemetry),X=new Map;for(let U of this.contributionRegistry.getRegisteredTools())X.set(U.name,U);let Y=Ez([...X.values()],this.config.toolPolicies),j=new Map;for(let U of Y)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let V=this.conversation.getConversationId(),H=jj(this.config),B=Array.from(j.values()),G=n6(this.conversation.getMessages()),K=Wj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:B,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[$Y]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,B),initialMessages:G,systemPrompt:W}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((U)=>{this.handleRuntimeEvent(U)}),L,f;try{if($.isContinue)L=await F.continue(void 0);else L=await F.run("")}catch(U){f=U instanceof Error?U:Error(String(U))}finally{A();try{await this.activeTrackerWork}catch(U){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:U})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(L&&L.messages.length>0){let U=q2(L.messages);this.conversation.replaceMessages(U)}let D=new Date;try{return this.buildLegacyResult({runResult:L,thrownError:f,startedAt:Z,endedAt:D})}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 $=Nz([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((Z)=>Z.hooks)]);return{...$,beforeModel:async(Z)=>{let Q=await $.beforeModel?.(Z);if(Q?.stop)return Q;let W=Q?.messages??Z.request.messages,J=await this.prepareMessagesForModelRequest(W);return{...Q,messages:J}}}}createRuntimePrepareTurn($,Z){let Q=this.config.prepareTurn;if(!Q)return;return async(W)=>{let J=q2(W.messages),X=await this.prepareProviderMessagesForApi(J),Y=await Q({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:J,apiMessages:X,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!Y)return;return{...Y.messages?{messages:n6(Y.messages)}:{},...Y.systemPrompt!==void 0?{systemPrompt:Y.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let Z=await this.prepareProviderMessagesForApi(a6($));return n6(Z)}async prepareProviderMessagesForApi($){let Z=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of Q)Z=await W.build(Z);return this.messageBuilder.buildForApi(Z)}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 Z=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,W=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"),X=J?.type==="tool-result"&&J.isError===!0,Y=X?Tz(J?.type==="tool-result"?J.output:void 0):void 0,j={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:J?.type==="tool-result"?J.output:void 0,error:Y,durationMs:Z===void 0?0:Q.getTime()-Z.getTime(),startedAt:Z??Q,endedAt:Q};if(this.currentRunToolCalls.push(j),X){if(this.currentTurnFailedTools+=1,Y)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${Y}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let Z=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(Z>0&&Q===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${Z} tool call(s) failed${W?`: ${W}`:""}`})}else if(Q>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 Z of this.eventAdapter.translate($))this.emitLegacyEvent(Z)}syncConversationFromRuntimeMessage($,Z){if($.length>0){this.conversation.replaceMessages(q2($));return}if(Z.length===0)return;let Q=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),W=q2(Z).filter((J)=>!J.id||!Q.has(J.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let Z of this.listeners)try{Z($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,Z,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:Z});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:W.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 Z=await this.mistakeTracker.record($);if(Z.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]}),this.activeRuntime?.abort(Z.reason??Z.message)})}buildLegacyResult($){let{runResult:Z,thrownError:Q,startedAt:W,endedAt:J}=$,X=J.getTime()-W.getTime(),Y=Q?"error":Cz(Z),j=(Z?.status==="failed"?Z.error?.message:void 0)||Z?.outputText||"",V=Z?{inputTokens:Z.usage.inputTokens,outputTokens:Z.usage.outputTokens,cacheReadTokens:Z.usage.cacheReadTokens>0?Z.usage.cacheReadTokens:void 0,cacheWriteTokens:Z.usage.cacheWriteTokens>0?Z.usage.cacheWriteTokens:void 0,totalCost:Z.usage.totalCost}:this.currentRunUsage,H=Z?q2(Z.messages):this.conversation.getMessages(),B=jj(this.config);if(Q)throw Q;return{text:j,usage:V,messages:H,toolCalls:this.currentRunToolCalls,iterations:Z?.iterations??0,finishReason:Y,model:{id:this.config.modelId,provider:this.config.providerId,info:B},startedAt:W,endedAt:J,durationMs:X}}}function wz($,Z,Q,W){if(!$)return;if(Z==="debug"){$.debug(Q,W);return}if(Z==="error"&&$.error){$.error(Q,W);return}let J=Z==="warn"?"warn":Z==="error"?"error":"info";$.log(Q,{...W,severity:J})}function Cz($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function Pz($,Z,Q,W){let{buildInitialUserContent:J}=await Promise.resolve().then(() => Xj);return J($,Z,Q,W)}function jj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let Z=PQ($);if(Z?.[$.modelId])return Z[$.modelId];return}import{buildClineSystemPrompt as Vj}from"@cline/shared";function Hj($,Z){let Q=$.trim();if(Z.providerId.toLowerCase()!=="cline")return Q;return Vj({ide:Z.clineIdeName?.trim()||"Terminal",workspaceRoot:Z.cwd?.trim()||"/",providerId:Z.providerId,rules:`# Team Teammate Role
166
- ${Q}`,platform:Z.clinePlatform,metadata:Z.workspaceMetadata})}function Bj($,Z){let Q=$.trim();if(Z.providerId.toLowerCase()!=="cline")return Q;return Vj({ide:Z.clineIdeName||"Terminal",workspaceRoot:Z.cwd?.trim()||"/",providerId:Z.providerId,overridePrompt:Q,metadata:Z.workspaceMetadata,platform:Z.clinePlatform})}function R2($){let Z={...$};return{getRuntimeConfig:()=>Z,getConnectionConfig:()=>({providerId:Z.providerId,modelId:Z.modelId,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxTokensPerTurn:Z.maxTokensPerTurn}),updateConnectionDefaults:(Q)=>{Z={...Z,...Q}}}}function M8($){let Z=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?Hj($.prompt,Z):Bj($.prompt,Z);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??Z.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:Z.hooks,extensions:Z.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:Z.logger,role:$.role}}function E2($){let Z=M8($),Q=new l1(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);return Q}var yz=cQ.object({systemPrompt:cQ.string().describe("System prompt defining the sub-agent's behavior"),task:cQ.string().describe("Task for the sub-agent to complete")});function N2($){return Sz({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:bz(yz),execute:async(Z,Q)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(Z,Q):$.subAgentTools??[],J=E2({kind:"subagent",prompt:Z.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),X=J.getAgentId(),Y=J.getConversationId(),j=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z})}catch{}try{let V=await J.run(Z.task),H={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z,result:H,agentResult:V})}catch{}return H}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as V0,TEAM_AWAIT_TIMEOUT_MS as hz,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as kz,TEAM_RUN_TEXT_PREVIEW_LIMIT as Iz,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as xz,TeamAttachOutcomeFragmentInputSchema as Gj,TeamAwaitRunsInputSchema as Kj,TeamBroadcastInputSchema as Fj,TeamBroadcastToolResultSchema as gz,TeamCancelRunInputSchema as Aj,TeamCancelRunToolResultSchema as mz,TeamCleanupInputSchema as fj,TeamCleanupToolResultSchema as vz,TeamCreateOutcomeInputSchema as Uj,TeamCreateOutcomeToolResultSchema as cz,TeamFinalizeOutcomeInputSchema as Dj,TeamFinalizeOutcomeToolResultSchema as uz,TeamListOutcomesInputSchema as Lj,TeamListRunsInputSchema as _j,TeamMailboxMessageToolResultSchema as dz,TeamMissionLogInputSchema as zj,TeamMissionLogToolResultSchema as lz,TeamOutcomeFragmentToolResultSchema as Tj,TeamOutcomeToolResultSchema as pz,TeamReadMailboxInputSchema as Oj,TeamReviewOutcomeFragmentInputSchema as qj,TeamRunTaskInputSchema as Mj,TeamRunTaskToolResultSchema as uQ,TeamRunToolSummarySchema as dQ,TeamSendMessageInputSchema as Rj,TeamSendMessageToolResultSchema as rz,TeamShutdownTeammateInputSchema as Ej,TeamSimpleAgentStatusToolResultSchema as Nj,TeamSpawnTeammateInputSchema as wj,TeamStatusInputSchema as Cj,TeamStatusToolResultSchema as iz,TeamTaskInputSchema as Pj,TeamTaskToolResultSchema as R8,validateWithZod as b,zodToJsonSchema as H0}from"@cline/shared";function Sj($,Z){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=Z)return Q;return`${Q.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function N$($,Z){if($===void 0)throw Error(`Missing required field: ${Z}`);return $}function nz($){let Z=$.result;if(!Z)return;return{textPreview:Sj(Z.text,Iz),iterations:Z.iterations,finishReason:Z.finishReason,durationMs:Z.durationMs,usage:{inputTokens:Z.usage.inputTokens,outputTokens:Z.usage.outputTokens,cacheReadTokens:Z.usage.cacheReadTokens,cacheWriteTokens:Z.usage.cacheWriteTokens,totalCost:Z.usage.totalCost}}}function e6($){return $?.toISOString()}function lQ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:Sj($.message,kz),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:e6($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:e6($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:e6($.heartbeatAt),lastProgressAt:e6($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:nz($)}}function az($){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 $5=["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 bj($){let Z=[];if($.createBaseTools)Z.push(...$.createBaseTools());Z.push(...E8({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:M8({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:Z,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function Z5($){let Z=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,W=E8({runtime:$.runtime,requesterId:Z,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let X of $.restoredTeammates??[]){if($.runtime.isTeammateActive(X.agentId))continue;bj({runtime:$.runtime,requesterId:Z,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:X}),J.push(X.agentId)}return{tools:W,restoredFromPersistence:Q,restoredTeammates:J}}function E8($){let Z=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,J=[];if(Q)J.push(V0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:H0(wj),execute:async(Y)=>{let j=b(wj,Y);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!Z)throw Error("Spawning teammates is disabled in this context.");let V={agentId:j.agentId,rolePrompt:j.rolePrompt};if(bj({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!W)$.onLeadToolsUnlocked?.(E8({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(Nj,{agentId:j.agentId,status:"spawned"})}}));if(!W)return J;J.push(V0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:H0(Ej),execute:async(Y)=>{let j=b(Ej,Y);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(j.agentId,j.reason),b(Nj,{agentId:j.agentId,status:"stopped"})}})),J.push(V0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:H0(Cj),execute:async(Y)=>{return b(Cj,Y),b(iz,$.runtime.getSnapshot())}})),J.push(V0({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:H0(Pj),execute:async(Y)=>{let j=b(Pj,Y);switch(j.action){case"create":{let V=new Set(xz.create??[]),H=Object.entries(Y).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),B=$.runtime.createTask({title:N$(j.title,"title"),description:N$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:$.requesterId});return b(R8,{action:"create",taskId:B.id,status:B.status,...H.length>0?{ignoredFields:H,note:`Ignored fields for action=create: ${H.join(", ")}`}:{}})}case"list":return b(R8,{action:"list",tasks:$.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let V=$.runtime.claimTask(N$(j.taskId,"taskId"),$.requesterId);return b(R8,{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(N$(j.taskId,"taskId"),$.requesterId,N$(j.summary,"summary"));return b(R8,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(N$(j.taskId,"taskId"),$.requesterId,N$(j.reason,"reason"));return b(R8,{action:"block",taskId:V.id,status:V.status})}}}}));let X=new Map;return J.push(V0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:H0(Mj),execute:async(Y)=>{let j=b(Mj,Y);if(j.runMode==="async"){let B=$.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:$.requesterId,continueConversation:j.continueConversation||void 0});return b(uQ,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${B.id}.`,runId:B.id})}let V=X.get(j.agentId);if(V){let B=await V;return b(uQ,{...B,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let H=$.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:$.requesterId,continueConversation:j.continueConversation||void 0}).then((B)=>b(uQ,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:B.text,iterations:B.iterations})).finally(()=>{X.delete(j.agentId)});return X.set(j.agentId,H),await H}})),J.push(V0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:H0(Aj),execute:async(Y)=>{let j=b(Aj,Y),V=$.runtime.cancelRun(j.runId,j.reason);return b(mz,{runId:V.id,status:V.status})}})),J.push(V0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:H0(_j),execute:async(Y)=>b(dQ.array(),$.runtime.listRuns(b(_j,Y)).map(lQ))})),J.push(V0({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:H0(Kj),timeoutMs:hz,execute:async(Y)=>{let j=b(Kj,Y);if(j.runId){let B=await $.runtime.awaitRun(j.runId);return az(B),b(dQ,lQ(B))}let V=await $.runtime.awaitAllRuns(),H=V.filter((B)=>["failed","cancelled","interrupted"].includes(B.status));if(H.length>0){let B=H.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${B}`)}return b(dQ.array(),V.map(lQ))}})),J.push(V0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:H0(Rj),execute:async(Y)=>{let j=b(Rj,Y),V=$.runtime.sendMessage($.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(rz,{id:V.id,toAgentId:V.toAgentId})}})),J.push(V0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:H0(Fj),execute:async(Y)=>{let j=b(Fj,Y),V=$.runtime.broadcast($.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(gz,{delivered:V.length})}})),J.push(V0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:H0(Oj),execute:async(Y)=>{let j=b(Oj,Y);return b(dz.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),J.push(V0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:H0(zj),execute:async(Y)=>{let j=b(zj,Y),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return b(lz,{id:V.id})}})),J.push(V0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:H0(fj),execute:async(Y)=>{if(b(fj,Y),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),b(vz,{status:"cleaned"})}})),J.push(V0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:H0(Uj),execute:async(Y)=>{let j=b(Uj,Y),V=$.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:$.requesterId});return b(cz,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(V0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:H0(Gj),execute:async(Y)=>{let j=b(Gj,Y),V=$.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:$.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(Tj,{fragmentId:V.id,status:V.status})}})),J.push(V0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:H0(qj),execute:async(Y)=>{let j=b(qj,Y),V=$.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:$.requesterId,approved:j.approved});return b(Tj,{fragmentId:V.id,status:V.status})}})),J.push(V0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:H0(Dj),execute:async(Y)=>{let j=b(Dj,Y),V=$.runtime.finalizeOutcome(j.outcomeId);return b(uz,{outcomeId:V.id,status:V.status})}})),J.push(V0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:H0(Lj),execute:async(Y)=>{return b(Lj,Y),b(pz.array(),$.runtime.listOutcomes())}})),J}function yj($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}var sz=[{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:N2({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...$5]}],oz={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function tz($){return $==="plan"||$==="yolo"?$:"act"}function kj($){let Z=tz($.mode),Q=e0[u1({mode:Z})],W=_8($.providerId??"",$.modelId??"",Z,L8);return{mode:Z,flags:{...Q,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function hj($,Z){if(Z.disabledToolIds?.has($))return!1;let{flags:Q}=kj(Z);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let W=oz[$];return W?Q[W]===!0:!1}function ez($,Z){if($.id==="editor"){let{flags:Q}=kj(Z),W=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:hj($.id,Z),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:hj($.id,Z)}}function N8($={}){return sz.map((Z)=>ez(Z,$))}function Ij($={}){return N8($).filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id)}function xj($){if(!$.enabled)return new Set;let Z=N8($.availabilityContext),Q=new Set(Z.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(Z.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!Q.has(W))throw Error(`Unknown tool "${W}". Available tools: ${Z.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function pQ($,Z={}){return N8(Z).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function gj($,Z={}){return pQ($,Z)}function w8($={}){let{executorOptions:Z={},executors:Q,...W}=$,J={...i6(Z),...Q??{}};return T2({...W,executors:J})}function Q5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function $T($){if(!$||$.length===0)return;let Z=$.map(Q5).filter((Q)=>Q.length>0);return Z.length>0?new Set(Z):void 0}function ZT($,Z,Q){if(!Q)return!0;let W=Q5($),J=Q5(Z),X=W.includes(":")?W.split(":").at(-1)??W:W,Y=J.includes(":")?J.split(":").at(-1)??J:J;return Q.has(W)||Q.has(J)||Q.has(X)||Q.has(Y)}function C8($,Z){let Q=$T(Z);return[...$.getSnapshot("skill").entries()].map(([J,X])=>{let Y=X.item;return{id:J,name:Y.name.trim(),description:Y.description?.trim(),disabled:Y.disabled===!0,skill:Y}}).filter((J)=>ZT(J.id,J.name,Q))}function QT($,Z){return C8($,Z).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,W)=>Q.localeCompare(W))}function WT($,Z,Q){let W=Q5(Z);if(!W)return{error:"Missing skill name."};let J=C8($,Q),X=J.find((B)=>B.id===W);if(X){let{skill:B}=X;if(B.disabled===!0)return{error:`Skill "${B.name}" is configured but disabled.`};return{id:X.id,skill:B}}let Y=W.includes(":")?W.split(":").at(-1)??W:W,j=J.filter(({id:B})=>{if(B===Y)return!0;return B.endsWith(`:${Y}`)}),V=j.filter(({skill:B})=>B.disabled!==!0);if(V.length===1){let{id:B,skill:G}=V[0];return{id:B,skill:G}}if(V.length>1)return{error:`Skill "${Z}" is ambiguous. Use one of: ${V.map(({id:B})=>B).join(", ")}`};if(j.length===1){let{skill:B}=j[0];return{error:`Skill "${B.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${Z}" is ambiguous, and all matches are disabled: ${j.map(({id:B})=>B).join(", ")}`};let H=QT($,Q);return{error:H.length>0?`Skill "${Z}" not found. Available skills: ${H.join(", ")}`:"No skills are currently available."}}function rQ($,Z=Promise.resolve(),Q){let W=new Set,J=async(X,Y)=>{await Z;let j=WT($,X,Q);if("error"in j)return j.error;let{id:V,skill:H}=j;if(W.has(V))return`Skill "${H.name}" is already running.`;W.add(V);try{let B=Y?.trim(),G=B?`
165
+ ${W}`;return Q||W}function wz($,Z){let Q=Z?.["*"]??{},W=Z?.[$]??{};return{...Q,...W}.enabled!==!1}function Cz($,Z){return $.filter((Q)=>wz(Q.name,Z))}function Pz($,Z){return k1(Cz($,Z))}function Sz($){let Z=$.filter((Q)=>Q!==void 0);if(Z.length===0)return{};return{beforeRun:async(Q)=>{for(let W of Z){let J=await W.beforeRun?.(Q);if(J?.stop)return J}return},afterRun:async(Q)=>{for(let W of Z)await W.afterRun?.(Q)},beforeModel:async(Q)=>{let W=Q.request,J;for(let X of Z){let Y=await X.beforeModel?.({...Q,request:W});if(!Y)continue;if(Y.stop)return Y;J={...J,...Y,options:Yj(J?.options,Y.options)},W={...W,...Y.messages?{messages:Y.messages}:{},...Y.tools?{tools:Y.tools}:{},...Y.options?{options:Yj(W.options,Y.options)}:{}}}return J},afterModel:async(Q)=>{for(let W of Z){let J=await W.afterModel?.(Q);if(J?.stop)return J}return},beforeTool:async(Q)=>{let W=Q.input,J;for(let X of Z){let Y=await X.beforeTool?.({...Q,input:W});if(!Y)continue;if(Y.stop||Y.skip)return Y;if(J={...J,...Y},Object.hasOwn(Y,"input"))W=Y.input}return J},afterTool:async(Q)=>{let W=Q.result,J;for(let X of Z){let Y=await X.afterTool?.({...Q,result:W});if(!Y)continue;if(Y.stop)return Y;if(J={...J,...Y},Y.result)W=Y.result}return J},onEvent:async(Q)=>{for(let W of Z)await W.onEvent?.(Q)}}}class l1{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 vQ;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($,Z={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=Z.logger??$.logger,this.telemetry=Z.telemetry??$.telemetry,this.createAgentRuntimeImpl=Z.createAgentRuntimeImpl??qz,this.conversation=new IQ($.initialMessages),this.messageBuilder=new yQ(Zj()),this.contributionRegistry=Mz({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 Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new mQ({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(X)=>this.emitLegacyEvent(X),log:(X,Y,j)=>bz(this.logger,X,Y,j),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(X,Y)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:X}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let J=W===!1||W===void 0?void 0:W;this.loopTracker=new gQ(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 Z=new Set(this.config.tools.map((W)=>W.name)),Q=[...this.config.tools];for(let W of $)if(!Z.has(W.name))Q.push(W),Z.add(W.name);this.config={...this.config,tools:Q}}updateConnection($){let Z={...this.config};if($.providerId!==void 0)Z.providerId=$.providerId;if($.modelId!==void 0)Z.modelId=$.modelId;if($.apiKey!==void 0)Z.apiKey=$.apiKey;if($.baseUrl!==void 0)Z.baseUrl=$.baseUrl;if($.headers!==void 0)Z.headers=$.headers;if($.providerConfig!==void 0)Z.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)Z.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)Z.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)Z.thinkingBudgetTokens=$.thinkingBudgetTokens;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 Z=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=Z,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(Z)}async shutdown($,Z){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($,Z,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:Z,userFiles:Q,isContinue:!1})}continue($,Z,Q){return this.executeRun({userMessage:$,userImages:Z,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let Z of this.contributionRegistry.getRegisteredRules()){let Q=await Ez(Z);if(Q)$.push(Q)}return Nz(this.config.systemPrompt,$)}executeRun($){let Z;return Z=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===Z)this.activeRunPromise=null}),this.activeRunPromise=Z,Z}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 Z=new Date,Q=$.userMessage;if(Q!==void 0){let U=await hz(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),J=rY(this.config,this.logger,this.telemetry),X=new Map;for(let U of this.contributionRegistry.getRegisteredTools())X.set(U.name,U);let Y=Pz([...X.values()],this.config.toolPolicies),j=new Map;for(let U of Y)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let V=this.conversation.getConversationId(),H=jj(this.config),B=Array.from(j.values()),G=a6(this.conversation.getMessages()),K=Wj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:V,parentAgentId:this.parentAgentId,model:J,logger:this.logger,telemetry:this.telemetry,tools:B,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[$Y]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,B),initialMessages:G,systemPrompt:W}),F=this.createAgentRuntimeImpl(K);if(this.activeRuntime=F,this.abortRequested)F.abort(this.abortReason);let A=F.subscribe((U)=>{this.handleRuntimeEvent(U)}),L,f;try{if($.isContinue)L=await F.continue(void 0);else L=await F.run("")}catch(U){f=U instanceof Error?U:Error(String(U))}finally{A();try{await this.activeTrackerWork}catch(U){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:U})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(L&&L.messages.length>0){let U=q2(L.messages);this.conversation.replaceMessages(U)}let D=new Date;try{return this.buildLegacyResult({runResult:L,thrownError:f,startedAt:Z,endedAt:D})}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 $=Sz([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((Z)=>Z.hooks)]);return{...$,beforeModel:async(Z)=>{let Q=await $.beforeModel?.(Z);if(Q?.stop)return Q;let W=Q?.messages??Z.request.messages,J=await this.prepareMessagesForModelRequest(W);return{...Q,messages:J}}}}createRuntimePrepareTurn($,Z){let Q=this.config.prepareTurn;if(!Q)return;return async(W)=>{let J=q2(W.messages),X=await this.prepareProviderMessagesForApi(J),Y=await Q({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:J,apiMessages:X,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:Z,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!Y)return;return{...Y.messages?{messages:a6(Y.messages)}:{},...Y.systemPrompt!==void 0?{systemPrompt:Y.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let Z=await this.prepareProviderMessagesForApi(s6($));return a6(Z)}async prepareProviderMessagesForApi($){let Z=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of Q)Z=await W.build(Z);return this.messageBuilder.buildForApi(Z)}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 Z=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,W=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"),X=J?.type==="tool-result"&&J.isError===!0,Y=X?Rz(J?.type==="tool-result"?J.output:void 0):void 0,j={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:J?.type==="tool-result"?J.output:void 0,error:Y,durationMs:Z===void 0?0:Q.getTime()-Z.getTime(),startedAt:Z??Q,endedAt:Q};if(this.currentRunToolCalls.push(j),X){if(this.currentTurnFailedTools+=1,Y)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${Y}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let Z=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(Z>0&&Q===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${Z} tool call(s) failed${W?`: ${W}`:""}`})}else if(Q>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 Z of this.eventAdapter.translate($))this.emitLegacyEvent(Z)}syncConversationFromRuntimeMessage($,Z){if($.length>0){this.conversation.replaceMessages(q2($));return}if(Z.length===0)return;let Q=new Set(this.conversation.getMessages().map((J)=>J.id).filter((J)=>typeof J==="string")),W=q2(Z).filter((J)=>!J.id||!Q.has(J.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let Z of this.listeners)try{Z($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,Z,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:Z});if(W.kind==="ok")return;if(W.kind==="soft"){if(W.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:W.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:W.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 Z=await this.mistakeTracker.record($);if(Z.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]}),this.activeRuntime?.abort(Z.reason??Z.message)})}buildLegacyResult($){let{runResult:Z,thrownError:Q,startedAt:W,endedAt:J}=$,X=J.getTime()-W.getTime(),Y=Q?"error":yz(Z),j=(Z?.status==="failed"?Z.error?.message:void 0)||Z?.outputText||"",V=Z?{inputTokens:Z.usage.inputTokens,outputTokens:Z.usage.outputTokens,cacheReadTokens:Z.usage.cacheReadTokens>0?Z.usage.cacheReadTokens:void 0,cacheWriteTokens:Z.usage.cacheWriteTokens>0?Z.usage.cacheWriteTokens:void 0,totalCost:Z.usage.totalCost}:this.currentRunUsage,H=Z?q2(Z.messages):this.conversation.getMessages(),B=jj(this.config);if(Q)throw Q;return{text:j,usage:V,messages:H,toolCalls:this.currentRunToolCalls,iterations:Z?.iterations??0,finishReason:Y,model:{id:this.config.modelId,provider:this.config.providerId,info:B},startedAt:W,endedAt:J,durationMs:X}}}function bz($,Z,Q,W){if(!$)return;if(Z==="debug"){$.debug(Q,W);return}if(Z==="error"&&$.error){$.error(Q,W);return}let J=Z==="warn"?"warn":Z==="error"?"error":"info";$.log(Q,{...W,severity:J})}function yz($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function hz($,Z,Q,W){let{buildInitialUserContent:J}=await Promise.resolve().then(() => Xj);return J($,Z,Q,W)}function jj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let Z=PQ($);if(Z?.[$.modelId])return Z[$.modelId];return}import{buildClineSystemPrompt as Vj}from"@cline/shared";function Hj($,Z){let Q=$.trim();if(Z.providerId.toLowerCase()!=="cline")return Q;return Vj({ide:Z.clineIdeName?.trim()||"Terminal",workspaceRoot:Z.cwd?.trim()||"/",providerId:Z.providerId,rules:`# Team Teammate Role
166
+ ${Q}`,platform:Z.clinePlatform,metadata:Z.workspaceMetadata})}function Bj($,Z){let Q=$.trim();if(Z.providerId.toLowerCase()!=="cline")return Q;return Vj({ide:Z.clineIdeName||"Terminal",workspaceRoot:Z.cwd?.trim()||"/",providerId:Z.providerId,overridePrompt:Q,metadata:Z.workspaceMetadata,platform:Z.clinePlatform})}function R2($){let Z={...$};return{getRuntimeConfig:()=>Z,getConnectionConfig:()=>({providerId:Z.providerId,modelId:Z.modelId,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxTokensPerTurn:Z.maxTokensPerTurn}),updateConnectionDefaults:(Q)=>{Z={...Z,...Q}}}}function M8($){let Z=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?Hj($.prompt,Z):Bj($.prompt,Z);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??Z.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:Z.hooks,extensions:Z.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:Z.logger,role:$.role}}function E2($){let Z=M8($),Q=new l1(Z);if(Z.onEvent)Q.subscribeEvents(Z.onEvent);return Q}var xz=cQ.object({systemPrompt:cQ.string().describe("System prompt defining the sub-agent's behavior"),task:cQ.string().describe("Task for the sub-agent to complete")});function N2($){return kz({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:Iz(xz),execute:async(Z,Q)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(Z,Q):$.subAgentTools??[],J=E2({kind:"subagent",prompt:Z.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),X=J.getAgentId(),Y=J.getConversationId(),j=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z})}catch{}try{let V=await J.run(Z.task),H={text:V.text,iterations:V.iterations,finishReason:V.finishReason,usage:{inputTokens:V.usage.inputTokens,outputTokens:V.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z,result:H,agentResult:V})}catch{}return H}catch(V){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:X,conversationId:Y,parentAgentId:j,input:Z,error:V instanceof Error?V:Error(String(V))})}catch{}throw V}},timeoutMs:300000,retryable:!1})}import{createTool as V0,TEAM_AWAIT_TIMEOUT_MS as gz,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as mz,TEAM_RUN_TEXT_PREVIEW_LIMIT as vz,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as cz,TeamAttachOutcomeFragmentInputSchema as Gj,TeamAwaitRunsInputSchema as Kj,TeamBroadcastInputSchema as Fj,TeamBroadcastToolResultSchema as uz,TeamCancelRunInputSchema as Aj,TeamCancelRunToolResultSchema as dz,TeamCleanupInputSchema as fj,TeamCleanupToolResultSchema as lz,TeamCreateOutcomeInputSchema as Uj,TeamCreateOutcomeToolResultSchema as pz,TeamFinalizeOutcomeInputSchema as Dj,TeamFinalizeOutcomeToolResultSchema as rz,TeamListOutcomesInputSchema as Lj,TeamListRunsInputSchema as _j,TeamMailboxMessageToolResultSchema as iz,TeamMissionLogInputSchema as zj,TeamMissionLogToolResultSchema as nz,TeamOutcomeFragmentToolResultSchema as Tj,TeamOutcomeToolResultSchema as az,TeamReadMailboxInputSchema as Oj,TeamReviewOutcomeFragmentInputSchema as qj,TeamRunTaskInputSchema as Mj,TeamRunTaskToolResultSchema as uQ,TeamRunToolSummarySchema as dQ,TeamSendMessageInputSchema as Rj,TeamSendMessageToolResultSchema as sz,TeamShutdownTeammateInputSchema as Ej,TeamSimpleAgentStatusToolResultSchema as Nj,TeamSpawnTeammateInputSchema as wj,TeamStatusInputSchema as Cj,TeamStatusToolResultSchema as oz,TeamTaskInputSchema as Pj,TeamTaskToolResultSchema as R8,validateWithZod as b,zodToJsonSchema as H0}from"@cline/shared";function Sj($,Z){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=Z)return Q;return`${Q.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function w$($,Z){if($===void 0)throw Error(`Missing required field: ${Z}`);return $}function tz($){let Z=$.result;if(!Z)return;return{textPreview:Sj(Z.text,vz),iterations:Z.iterations,finishReason:Z.finishReason,durationMs:Z.durationMs,usage:{inputTokens:Z.usage.inputTokens,outputTokens:Z.usage.outputTokens,cacheReadTokens:Z.usage.cacheReadTokens,cacheWriteTokens:Z.usage.cacheWriteTokens,totalCost:Z.usage.totalCost}}}function $5($){return $?.toISOString()}function lQ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:Sj($.message,mz),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:$5($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:$5($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:$5($.heartbeatAt),lastProgressAt:$5($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:tz($)}}function ez($){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 Z5=["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 bj($){let Z=[];if($.createBaseTools)Z.push(...$.createBaseTools());Z.push(...E8({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:M8({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:Z,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function Q5($){let Z=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,W=E8({runtime:$.runtime,requesterId:Z,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),J=[];for(let X of $.restoredTeammates??[]){if($.runtime.isTeammateActive(X.agentId))continue;bj({runtime:$.runtime,requesterId:Z,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:X}),J.push(X.agentId)}return{tools:W,restoredFromPersistence:Q,restoredTeammates:J}}function E8($){let Z=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,J=[];if(Q)J.push(V0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:H0(wj),execute:async(Y)=>{let j=b(wj,Y);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!Z)throw Error("Spawning teammates is disabled in this context.");let V={agentId:j.agentId,rolePrompt:j.rolePrompt};if(bj({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:V}),!W)$.onLeadToolsUnlocked?.(E8({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return b(Nj,{agentId:j.agentId,status:"spawned"})}}));if(!W)return J;J.push(V0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:H0(Ej),execute:async(Y)=>{let j=b(Ej,Y);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(j.agentId,j.reason),b(Nj,{agentId:j.agentId,status:"stopped"})}})),J.push(V0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:H0(Cj),execute:async(Y)=>{return b(Cj,Y),b(oz,$.runtime.getSnapshot())}})),J.push(V0({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:H0(Pj),execute:async(Y)=>{let j=b(Pj,Y);switch(j.action){case"create":{let V=new Set(cz.create??[]),H=Object.entries(Y).filter(([G,K])=>V.has(G)&&K!=null).map(([G])=>G),B=$.runtime.createTask({title:w$(j.title,"title"),description:w$(j.description,"description"),dependsOn:j.dependsOn,assignee:j.assignee,createdBy:$.requesterId});return b(R8,{action:"create",taskId:B.id,status:B.status,...H.length>0?{ignoredFields:H,note:`Ignored fields for action=create: ${H.join(", ")}`}:{}})}case"list":return b(R8,{action:"list",tasks:$.runtime.listTaskItems({status:j.status,assignee:j.assignee})});case"claim":{let V=$.runtime.claimTask(w$(j.taskId,"taskId"),$.requesterId);return b(R8,{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(w$(j.taskId,"taskId"),$.requesterId,w$(j.summary,"summary"));return b(R8,{action:"complete",taskId:V.id,status:V.status})}case"block":{let V=$.runtime.blockTask(w$(j.taskId,"taskId"),$.requesterId,w$(j.reason,"reason"));return b(R8,{action:"block",taskId:V.id,status:V.status})}}}}));let X=new Map;return J.push(V0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:H0(Mj),execute:async(Y)=>{let j=b(Mj,Y);if(j.runMode==="async"){let B=$.runtime.startTeammateRun(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:$.requesterId,continueConversation:j.continueConversation||void 0});return b(uQ,{agentId:j.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${j.agentId} and queued as ${B.id}.`,runId:B.id})}let V=X.get(j.agentId);if(V){let B=await V;return b(uQ,{...B,status:"joined",deduped:!0,message:`Task for ${j.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let H=$.runtime.routeToTeammate(j.agentId,j.task,{taskId:j.taskId||void 0,fromAgentId:$.requesterId,continueConversation:j.continueConversation||void 0}).then((B)=>b(uQ,{agentId:j.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${j.agentId} and completed in sync mode.`,text:B.text,iterations:B.iterations})).finally(()=>{X.delete(j.agentId)});return X.set(j.agentId,H),await H}})),J.push(V0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:H0(Aj),execute:async(Y)=>{let j=b(Aj,Y),V=$.runtime.cancelRun(j.runId,j.reason);return b(dz,{runId:V.id,status:V.status})}})),J.push(V0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:H0(_j),execute:async(Y)=>b(dQ.array(),$.runtime.listRuns(b(_j,Y)).map(lQ))})),J.push(V0({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:H0(Kj),timeoutMs:gz,execute:async(Y)=>{let j=b(Kj,Y);if(j.runId){let B=await $.runtime.awaitRun(j.runId);return ez(B),b(dQ,lQ(B))}let V=await $.runtime.awaitAllRuns(),H=V.filter((B)=>["failed","cancelled","interrupted"].includes(B.status));if(H.length>0){let B=H.map((G)=>`${G.id}:${G.status}${G.error?`(${G.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${B}`)}return b(dQ.array(),V.map(lQ))}})),J.push(V0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:H0(Rj),execute:async(Y)=>{let j=b(Rj,Y),V=$.runtime.sendMessage($.requesterId,j.toAgentId,j.subject,j.body,j.taskId??void 0);return b(sz,{id:V.id,toAgentId:V.toAgentId})}})),J.push(V0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:H0(Fj),execute:async(Y)=>{let j=b(Fj,Y),V=$.runtime.broadcast($.requesterId,j.subject,j.body,{taskId:j.taskId??void 0});return b(uz,{delivered:V.length})}})),J.push(V0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:H0(Oj),execute:async(Y)=>{let j=b(Oj,Y);return b(iz.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:j.unreadOnly,markRead:!0}))}})),J.push(V0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:H0(zj),execute:async(Y)=>{let j=b(zj,Y),V=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:j.taskId||void 0,kind:j.kind,summary:j.summary,evidence:j.evidence?.length?j.evidence:void 0,nextAction:j.nextAction||void 0});return b(nz,{id:V.id})}})),J.push(V0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:H0(fj),execute:async(Y)=>{if(b(fj,Y),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),b(lz,{status:"cleaned"})}})),J.push(V0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:H0(Uj),execute:async(Y)=>{let j=b(Uj,Y),V=$.runtime.createOutcome({title:j.title,requiredSections:j.requiredSections,createdBy:$.requesterId});return b(pz,{outcomeId:V.id,status:V.status,requiredSections:V.requiredSections})}})),J.push(V0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:H0(Gj),execute:async(Y)=>{let j=b(Gj,Y),V=$.runtime.attachOutcomeFragment({outcomeId:j.outcomeId,section:j.section,sourceAgentId:$.requesterId,sourceRunId:j.sourceRunId||void 0,content:j.content});return b(Tj,{fragmentId:V.id,status:V.status})}})),J.push(V0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:H0(qj),execute:async(Y)=>{let j=b(qj,Y),V=$.runtime.reviewOutcomeFragment({fragmentId:j.fragmentId,reviewedBy:$.requesterId,approved:j.approved});return b(Tj,{fragmentId:V.id,status:V.status})}})),J.push(V0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:H0(Dj),execute:async(Y)=>{let j=b(Dj,Y),V=$.runtime.finalizeOutcome(j.outcomeId);return b(rz,{outcomeId:V.id,status:V.status})}})),J.push(V0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:H0(Lj),execute:async(Y)=>{return b(Lj,Y),b(az.array(),$.runtime.listOutcomes())}})),J}function yj($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}var $T=[{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:N2({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...Z5]}],ZT={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function QT($){return $==="plan"||$==="yolo"?$:"act"}function kj($){let Z=QT($.mode),Q=e0[u1({mode:Z})],W=_8($.providerId??"",$.modelId??"",Z,L8);return{mode:Z,flags:{...Q,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function hj($,Z){if(Z.disabledToolIds?.has($))return!1;let{flags:Q}=kj(Z);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let W=ZT[$];return W?Q[W]===!0:!1}function WT($,Z){if($.id==="editor"){let{flags:Q}=kj(Z),W=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:hj($.id,Z),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:hj($.id,Z)}}function N8($={}){return $T.map((Z)=>WT(Z,$))}function Ij($={}){return N8($).filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id)}function xj($){if(!$.enabled)return new Set;let Z=N8($.availabilityContext),Q=new Set(Z.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(Z.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!Q.has(W))throw Error(`Unknown tool "${W}". Available tools: ${Z.map((J)=>J.id).join(", ")}`);return new Set($.allowlist)}function pQ($,Z={}){return N8(Z).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function gj($,Z={}){return pQ($,Z)}function w8($={}){let{executorOptions:Z={},executors:Q,...W}=$,J={...n6(Z),...Q??{}};return T2({...W,executors:J})}function W5($){return $.trim().replace(/^\/+/,"").toLowerCase()}function JT($){if(!$||$.length===0)return;let Z=$.map(W5).filter((Q)=>Q.length>0);return Z.length>0?new Set(Z):void 0}function XT($,Z,Q){if(!Q)return!0;let W=W5($),J=W5(Z),X=W.includes(":")?W.split(":").at(-1)??W:W,Y=J.includes(":")?J.split(":").at(-1)??J:J;return Q.has(W)||Q.has(J)||Q.has(X)||Q.has(Y)}function C8($,Z){let Q=JT(Z);return[...$.getSnapshot("skill").entries()].map(([J,X])=>{let Y=X.item;return{id:J,name:Y.name.trim(),description:Y.description?.trim(),disabled:Y.disabled===!0,skill:Y}}).filter((J)=>XT(J.id,J.name,Q))}function YT($,Z){return C8($,Z).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,W)=>Q.localeCompare(W))}function jT($,Z,Q){let W=W5(Z);if(!W)return{error:"Missing skill name."};let J=C8($,Q),X=J.find((B)=>B.id===W);if(X){let{skill:B}=X;if(B.disabled===!0)return{error:`Skill "${B.name}" is configured but disabled.`};return{id:X.id,skill:B}}let Y=W.includes(":")?W.split(":").at(-1)??W:W,j=J.filter(({id:B})=>{if(B===Y)return!0;return B.endsWith(`:${Y}`)}),V=j.filter(({skill:B})=>B.disabled!==!0);if(V.length===1){let{id:B,skill:G}=V[0];return{id:B,skill:G}}if(V.length>1)return{error:`Skill "${Z}" is ambiguous. Use one of: ${V.map(({id:B})=>B).join(", ")}`};if(j.length===1){let{skill:B}=j[0];return{error:`Skill "${B.name}" is configured but disabled.`}}if(j.length>1)return{error:`Skill "${Z}" is ambiguous, and all matches are disabled: ${j.map(({id:B})=>B).join(", ")}`};let H=YT($,Q);return{error:H.length>0?`Skill "${Z}" not found. Available skills: ${H.join(", ")}`:"No skills are currently available."}}function rQ($,Z=Promise.resolve(),Q){let W=new Set,J=async(X,Y)=>{await Z;let j=jT($,X,Q);if("error"in j)return j.error;let{id:V,skill:H}=j;if(W.has(V))return`Skill "${H.name}" is already running.`;W.add(V);try{let B=Y?.trim(),G=B?`
167
167
  <command-args>${B}</command-args>`:"",K=H.description?.trim()?`Description: ${H.description.trim()}
168
168
 
169
169
  `:"";return`<command-name>${H.name}</command-name>${G}
@@ -171,20 +171,20 @@ ${Q}`,platform:Z.clinePlatform,metadata:Z.workspaceMetadata})}function Bj($,Z){l
171
171
  ${K}${H.instructions}
172
172
  </command-instructions>`}finally{W.delete(V)}};return Object.defineProperty(J,"configuredSkills",{get:()=>C8($,Q).map(({skill:X,...Y})=>Y),enumerable:!0,configurable:!1}),J}function mj($){let Z=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((W)=>Boolean(W))},async setup(W){if(await Z,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>eX($.watcher)});if($.registerSkillsTool)W.registerTool(z2(rQ($.watcher,Z,$.allowedSkillNames)));for(let J of F8($.watcher).filter((X)=>X.kind==="skill"&&$.includeSkills||X.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:J.name,description:J.description,handler:(X)=>{let Y=X.trim();return Y?`${J.instructions}
173
173
 
174
- ${Y}`:J.instructions}})}}}class vj{watcher;ready;stopped=!1;constructor($){this.watcher=nX($)}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(([Z,Q])=>({type:$,id:Z,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return F8(this.watcher)}resolveRuntimeSlashCommand($){return oX($,this.watcher)}hasConfiguredSkills($){return C8(this.watcher,$).some((Z)=>!Z.disabled)}createSkillsExecutor($){return rQ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return mj({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function w2($){return new vj($)}import{readFile as JT,writeFile as XT}from"node:fs/promises";import uj from"yaml";function YT($){let Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(Z);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,W,J]=Q,X=uj.parse(W);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:J,hadFrontmatter:!0}}function cj($,Z){return`---
174
+ ${Y}`:J.instructions}})}}}class vj{watcher;ready;stopped=!1;constructor($){this.watcher=nX($)}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(([Z,Q])=>({type:$,id:Z,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return F8(this.watcher)}resolveRuntimeSlashCommand($){return oX($,this.watcher)}hasConfiguredSkills($){return C8(this.watcher,$).some((Z)=>!Z.disabled)}createSkillsExecutor($){return rQ(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return mj({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function w2($){return new vj($)}import{readFile as VT,writeFile as HT}from"node:fs/promises";import uj from"yaml";function BT($){let Z=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(Z);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,W,J]=Q,X=uj.parse(W);return{data:X&&typeof X==="object"&&!Array.isArray(X)?X:{},body:J,hadFrontmatter:!0}}function cj($,Z){return`---
175
175
  ${uj.stringify($).trimEnd()}
176
176
  ---
177
- ${Z}`}function jT($,Z){let{data:Q,body:W,hadFrontmatter:J}=YT($);if(!J&&Z)return $;if(Z){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return W;return cj(Q,W)}return Q.disabled=!0,cj(Q,W)}async function dj({filePath:$,enabled:Z}){let Q=await JT($,"utf8"),W=jT(Q,Z);return await XT($,W),{filePath:$,enabled:Z,disabled:!Z}}import{spawn as rT}from"node:child_process";import{StringDecoder as FV}from"node:string_decoder";import{UnauthorizedError as HV}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as iT}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as IT}from"node:crypto";import{UnauthorizedError as xT}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as gT}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as mT}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as vT}from"@modelcontextprotocol/sdk/client/streamableHttp.js";Y5();var cT="/mcp/oauth/callback",uT=[1456,1457,1458],dT=300000;function lT($){if($ instanceof Error){let Z=$.message.trim();if(Z.length>0)return Z}return String($)}function pT($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function V5($){let Z={};try{Z=y8($.serverName,{filePath:$.settingsPath})??{}}catch{Z={}}let Q,W,J=async(Y)=>{let j=S2(Y(Z))??{};try{Z=h8($.serverName,()=>j,{filePath:$.settingsPath})}catch{Z=j}};return{provider:{get redirectUrl(){return Z.redirectUrl??$.redirectUrl},get clientMetadata(){return pT(Z.redirectUrl??$.redirectUrl)},state:()=>{return W=IT(),W},clientInformation:()=>Z.clientInformation,saveClientInformation:async(Y)=>{await J((j)=>({...j,clientInformation:Y,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>Z.tokens,saveTokens:async(Y)=>{let j=Date.now();await J((V)=>({...V,tokens:Y,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:j}))},redirectToAuthorization:async(Y)=>{Q=Y.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(Y)=>{await J((j)=>({...j,codeVerifier:Y,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!Z.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return Z.codeVerifier},invalidateCredentials:async(Y)=>{await J((j)=>{if(Y==="all")return{lastError:j.lastError,redirectUrl:j.redirectUrl};return{...j,...Y==="client"?{clientInformation:void 0}:{},...Y==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...Y==="verifier"?{codeVerifier:void 0}:{},...Y==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(Y)=>{await J((j)=>({...j,discoveryState:Y}))},discoveryState:()=>Z.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await J((Y)=>({...Y,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(Y)=>{await J((j)=>({...j,lastError:Y}))},clearError:async()=>{await J((Y)=>({...Y,lastError:void 0}))}}}function j5($){let Z=$.registration.transport;if(Z.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=Z.headers?{headers:Z.headers}:void 0;if(Z.type==="sse")return new mT(new URL(Z.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new vT(new URL(Z.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function jV($){return new gT({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function VV($){let Z=$.serverName.trim();if(!Z)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (Y5(),YV)),W=Q({filePath:$.filePath}).find((V)=>V.name===Z);if(!W)throw Error(`MCP server "${Z}" is not configured.`);if(W.disabled)throw Error(`MCP server "${Z}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${Z}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:uT,callbackPath:$.callbackPath??cT,timeoutMs:$.timeoutMs??dT,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let X=V5({settingsPath:$.filePath,serverName:Z,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await X.resetInteractiveState();let Y=jV($),j;try{let V=j5({registration:W,oauthProvider:X.provider,fetch:$.fetch});try{return await Y.connect(V),await Y.listTools(),await X.clearError(),{serverName:Z,authorized:!0,message:`MCP server "${Z}" is already authorized.`}}catch(H){if(!(H instanceof xT))throw H;if(!X.getLastAuthorizationUrl())throw Error(`MCP server "${Z}" 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=X.getLastOAuthState();if(!K)throw Error(`MCP server "${Z}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),j=jV($);let F=j5({registration:W,oauthProvider:X.provider,fetch:$.fetch});return await j.connect(F),await j.listTools(),await X.clearError(),{serverName:Z,authorized:!0,message:`MCP server "${Z}" OAuth authorization completed.`}}}catch(V){let H=lT(V);throw await X.markError(H),Error(H)}finally{await Y.close().catch(()=>{return}),await j?.close().catch(()=>{return}),J.close()}}var nT="2024-11-05",aT=5000,sT=1500,BV="http://127.0.0.1:1456/mcp/oauth/callback";function H5($){return $ instanceof Error?$.message:String($)}function GV($){let Z=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${Z.byteLength}\r
177
+ ${Z}`}function GT($,Z){let{data:Q,body:W,hadFrontmatter:J}=BT($);if(!J&&Z)return $;if(Z){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return W;return cj(Q,W)}return Q.disabled=!0,cj(Q,W)}async function dj({filePath:$,enabled:Z}){let Q=await VT($,"utf8"),W=GT(Q,Z);return await HT($,W),{filePath:$,enabled:Z,disabled:!Z}}import{spawn as sT}from"node:child_process";import{StringDecoder as FV}from"node:string_decoder";import{UnauthorizedError as HV}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as oT}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as vT}from"node:crypto";import{UnauthorizedError as cT}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as uT}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as dT}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as lT}from"@modelcontextprotocol/sdk/client/streamableHttp.js";j5();var pT="/mcp/oauth/callback",rT=[1456,1457,1458],iT=300000;function nT($){if($ instanceof Error){let Z=$.message.trim();if(Z.length>0)return Z}return String($)}function aT($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function H5($){let Z={};try{Z=y8($.serverName,{filePath:$.settingsPath})??{}}catch{Z={}}let Q,W,J=async(Y)=>{let j=S2(Y(Z))??{};try{Z=h8($.serverName,()=>j,{filePath:$.settingsPath})}catch{Z=j}};return{provider:{get redirectUrl(){return Z.redirectUrl??$.redirectUrl},get clientMetadata(){return aT(Z.redirectUrl??$.redirectUrl)},state:()=>{return W=vT(),W},clientInformation:()=>Z.clientInformation,saveClientInformation:async(Y)=>{await J((j)=>({...j,clientInformation:Y,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>Z.tokens,saveTokens:async(Y)=>{let j=Date.now();await J((V)=>({...V,tokens:Y,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:j}))},redirectToAuthorization:async(Y)=>{Q=Y.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(Y)=>{await J((j)=>({...j,codeVerifier:Y,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!Z.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return Z.codeVerifier},invalidateCredentials:async(Y)=>{await J((j)=>{if(Y==="all")return{lastError:j.lastError,redirectUrl:j.redirectUrl};return{...j,...Y==="client"?{clientInformation:void 0}:{},...Y==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...Y==="verifier"?{codeVerifier:void 0}:{},...Y==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(Y)=>{await J((j)=>({...j,discoveryState:Y}))},discoveryState:()=>Z.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await J((Y)=>({...Y,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(Y)=>{await J((j)=>({...j,lastError:Y}))},clearError:async()=>{await J((Y)=>({...Y,lastError:void 0}))}}}function V5($){let Z=$.registration.transport;if(Z.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=Z.headers?{headers:Z.headers}:void 0;if(Z.type==="sse")return new dT(new URL(Z.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new lT(new URL(Z.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function jV($){return new uT({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function VV($){let Z=$.serverName.trim();if(!Z)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (j5(),YV)),W=Q({filePath:$.filePath}).find((V)=>V.name===Z);if(!W)throw Error(`MCP server "${Z}" is not configured.`);if(W.disabled)throw Error(`MCP server "${Z}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${Z}" uses stdio transport and does not support OAuth browser flow.`);let J=await H1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:rT,callbackPath:$.callbackPath??pT,timeoutMs:$.timeoutMs??iT,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!J.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let X=H5({settingsPath:$.filePath,serverName:Z,redirectUrl:J.callbackUrl,onAuthorizationUrl:async(V)=>{await $.openUrl?.(V)}});await X.resetInteractiveState();let Y=jV($),j;try{let V=V5({registration:W,oauthProvider:X.provider,fetch:$.fetch});try{return await Y.connect(V),await Y.listTools(),await X.clearError(),{serverName:Z,authorized:!0,message:`MCP server "${Z}" is already authorized.`}}catch(H){if(!(H instanceof cT))throw H;if(!X.getLastAuthorizationUrl())throw Error(`MCP server "${Z}" 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=X.getLastOAuthState();if(!K)throw Error(`MCP server "${Z}" did not start an OAuth stateful authorization flow.`);if(G.state!==K)throw Error("OAuth authorization failed: state mismatch.");await V.finishAuth(G.code),j=jV($);let F=V5({registration:W,oauthProvider:X.provider,fetch:$.fetch});return await j.connect(F),await j.listTools(),await X.clearError(),{serverName:Z,authorized:!0,message:`MCP server "${Z}" OAuth authorization completed.`}}}catch(V){let H=nT(V);throw await X.markError(H),Error(H)}finally{await Y.close().catch(()=>{return}),await j?.close().catch(()=>{return}),J.close()}}var tT="2024-11-05",eT=5000,$O=1500,BV="http://127.0.0.1:1456/mcp/oauth/callback";function B5($){return $ instanceof Error?$.message:String($)}function GV($){let Z=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${Z.byteLength}\r
178
178
  \r
179
179
  `,"utf8");return Buffer.concat([Q,Z])}function KV($){return Buffer.from(`${JSON.stringify($)}
180
180
  `,"utf8")}class Z7{buffer="";decoder=new FV("utf8");push($){this.buffer+=this.decoder.write($);let Z=[];while(!0){let Q=this.buffer.indexOf(`\r
181
181
  \r
182
182
  `);if(Q<0)break;let J=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!J)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let X=Number.parseInt(J[1],10),Y=Q+4,j=Y+X;if(this.buffer.length<j)break;Z.push(this.buffer.slice(Y,j)),this.buffer=this.buffer.slice(j)}return Z}}class Q7{buffer="";decoder=new FV("utf8");push($){this.buffer+=this.decoder.write($);let Z=[];while(!0){let Q=this.buffer.indexOf(`
183
- `);if(Q<0)break;let W=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),W.length>0)Z.push(W)}return Z}}class AV{registration;process;nextRequestId=1;pending=new Map;framedParser=new Z7;newlineParser=new Q7;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"],Z;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:nT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},sT),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(W){Z=W instanceof Error?W:Error(String(W))}}throw Z??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((Z)=>typeof Z?.name==="string"&&typeof Z.inputSchema==="object"&&Z.inputSchema!==null).map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let Z=this.registration.transport;if(Z.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${Z.type}`);this.framedParser=new Z7,this.newlineParser=new Q7,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=rT(Z.command,Z.args??[],{cwd:Z.cwd,env:{...process.env,...Z.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=W,W.stdout.on("data",(J)=>this.handleStdout(J)),W.stderr.on("data",(J)=>{if(this.process!==W)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(J)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${H5(J)}`))}),W.once("exit",(J,X)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let Y=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${X??"null"}).${Y}`))})}handleStdout($){try{let Z=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of Z){let W=JSON.parse(Q);if(typeof W.id!=="number")continue;let J=this.pending.get(W.id);if(!J)continue;if(this.pending.delete(W.id),clearTimeout(J.timeout),W.error){let X=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;J.reject(Error(X));continue}J.resolve(W.result)}}catch(Z){this.handleProtocolFailure(Z)}}handleProtocolFailure($){let Z=this.process;if(!Z)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${H5($)}.${Q}`)),Z.kill()}async request($,Z,Q=aT){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,X={jsonrpc:"2.0",id:J,method:$,...Z?{params:Z}:{}},Y=new Promise((j,V)=>{let H=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(J,{resolve:j,reject:V,timeout:H})});try{W.stdin.write(this.protocolMode==="framed"?GV(X):KV(X))}catch(j){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw j}return Y}notify($,Z){let Q=this.process;if(!Q?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...Z?{params:Z}:{}};Q.stdin.write(this.protocolMode==="framed"?GV(W):KV(W))}failAllPending($){for(let[Z,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(Z),Q.reject($)}}class fV{registration;options;client;authContext;constructor($,Z){this.registration=$;this.options=Z}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 $=V5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BV});this.authContext=$;try{let Z=new iT({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=j5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await Z.connect(Q),await $.clearError(),this.client=Z}catch(Z){let Q=Z instanceof HV?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):H5(Z);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(Z){return await this.handleOperationError(Z)}}async callTool($){let Z=await this.ensureConnectedClient();try{return await Z.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}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 Z=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${Z} Run authorizeMcpServerOAuth for this server.`;return`${Z} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let Z=this.authContext??V5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BV}),Q=$ instanceof HV?this.formatUnauthorizedMessage(Z.getLastAuthorizationUrl()):H5($);throw await Z.markError(Q),Error(Q)}}function B5($={}){return(Z)=>Z.transport.type==="stdio"?new AV(Z):new fV(Z,$)}Y5();function k0(){return Date.now()}function oT($){return $.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema}))}class I8{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let Z=this.servers.get($.name);if(!Z){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:k0()});return}let Q=JSON.stringify(Z.registration.transport)!==JSON.stringify($.transport);if(Z.registration={...$},Z.updatedAt=k0(),Q)await this.disconnectState(Z),Z.client=void 0,Z.toolCache=void 0,Z.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.disconnectState(Z),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.connectState(Z)})}async disconnectServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.disconnectState(Z)})}async setServerDisabled($,Z){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:Z},Q.updatedAt=k0(),Z)await this.disconnectState(Q)})}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(($,Z)=>$.name.localeCompare(Z.name))}async listTools($){let Z=this.requireServer($),Q=Z.toolCacheUpdatedAt??0;if(Z.toolCache&&k0()-Q<=this.toolsCacheTtlMs)return Z.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let Z=this.requireServer($),W=await(await this.ensureConnectedClient(Z)).listTools(),J=oT(W);return Z.toolCache=J,Z.toolCacheUpdatedAt=k0(),Z.updatedAt=k0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let Z=this.requireServer($.serverName),Q=await this.ensureConnectedClient(Z);return Z.updatedAt=k0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let Z of $)await this.unregisterServer(Z)}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=k0();try{let Z=$.client??await this.clientFactory($.registration);await Z.connect(),$.client=Z,$.status="connected",$.lastError=void 0,$.updatedAt=k0()}catch(Z){throw $.status="disconnected",$.lastError=Z instanceof Error?Z.message:String(Z),$.updatedAt=k0(),Z}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=k0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=k0()}}requireServer($){let Z=this.servers.get($);if(!Z)throw Error(`Unknown MCP server: ${$}`);return Z}async runExclusive($,Z){let Q=this.operationLocks.get($)??Promise.resolve(),W,J=new Promise((Y)=>{W=Y}),X=Q.catch(()=>{return}).then(()=>J);this.operationLocks.set($,X),await Q.catch(()=>{return});try{return await Z()}finally{if(W?.(),this.operationLocks.get($)===X)this.operationLocks.delete($)}}}function b2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function UV($){return b2($)&&Object.values($).every((Z)=>typeof Z==="string")}function tT($){return Array.isArray($)&&$.every((Z)=>typeof Z==="string")}function eT($){if(!b2($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function $O($){let Z=$.env?Object.entries($.env):[];if(Z.length===0)return{ok:!0};let Q={};for(let[W,J]of Z){if(typeof J==="string"){Q[W]=J;continue}let X=J.fromEnv?.trim()||W,Y=process.env[X];if(typeof Y==="string"&&Y.length>0){Q[W]=Y;continue}if(typeof J.value==="string"){Q[W]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${X}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function DV($){if(!b2($))return{name:"",loadError:"invalid MCP server registration"};let Z=typeof $.name==="string"?$.name.trim():"";if(!Z)return{name:Z,loadError:"empty MCP server name"};let Q=$.env,W=Q===void 0?void 0:Q;if(W!==void 0){if(!b2(W))return{name:Z,loadError:"invalid env"};for(let[V,H]of Object.entries(W))if(typeof H!=="string"&&!eT(H))return{name:Z,loadError:`invalid env "${V}"`}}let J=$.transport;if(!b2(J))return{name:Z,loadError:"invalid MCP transport"};let X=J.type;if(X!=="stdio"&&X!=="sse"&&X!=="streamableHttp")return{name:Z,loadError:"invalid MCP transport type"};if(X!=="stdio"&&W!==void 0)return{name:Z,loadError:"top-level env is only supported for stdio MCP transports"};let Y=b2($.metadata)?$.metadata:void 0;if(X==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:Z,loadError:"stdio MCP transport requires command"};let H=J.args;if(H!==void 0&&!tT(H))return{name:Z,loadError:"stdio MCP transport args must be strings"};let B=J.cwd;if(B!==void 0&&typeof B!=="string")return{name:Z,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!UV(G))return{name:Z,loadError:"stdio MCP transport env must be strings"};let K=$O({name:Z,transport:{type:"stdio",command:V,args:H,cwd:B,env:G},env:W,metadata:Y});if(!K.ok)return{name:Z,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:Z,registration:{name:Z,transport:{type:"stdio",command:V,args:H,cwd:B,env:F},metadata:Y}}}if(typeof J.url!=="string"||!J.url.trim())return{name:Z,loadError:`${X} MCP transport requires url`};let j=J.headers;if(j!==void 0&&!UV(j))return{name:Z,loadError:`${X} MCP transport headers must be strings`};return{name:Z,registration:{name:Z,transport:X==="sse"?{type:"sse",url:J.url,headers:j}:{type:"streamableHttp",url:J.url,headers:j},metadata:Y}}}function W7($){let Z=new Map;return $.map(({server:Q,owner:W,ownerLabel:J})=>{let X=DV(Q);if(!X.registration)return{owner:W,name:X.name,loadError:X.loadError??"invalid MCP server registration"};let Y=Z.get(X.registration.name);if(Z.has(X.registration.name)){let j=Y?` already registered by ${Y}`:"";return{owner:W,name:X.registration.name,loadError:`duplicate MCP server name "${X.registration.name}"${j}`}}return Z.set(X.registration.name,J),{owner:W,name:X.registration.name,registration:X.registration}})}import{createHash as ZO}from"node:crypto";var LV=64,QO=/[^a-zA-Z0-9_-]+/g,_V=8,WO=1,JO="mcp_tool";function XO($){return ZO("sha1").update($).digest("hex").slice(0,_V)}function YO($){return $.replace(QO,"_")}var G5=({serverName:$,toolName:Z})=>{let Q=`${$}__${Z}`,W=YO(Q);if(W===Q&&Q.length<=LV)return Q;let J=XO(Q),X=LV-WO-_V;return`${W.slice(0,X)||JO}_${J}`};function J7($){return{[($.nameTransform??G5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function zV($){let Z={};for(let Q of $.toolNames)Object.assign(Z,J7({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return Z}import{createTool as jO}from"@cline/shared";function VO($,Z){let Q=Z.description?.trim();if(Q)return Q;return`Execute MCP tool "${Z.name}" from server "${$}".`}async function K5($){let Z=await $.provider.listTools($.serverName),Q=$.nameTransform??G5;return Z.map((W)=>{let J=Q({serverName:$.serverName,toolName:W.name});return jO({name:J,description:VO($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(X,Y)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:X&&typeof X==="object"&&!Array.isArray(X)?X:void 0,context:Y})})})}r0();import{stat as HO}from"node:fs/promises";import{isAbsolute as BO,relative as GO,resolve as TV}from"node:path";r0();function KO($,Z){let Q=GO(TV($),TV(Z));return Q===""||!Q.startsWith("..")&&!BO(Q)}var FO=32,y2=new Map;function AO($,Z){if(!y2.has($)&&y2.size>=FO){let Q=y2.keys().next().value;if(Q)y2.delete(Q)}y2.set($,Z)}async function fO($){let Z=await Promise.all($.pluginPaths.map(async(Q)=>{try{let W=await HO(Q);return`${Q}:${W.mtimeMs}:${W.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:Z})}function OV($,Z){return $.map((Q)=>({...Q,enabled:!Z.has(Q.name)}))}function UO($){return $.sort((Z,Q)=>{let W=Z.name.localeCompare(Q.name);if(W!==0)return W;return Z.path.localeCompare(Q.path)})}async function DO($,Z){if(!$.setup)return{tools:[]};let Q=[],W={registerTool:(J)=>Q.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(W,{workspaceInfo:Z}),{tools:Q}}async function qV($){let Z=_$({workspacePath:$.workspacePath,cwd:$.cwd}),Q=G1($.disabledToolNames);if(Z.length===0)return{tools:[],failures:[],warnings:[]};let W=await fO({pluginPaths:Z,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=y2.get(W);if(J)return{tools:OV(J.tools,Q),failures:J.failures,warnings:J.warnings};let X=[],Y=[],j=[],V;try{V=await F2({pluginPaths:Z,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),Y=[...V.failures],j=[...V.warnings];for(let B of V.extensions??[]){let G=B.__clinePluginPath;if(!G)continue;let K=KO($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await DO(B,{rootPath:$.workspacePath})}catch(A){Y.push({pluginPath:G,pluginName:B.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)X.push({name:A.name,pluginName:B.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(B){Y=Z.map((G)=>({pluginPath:G,phase:"load",message:B instanceof Error?B.message:String(B),stack:B instanceof Error?B.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let H=UO(X);return AO(W,{tools:H,failures:Y,warnings:j}),{tools:OV(H,Q),failures:Y,warnings:j}}async function X7($){return(await qV($)).tools}function m8($,Z){if(!Z)return"global";let Q=wV(Z,$);return!Q.startsWith("..")&&!NV(Q)?"workspace":"global"}function TO($,Z){return m8($,Z)==="workspace"?"workspace-plugin":"global-plugin"}function OO($,Z){let Q=wV(RV($),RV(Z));return Q===""||!Q.startsWith("..")&&!NV(Q)}function qO($){try{let Z=JSON.parse(LO($,"utf8"));return typeof Z.name==="string"&&Z.name.trim()?Z.name.trim():void 0}catch{return}}function MO($){let Z=MV($);while(!0){let Q=zO(Z,"package.json");if(g8(Q)){let J=qO(Q);if(J)return J;break}let W=MV(Z);if(W===Z)break;Z=W}return Y7($,_O($))}function RO($){let Z=[];for(let Q of _$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let W of z$([Q]))Z.push({directory:W,pluginName:MO(Q),pluginPath:Q,source:$.workspaceRoot?TO(Q,$.workspaceRoot):"global-plugin"});return Z.sort((Q,W)=>W.directory.length-Q.directory.length)}function EO($,Z){return Z.find((Q)=>OO(Q.directory,$))}function x8($){return[...$].sort((Z,Q)=>{let W=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(Z.source!==Q.source)return W(Z.source)-W(Q.source);return Z.name.localeCompare(Q.name)})}function CV($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function PV($,Z){return $.cwd?.trim()||Z||process.cwd()}async function EV($,Z){if($.userInstructionService)return await Z($.userInstructionService);let Q=CV($),W=PV($,Q),J=w2({skills:{workspacePath:Q||void 0,includePluginSkills:!0,cwd:W},rules:{workspacePath:Q||void 0},workflows:{workspacePath:Q||void 0}});try{return await J.start(),await Z(J)}finally{J.stop()}}function NO($,Z){if(!$)return;let Q=$.listRecords("skill");if(Z.id){let W=Q.find((J)=>J.id===Z.id);if(W)return W}for(let W of Q)if(W.filePath===Z.path||W.item.name===Z.name||W.id===Z.name)return W;return}class h2{async list($={}){return await EV($,async(Z)=>{let Q=CV($),W=RO({workspaceRoot:Q,cwd:PV($,Q)}),J=[],X=[],Y=[],j=[],V=[];if(Z){for(let B of Z.listRecords("workflow")){let G=B.item;J.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"workflow",source:m8(B.filePath,Q),description:G.instructions,toggleable:!1})}for(let B of Z.listRecords("rule")){let G=B.item;X.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"rule",source:m8(B.filePath,Q),description:G.instructions,toggleable:!1})}for(let B of Z.listRecords("skill")){let G=B.item,K=EO(B.filePath,W);Y.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??m8(B.filePath,Q),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Q)try{for(let B of await X7({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${B.pluginName}:${B.name}:${B.path}`,name:B.name,path:B.path,enabled:B.enabled,kind:"tool",source:B.source,description:B.description,toggleable:!0})}catch{}let H=Z0();if(w$({filePath:H}))try{for(let B of $1({filePath:H}))V.push({id:B.name,name:B.name,path:H,enabled:B.disabled!==!0,kind:"mcp",source:m8(H,Q),description:B.transport.type,toggleable:!0})}catch{}return{workflows:x8(J.filter((B)=>g8(B.path))),rules:x8(X.filter((B)=>g8(B.path))),skills:x8(Y.filter((B)=>g8(B.path))),tools:x8(j),mcp:x8(V.filter((B)=>g8(B.path)))}})}async toggle($){if($.type==="skills")return await EV($,async(Z)=>{let Q=NO(Z,$),W=Q?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??Y7($.path??"")}'.`);let J=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,X=$.enabled??(J!==void 0?!J:void 0);if(X===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Y7($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await dj({filePath:W,enabled:X}),await Z?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:Z}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)vZ($.name);else _X($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let Z=$.name?.trim()||$.id?.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||Z0(),W=$.enabled;if(W===void 0){let J=$1({filePath:Q}).find((X)=>X.name===Z);if(!J)throw Error(`Unknown MCP server: ${Z}`);W=J.disabled===!0}return b8({filePath:Q,name:Z,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function v8(){return new h2}function SV($){return{async list(Z){let Q=$;if(Q.listSettings)return await Q.listSettings(Z);return await v8().list(Z)},async toggle(Z){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(Z);return await v8().toggle(Z)}}}function bV($){function Z(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return Z().list(Q)},update(Q){return Z().update(Q)},delete(Q){return Z().delete(Q)}}}function T0(...$){let Z,Q;for(let J of $){if(!J)continue;if(J.toolExecutors)Z={...Z??{},...J.toolExecutors};if(J.requestToolApproval)Q=J.requestToolApproval}let W=Z&&Object.keys(Z).length>0;if(!W&&!Q)return;return{...W?{toolExecutors:Z}:{},...Q?{requestToolApproval:Q}:{}}}var c8="session_not_found";class C$ extends Error{sessionId;code="session_not_found";constructor($,Z){super(Z??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function P$($){return $ instanceof C$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function j7($){let{hooks:Z,logger:Q,telemetry:W,extensionContext:J,extraTools:X,extensions:Y,onTeamEvent:j,onConsecutiveMistakeLimitReached:V,checkpoint:H,compaction:B,...G}=$,K={};if(Z)K.hooks=Z;if(Q)K.logger=Q;if(W)K.telemetry=W;if(J)K.extensionContext=J;if(X)K.extraTools=X;if(Y)K.extensions=Y;if(j)K.onTeamEvent=j;if(V)K.onConsecutiveMistakeLimitReached=V;if(H?.createCheckpoint)K.checkpoint=H;if(B?.compact)K.compaction=B;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...H?{checkpoint:{enabled:H.enabled}}:{},...B?{compaction:{enabled:B.enabled,strategy:B.strategy,thresholdRatio:B.thresholdRatio,reserveTokens:B.reserveTokens,preserveRecentTokens:B.preserveRecentTokens,maxInputTokens:B.maxInputTokens,summarizer:B.summarizer}}:{}},...F?{localRuntime:F}:{}}}function yV($){let Z=$.config;return"providerId"in Z?{...$,config:{...Z,...wO($.localRuntime)},localRuntime:$.localRuntime}:$}function V7($,Z={}){let Q=j7($.config),W=T0(Z.defaultCapabilities,$.capabilities),J=CO(Q.localRuntime,$.localRuntime),X=Z.withExtensionContext?.(J?.extensionContext);if(X)J={...J??{},extensionContext:X};return{...$,...Q,...J?{localRuntime:J}:{},...W?{capabilities:W}:{}}}function wO($){if(!$)return{};let{modelCatalogDefaults:Z,userInstructionService:Q,configExtensions:W,onTeamRestored:J,...X}=$;return X}function CO(...$){let Z={};for(let Q of $)if(Q)Object.assign(Z,Q);return Object.keys(Z).length>0?Z:void 0}G0();function hV($){let Z=$.input.config.telemetry??$.telemetry;if(!Z)return;Z.capture({event:I.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??z0.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 u8($){return!!$&&typeof $==="object"&&!Array.isArray($)}function H7($){let Z=$?.trim();return Z?Z:void 0}function PO($,Z){let Q=$?.trim();if(!Q)return Z;let W=Date.parse(Q);if(!Number.isFinite(W))return Z;return new Date(W).toISOString()}function kV($,Z){return new Date(new Date($).getTime()+Math.max(0,Math.floor(Z))*1000).toISOString()}function IV($,Z){return new Date(new Date($).getTime()-Math.max(0,Math.floor(Z))*1000).toISOString()}function SO($,Z){if(!$)return Z;return new Date($).getTime()>=new Date(Z).getTime()?$:Z}function bO($,Z){let Q=$.eventId.trim(),W=$.eventType.trim(),J=$.source.trim(),X=H7($.subject),Y=H7($.dedupeKey)??`${W}:${J}:${X??Q}`;return{eventId:Q,eventType:W,source:J,subject:X,occurredAt:PO($.occurredAt,Z),workspaceRoot:H7($.workspaceRoot),payload:u8($.payload)?$.payload:void 0,attributes:u8($.attributes)?$.attributes:void 0,dedupeKey:Y}}function B7($,Z){if(!Z)return;let Q=Z.split("."),W=$;for(let J of Q){if(!u8(W))return;W=W[J]}return W}function yO($,Z){if($.attributes&&Object.hasOwn($.attributes,Z))return $.attributes[Z];if($.payload&&Object.hasOwn($.payload,Z))return $.payload[Z];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=B7(Q,Z);if(W!==void 0)return W;if($.attributes){let J=B7($.attributes,Z);if(J!==void 0)return J}if($.payload)return B7($.payload,Z);return}function F5($,Z){if(Array.isArray(Z))return Z.some((Q)=>F5($,Q));if(Array.isArray($))return $.some((Q)=>F5(Q,Z));if(u8(Z)){if(!u8($))return!1;return Object.entries(Z).every(([Q,W])=>F5($[Q],W))}return Object.is($,Z)}function hO($,Z){if(!Z||Object.keys(Z).length===0)return!0;return Object.entries(Z).every(([Q,W])=>F5(yO($,Q),W))}class G7{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let Z=new Date(this.nowFn()).toISOString(),Q=bO($,Z),W=this.store.insertEventLog(Q,{receivedAtIso:Z});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Q.eventType),X=[],Y=[],j=[];for(let B of J){if(!hO(Q,B.filters)){X.push({specId:B.specId,externalId:B.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}Y.push(B);let G=this.materializeForSpec(B,Q,W.record.receivedAt);if(G.run)j.push(G.run);else X.push({specId:B.specId,externalId:B.externalId,reason:G.reason,dedupeKey:Q.dedupeKey})}let V=Y.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:V,matchedSpecCount:Y.length,queuedRunCount:j.length,suppressedCount:X.filter((B)=>B.reason!=="filter_mismatch").length});let H=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:V,matchedSpecCount:Y.length,queuedRunCount:j.length}),{event:H??W.record,duplicate:!1,matchedSpecs:Y,queuedRuns:j,suppressions:X}}catch(J){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:J});throw J}}materializeForSpec($,Z,Q){let W=Z.dedupeKey??Z.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(V){let H=SO(V.scheduledFor,kV(Q,J)),B=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:Z.eventId,scheduledFor:H});if(B)return{run:B,reason:"dedupe_window"}}}let X=$.dedupeWindowSeconds??0;if(X>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:IV(Q,X)}))return{reason:"dedupe_window"};let Y=$.cooldownSeconds??0;if(Y>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:IV(Q,Y)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:Z.eventId,scheduledFor:J>0?kV(Q,J):Q}),reason:"dedupe_window"}}}class d8{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},Z=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of Z)if(this.materializeOneOff(W))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of Q)try{if(this.materializeSchedule(W))$.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 lO}from"node:path";import{buildClineSystemPrompt as pO}from"@cline/shared";import{nowIso as vV}from"@cline/shared/db";import{basename as kO,resolve as IO}from"node:path";import{performance as xV}from"node:perf_hooks";import{processWorkspaceInfo as gV}from"@cline/shared";import xO from"simple-git";function S$($){return IO($)}async function f5($){return(await K7($)).info}function A5($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function K7($){let Z=S$($),Q={rootPath:Z,hint:kO(Z)},W;try{let J=xO({baseDir:Z});if(!await J.checkIsRepo())return{info:Q,vcsType:"none"};try{let Y=await J.getRemotes(!0);if(Y.length>0){let j=Y.map((V)=>{let H=V.refs.fetch||V.refs.push;return`${V.name}: ${H}`});Q.associatedRemoteUrls=j}}catch(Y){W??=A5(Y)}try{let Y=(await J.revparse(["HEAD"])).trim();if(Y.length>0)Q.latestGitCommitHash=Y}catch(Y){W??=A5(Y)}try{let Y=(await J.branch()).current.trim();if(Y.length>0)Q.latestGitBranchName=Y}catch(Y){W??=A5(Y)}return{info:Q,vcsType:"git",error:W}}catch(J){return{info:Q,vcsType:"none",error:A5(J)}}}async function F7($){let Z=await f5($);return gV(Z)}async function mV($){let Z=xV.now(),Q=await K7($),W=xV.now()-Z,J=Q.info;return{workspaceInfo:J,workspaceMetadata:gV(J),durationMs:W,vcsType:Q.vcsType,initError:Q.error}}import{mkdirSync as gO,writeFileSync as mO}from"node:fs";import{join as vO}from"node:path";import{resolveCronReportsDir as cO}from"@cline/shared/storage";function p1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function b$($,Z){if(Z===void 0||Z===null)return;return`${$}: ${p1(Z)}`}function uO($,Z,Q){let W=[`runId: ${p1($.runId)}`,`specId: ${p1(Z.specId)}`,`externalId: ${p1(Z.externalId)}`,`title: ${p1(Z.title)}`,`triggerKind: ${p1($.triggerKind)}`,`status: ${p1($.status)}`,`sourcePath: ${p1(Z.sourcePath)}`],J=[b$("sessionId",$.sessionId),b$("startedAt",$.startedAt),b$("completedAt",$.completedAt),b$("triggerEventId",$.triggerEventId),b$("triggerEventType",Q?.eventType),b$("triggerEventSource",Q?.source),b$("triggerEventSubject",Q?.subject)];for(let X of J)if(X)W.push(X);return`---
183
+ `);if(Q<0)break;let W=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),W.length>0)Z.push(W)}return Z}}class AV{registration;process;nextRequestId=1;pending=new Map;framedParser=new Z7;newlineParser=new Q7;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"],Z;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:tT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},$O),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(W){Z=W instanceof Error?W:Error(String(W))}}throw Z??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((Z)=>typeof Z?.name==="string"&&typeof Z.inputSchema==="object"&&Z.inputSchema!==null).map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let Z=this.registration.transport;if(Z.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${Z.type}`);this.framedParser=new Z7,this.newlineParser=new Q7,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=sT(Z.command,Z.args??[],{cwd:Z.cwd,env:{...process.env,...Z.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=W,W.stdout.on("data",(J)=>this.handleStdout(J)),W.stderr.on("data",(J)=>{if(this.process!==W)return;if(this.stderrBuffer+=J.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(J)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${B5(J)}`))}),W.once("exit",(J,X)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let Y=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${J??"null"}, signal=${X??"null"}).${Y}`))})}handleStdout($){try{let Z=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of Z){let W=JSON.parse(Q);if(typeof W.id!=="number")continue;let J=this.pending.get(W.id);if(!J)continue;if(this.pending.delete(W.id),clearTimeout(J.timeout),W.error){let X=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;J.reject(Error(X));continue}J.resolve(W.result)}}catch(Z){this.handleProtocolFailure(Z)}}handleProtocolFailure($){let Z=this.process;if(!Z)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${B5($)}.${Q}`)),Z.kill()}async request($,Z,Q=eT){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let J=this.nextRequestId++,X={jsonrpc:"2.0",id:J,method:$,...Z?{params:Z}:{}},Y=new Promise((j,V)=>{let H=setTimeout(()=>{this.pending.delete(J),V(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(J,{resolve:j,reject:V,timeout:H})});try{W.stdin.write(this.protocolMode==="framed"?GV(X):KV(X))}catch(j){let V=this.pending.get(J);if(V)clearTimeout(V.timeout),this.pending.delete(J);throw j}return Y}notify($,Z){let Q=this.process;if(!Q?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...Z?{params:Z}:{}};Q.stdin.write(this.protocolMode==="framed"?GV(W):KV(W))}failAllPending($){for(let[Z,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(Z),Q.reject($)}}class fV{registration;options;client;authContext;constructor($,Z){this.registration=$;this.options=Z}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 $=H5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BV});this.authContext=$;try{let Z=new oT({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=V5({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await Z.connect(Q),await $.clearError(),this.client=Z}catch(Z){let Q=Z instanceof HV?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):B5(Z);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(Z){return await this.handleOperationError(Z)}}async callTool($){let Z=await this.ensureConnectedClient();try{return await Z.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}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 Z=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${Z} Run authorizeMcpServerOAuth for this server.`;return`${Z} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let Z=this.authContext??H5({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BV}),Q=$ instanceof HV?this.formatUnauthorizedMessage(Z.getLastAuthorizationUrl()):B5($);throw await Z.markError(Q),Error(Q)}}function G5($={}){return(Z)=>Z.transport.type==="stdio"?new AV(Z):new fV(Z,$)}j5();function k0(){return Date.now()}function ZO($){return $.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema}))}class I8{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let Z=this.servers.get($.name);if(!Z){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:k0()});return}let Q=JSON.stringify(Z.registration.transport)!==JSON.stringify($.transport);if(Z.registration={...$},Z.updatedAt=k0(),Q)await this.disconnectState(Z),Z.client=void 0,Z.toolCache=void 0,Z.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.disconnectState(Z),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.connectState(Z)})}async disconnectServer($){await this.runExclusive($,async()=>{let Z=this.requireServer($);await this.disconnectState(Z)})}async setServerDisabled($,Z){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:Z},Q.updatedAt=k0(),Z)await this.disconnectState(Q)})}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(($,Z)=>$.name.localeCompare(Z.name))}async listTools($){let Z=this.requireServer($),Q=Z.toolCacheUpdatedAt??0;if(Z.toolCache&&k0()-Q<=this.toolsCacheTtlMs)return Z.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let Z=this.requireServer($),W=await(await this.ensureConnectedClient(Z)).listTools(),J=ZO(W);return Z.toolCache=J,Z.toolCacheUpdatedAt=k0(),Z.updatedAt=k0(),J})}async callTool($){return this.runExclusive($.serverName,async()=>{let Z=this.requireServer($.serverName),Q=await this.ensureConnectedClient(Z);return Z.updatedAt=k0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let Z of $)await this.unregisterServer(Z)}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=k0();try{let Z=$.client??await this.clientFactory($.registration);await Z.connect(),$.client=Z,$.status="connected",$.lastError=void 0,$.updatedAt=k0()}catch(Z){throw $.status="disconnected",$.lastError=Z instanceof Error?Z.message:String(Z),$.updatedAt=k0(),Z}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=k0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=k0()}}requireServer($){let Z=this.servers.get($);if(!Z)throw Error(`Unknown MCP server: ${$}`);return Z}async runExclusive($,Z){let Q=this.operationLocks.get($)??Promise.resolve(),W,J=new Promise((Y)=>{W=Y}),X=Q.catch(()=>{return}).then(()=>J);this.operationLocks.set($,X),await Q.catch(()=>{return});try{return await Z()}finally{if(W?.(),this.operationLocks.get($)===X)this.operationLocks.delete($)}}}function b2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function UV($){return b2($)&&Object.values($).every((Z)=>typeof Z==="string")}function QO($){return Array.isArray($)&&$.every((Z)=>typeof Z==="string")}function WO($){if(!b2($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function JO($){let Z=$.env?Object.entries($.env):[];if(Z.length===0)return{ok:!0};let Q={};for(let[W,J]of Z){if(typeof J==="string"){Q[W]=J;continue}let X=J.fromEnv?.trim()||W,Y=process.env[X];if(typeof Y==="string"&&Y.length>0){Q[W]=Y;continue}if(typeof J.value==="string"){Q[W]=J.value;continue}if(J.required===!0)return{ok:!1,reason:`required environment variable "${X}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function DV($){if(!b2($))return{name:"",loadError:"invalid MCP server registration"};let Z=typeof $.name==="string"?$.name.trim():"";if(!Z)return{name:Z,loadError:"empty MCP server name"};let Q=$.env,W=Q===void 0?void 0:Q;if(W!==void 0){if(!b2(W))return{name:Z,loadError:"invalid env"};for(let[V,H]of Object.entries(W))if(typeof H!=="string"&&!WO(H))return{name:Z,loadError:`invalid env "${V}"`}}let J=$.transport;if(!b2(J))return{name:Z,loadError:"invalid MCP transport"};let X=J.type;if(X!=="stdio"&&X!=="sse"&&X!=="streamableHttp")return{name:Z,loadError:"invalid MCP transport type"};if(X!=="stdio"&&W!==void 0)return{name:Z,loadError:"top-level env is only supported for stdio MCP transports"};let Y=b2($.metadata)?$.metadata:void 0;if(X==="stdio"){let V=J.command;if(typeof V!=="string"||!V.trim())return{name:Z,loadError:"stdio MCP transport requires command"};let H=J.args;if(H!==void 0&&!QO(H))return{name:Z,loadError:"stdio MCP transport args must be strings"};let B=J.cwd;if(B!==void 0&&typeof B!=="string")return{name:Z,loadError:"stdio MCP transport cwd must be a string"};let G=J.env;if(G!==void 0&&!UV(G))return{name:Z,loadError:"stdio MCP transport env must be strings"};let K=JO({name:Z,transport:{type:"stdio",command:V,args:H,cwd:B,env:G},env:W,metadata:Y});if(!K.ok)return{name:Z,loadError:K.reason};let F=G||K.env?{...G??{},...K.env??{}}:void 0;return{name:Z,registration:{name:Z,transport:{type:"stdio",command:V,args:H,cwd:B,env:F},metadata:Y}}}if(typeof J.url!=="string"||!J.url.trim())return{name:Z,loadError:`${X} MCP transport requires url`};let j=J.headers;if(j!==void 0&&!UV(j))return{name:Z,loadError:`${X} MCP transport headers must be strings`};return{name:Z,registration:{name:Z,transport:X==="sse"?{type:"sse",url:J.url,headers:j}:{type:"streamableHttp",url:J.url,headers:j},metadata:Y}}}function W7($){let Z=new Map;return $.map(({server:Q,owner:W,ownerLabel:J})=>{let X=DV(Q);if(!X.registration)return{owner:W,name:X.name,loadError:X.loadError??"invalid MCP server registration"};let Y=Z.get(X.registration.name);if(Z.has(X.registration.name)){let j=Y?` already registered by ${Y}`:"";return{owner:W,name:X.registration.name,loadError:`duplicate MCP server name "${X.registration.name}"${j}`}}return Z.set(X.registration.name,J),{owner:W,name:X.registration.name,registration:X.registration}})}import{createHash as XO}from"node:crypto";var LV=64,YO=/[^a-zA-Z0-9_-]+/g,_V=8,jO=1,VO="mcp_tool";function HO($){return XO("sha1").update($).digest("hex").slice(0,_V)}function BO($){return $.replace(YO,"_")}var K5=({serverName:$,toolName:Z})=>{let Q=`${$}__${Z}`,W=BO(Q);if(W===Q&&Q.length<=LV)return Q;let J=HO(Q),X=LV-jO-_V;return`${W.slice(0,X)||VO}_${J}`};function J7($){return{[($.nameTransform??K5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function zV($){let Z={};for(let Q of $.toolNames)Object.assign(Z,J7({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return Z}import{createTool as GO}from"@cline/shared";function KO($,Z){let Q=Z.description?.trim();if(Q)return Q;return`Execute MCP tool "${Z.name}" from server "${$}".`}async function F5($){let Z=await $.provider.listTools($.serverName),Q=$.nameTransform??K5;return Z.map((W)=>{let J=Q({serverName:$.serverName,toolName:W.name});return GO({name:J,description:KO($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(X,Y)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:X&&typeof X==="object"&&!Array.isArray(X)?X:void 0,context:Y})})})}r0();import{stat as FO}from"node:fs/promises";import{isAbsolute as AO,relative as fO,resolve as TV}from"node:path";r0();function UO($,Z){let Q=fO(TV($),TV(Z));return Q===""||!Q.startsWith("..")&&!AO(Q)}var DO=32,y2=new Map;function LO($,Z){if(!y2.has($)&&y2.size>=DO){let Q=y2.keys().next().value;if(Q)y2.delete(Q)}y2.set($,Z)}async function _O($){let Z=await Promise.all($.pluginPaths.map(async(Q)=>{try{let W=await FO(Q);return`${Q}:${W.mtimeMs}:${W.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:Z})}function OV($,Z){return $.map((Q)=>({...Q,enabled:!Z.has(Q.name)}))}function zO($){return $.sort((Z,Q)=>{let W=Z.name.localeCompare(Q.name);if(W!==0)return W;return Z.path.localeCompare(Q.path)})}async function TO($,Z){if(!$.setup)return{tools:[]};let Q=[],W={registerTool:(J)=>Q.push(J),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(J)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(W,{workspaceInfo:Z}),{tools:Q}}async function qV($){let Z=z$({workspacePath:$.workspacePath,cwd:$.cwd}),Q=K1($.disabledToolNames);if(Z.length===0)return{tools:[],failures:[],warnings:[]};let W=await _O({pluginPaths:Z,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),J=y2.get(W);if(J)return{tools:OV(J.tools,Q),failures:J.failures,warnings:J.warnings};let X=[],Y=[],j=[],V;try{V=await F2({pluginPaths:Z,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),Y=[...V.failures],j=[...V.warnings];for(let B of V.extensions??[]){let G=B.__clinePluginPath;if(!G)continue;let K=UO($.workspacePath,G)?"workspace-plugin":"global-plugin",F;try{F=await TO(B,{rootPath:$.workspacePath})}catch(A){Y.push({pluginPath:G,pluginName:B.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)X.push({name:A.name,pluginName:B.name,path:G,source:K,description:A.description?.trim()||void 0})}}catch(B){Y=Z.map((G)=>({pluginPath:G,phase:"load",message:B instanceof Error?B.message:String(B),stack:B instanceof Error?B.stack:void 0}))}finally{await V?.shutdown().catch(()=>{})}let H=zO(X);return LO(W,{tools:H,failures:Y,warnings:j}),{tools:OV(H,Q),failures:Y,warnings:j}}async function X7($){return(await qV($)).tools}function m8($,Z){if(!Z)return"global";let Q=wV(Z,$);return!Q.startsWith("..")&&!NV(Q)?"workspace":"global"}function RO($,Z){return m8($,Z)==="workspace"?"workspace-plugin":"global-plugin"}function EO($,Z){let Q=wV(RV($),RV(Z));return Q===""||!Q.startsWith("..")&&!NV(Q)}function NO($){try{let Z=JSON.parse(OO($,"utf8"));return typeof Z.name==="string"&&Z.name.trim()?Z.name.trim():void 0}catch{return}}function wO($){let Z=MV($);while(!0){let Q=MO(Z,"package.json");if(g8(Q)){let J=NO(Q);if(J)return J;break}let W=MV(Z);if(W===Z)break;Z=W}return Y7($,qO($))}function CO($){let Z=[];for(let Q of z$({workspacePath:$.workspaceRoot||void 0,cwd:$.cwd}))for(let W of T$([Q]))Z.push({directory:W,pluginName:wO(Q),pluginPath:Q,source:$.workspaceRoot?RO(Q,$.workspaceRoot):"global-plugin"});return Z.sort((Q,W)=>W.directory.length-Q.directory.length)}function PO($,Z){return Z.find((Q)=>EO(Q.directory,$))}function x8($){return[...$].sort((Z,Q)=>{let W=(J)=>{switch(J){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(Z.source!==Q.source)return W(Z.source)-W(Q.source);return Z.name.localeCompare(Q.name)})}function CV($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}function PV($,Z){return $.cwd?.trim()||Z||process.cwd()}async function EV($,Z){if($.userInstructionService)return await Z($.userInstructionService);let Q=CV($),W=PV($,Q),J=w2({skills:{workspacePath:Q||void 0,includePluginSkills:!0,cwd:W},rules:{workspacePath:Q||void 0},workflows:{workspacePath:Q||void 0}});try{return await J.start(),await Z(J)}finally{J.stop()}}function SO($,Z){if(!$)return;let Q=$.listRecords("skill");if(Z.id){let W=Q.find((J)=>J.id===Z.id);if(W)return W}for(let W of Q)if(W.filePath===Z.path||W.item.name===Z.name||W.id===Z.name)return W;return}class h2{async list($={}){return await EV($,async(Z)=>{let Q=CV($),W=CO({workspaceRoot:Q,cwd:PV($,Q)}),J=[],X=[],Y=[],j=[],V=[];if(Z){for(let B of Z.listRecords("workflow")){let G=B.item;J.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"workflow",source:m8(B.filePath,Q),description:G.instructions,toggleable:!1})}for(let B of Z.listRecords("rule")){let G=B.item;X.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"rule",source:m8(B.filePath,Q),description:G.instructions,toggleable:!1})}for(let B of Z.listRecords("skill")){let G=B.item,K=PO(B.filePath,W);Y.push({id:B.id,name:G.name,path:B.filePath,enabled:G.disabled!==!0,kind:"skill",source:K?.source??m8(B.filePath,Q),description:G.description,pluginName:K?.pluginName,pluginPath:K?.pluginPath,toggleable:!0})}}if(Q)try{for(let B of await X7({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${B.pluginName}:${B.name}:${B.path}`,name:B.name,path:B.path,enabled:B.enabled,kind:"tool",source:B.source,description:B.description,toggleable:!0})}catch{}let H=Z0();if(C$({filePath:H}))try{for(let B of $1({filePath:H}))V.push({id:B.name,name:B.name,path:H,enabled:B.disabled!==!0,kind:"mcp",source:m8(H,Q),description:B.transport.type,toggleable:!0})}catch{}return{workflows:x8(J.filter((B)=>g8(B.path))),rules:x8(X.filter((B)=>g8(B.path))),skills:x8(Y.filter((B)=>g8(B.path))),tools:x8(j),mcp:x8(V.filter((B)=>g8(B.path)))}})}async toggle($){if($.type==="skills")return await EV($,async(Z)=>{let Q=SO(Z,$),W=Q?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??Y7($.path??"")}'.`);let J=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,X=$.enabled??(J!==void 0?!J:void 0);if(X===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??Y7($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await dj({filePath:W,enabled:X}),await Z?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:Z}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)cZ($.name);else _X($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let Z=$.name?.trim()||$.id?.trim();if(!Z)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||Z0(),W=$.enabled;if(W===void 0){let J=$1({filePath:Q}).find((X)=>X.name===Z);if(!J)throw Error(`Unknown MCP server: ${Z}`);W=J.disabled===!0}return b8({filePath:Q,name:Z,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function v8(){return new h2}function SV($){return{async list(Z){let Q=$;if(Q.listSettings)return await Q.listSettings(Z);return await v8().list(Z)},async toggle(Z){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(Z);return await v8().toggle(Z)}}}function bV($){function Z(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return Z().list(Q)},update(Q){return Z().update(Q)},delete(Q){return Z().delete(Q)}}}function O0(...$){let Z,Q;for(let J of $){if(!J)continue;if(J.toolExecutors)Z={...Z??{},...J.toolExecutors};if(J.requestToolApproval)Q=J.requestToolApproval}let W=Z&&Object.keys(Z).length>0;if(!W&&!Q)return;return{...W?{toolExecutors:Z}:{},...Q?{requestToolApproval:Q}:{}}}var c8="session_not_found";class P$ extends Error{sessionId;code="session_not_found";constructor($,Z){super(Z??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function S$($){return $ instanceof P$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function j7($){let{hooks:Z,logger:Q,telemetry:W,extensionContext:J,extraTools:X,extensions:Y,onTeamEvent:j,onConsecutiveMistakeLimitReached:V,checkpoint:H,compaction:B,...G}=$,K={};if(Z)K.hooks=Z;if(Q)K.logger=Q;if(W)K.telemetry=W;if(J)K.extensionContext=J;if(X)K.extraTools=X;if(Y)K.extensions=Y;if(j)K.onTeamEvent=j;if(V)K.onConsecutiveMistakeLimitReached=V;if(H?.createCheckpoint)K.checkpoint=H;if(B?.compact)K.compaction=B;let F=Object.keys(K).length>0?K:void 0;return{config:{...G,...H?{checkpoint:{enabled:H.enabled}}:{},...B?{compaction:{enabled:B.enabled,strategy:B.strategy,thresholdRatio:B.thresholdRatio,reserveTokens:B.reserveTokens,preserveRecentTokens:B.preserveRecentTokens,maxInputTokens:B.maxInputTokens,summarizer:B.summarizer}}:{}},...F?{localRuntime:F}:{}}}function yV($){let Z=$.config;return"providerId"in Z?{...$,config:{...Z,...bO($.localRuntime)},localRuntime:$.localRuntime}:$}function V7($,Z={}){let Q=j7($.config),W=O0(Z.defaultCapabilities,$.capabilities),J=yO(Q.localRuntime,$.localRuntime),X=Z.withExtensionContext?.(J?.extensionContext);if(X)J={...J??{},extensionContext:X};return{...$,...Q,...J?{localRuntime:J}:{},...W?{capabilities:W}:{}}}function bO($){if(!$)return{};let{modelCatalogDefaults:Z,userInstructionService:Q,configExtensions:W,onTeamRestored:J,...X}=$;return X}function yO(...$){let Z={};for(let Q of $)if(Q)Object.assign(Z,Q);return Object.keys(Z).length>0?Z:void 0}G0();function hV($){let Z=$.input.config.telemetry??$.telemetry;if(!Z)return;Z.capture({event:I.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??T0.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 u8($){return!!$&&typeof $==="object"&&!Array.isArray($)}function H7($){let Z=$?.trim();return Z?Z:void 0}function hO($,Z){let Q=$?.trim();if(!Q)return Z;let W=Date.parse(Q);if(!Number.isFinite(W))return Z;return new Date(W).toISOString()}function kV($,Z){return new Date(new Date($).getTime()+Math.max(0,Math.floor(Z))*1000).toISOString()}function IV($,Z){return new Date(new Date($).getTime()-Math.max(0,Math.floor(Z))*1000).toISOString()}function kO($,Z){if(!$)return Z;return new Date($).getTime()>=new Date(Z).getTime()?$:Z}function IO($,Z){let Q=$.eventId.trim(),W=$.eventType.trim(),J=$.source.trim(),X=H7($.subject),Y=H7($.dedupeKey)??`${W}:${J}:${X??Q}`;return{eventId:Q,eventType:W,source:J,subject:X,occurredAt:hO($.occurredAt,Z),workspaceRoot:H7($.workspaceRoot),payload:u8($.payload)?$.payload:void 0,attributes:u8($.attributes)?$.attributes:void 0,dedupeKey:Y}}function B7($,Z){if(!Z)return;let Q=Z.split("."),W=$;for(let J of Q){if(!u8(W))return;W=W[J]}return W}function xO($,Z){if($.attributes&&Object.hasOwn($.attributes,Z))return $.attributes[Z];if($.payload&&Object.hasOwn($.payload,Z))return $.payload[Z];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=B7(Q,Z);if(W!==void 0)return W;if($.attributes){let J=B7($.attributes,Z);if(J!==void 0)return J}if($.payload)return B7($.payload,Z);return}function A5($,Z){if(Array.isArray(Z))return Z.some((Q)=>A5($,Q));if(Array.isArray($))return $.some((Q)=>A5(Q,Z));if(u8(Z)){if(!u8($))return!1;return Object.entries(Z).every(([Q,W])=>A5($[Q],W))}return Object.is($,Z)}function gO($,Z){if(!Z||Object.keys(Z).length===0)return!0;return Object.entries(Z).every(([Q,W])=>A5(xO($,Q),W))}class G7{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let Z=new Date(this.nowFn()).toISOString(),Q=IO($,Z),W=this.store.insertEventLog(Q,{receivedAtIso:Z});if(!W.created)return this.logger?.debug("cron.event.duplicate",{eventId:W.record.eventId,eventType:W.record.eventType,source:W.record.source}),{event:W.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:W.record.dedupeKey}]};try{let J=this.store.listEventSpecsForType(Q.eventType),X=[],Y=[],j=[];for(let B of J){if(!gO(Q,B.filters)){X.push({specId:B.specId,externalId:B.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}Y.push(B);let G=this.materializeForSpec(B,Q,W.record.receivedAt);if(G.run)j.push(G.run);else X.push({specId:B.specId,externalId:B.externalId,reason:G.reason,dedupeKey:Q.dedupeKey})}let V=Y.length===0?"unmatched":j.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:V,matchedSpecCount:Y.length,queuedRunCount:j.length,suppressedCount:X.filter((B)=>B.reason!=="filter_mismatch").length});let H=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:V,matchedSpecCount:Y.length,queuedRunCount:j.length}),{event:H??W.record,duplicate:!1,matchedSpecs:Y,queuedRuns:j,suppressions:X}}catch(J){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:J instanceof Error?J.message:String(J)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:J});throw J}}materializeForSpec($,Z,Q){let W=Z.dedupeKey??Z.eventId,J=$.debounceSeconds??0;if(J>0){let V=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(V){let H=kO(V.scheduledFor,kV(Q,J)),B=this.store.updateQueuedEventRunForDebounce({runId:V.runId,triggerEventId:Z.eventId,scheduledFor:H});if(B)return{run:B,reason:"dedupe_window"}}}let X=$.dedupeWindowSeconds??0;if(X>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:IV(Q,X)}))return{reason:"dedupe_window"};let Y=$.cooldownSeconds??0;if(Y>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:IV(Q,Y)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:Z.eventId,scheduledFor:J>0?kV(Q,J):Q}),reason:"dedupe_window"}}}class d8{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},Z=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of Z)if(this.materializeOneOff(W))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of Q)try{if(this.materializeSchedule(W))$.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 nO}from"node:path";import{buildClineSystemPrompt as aO}from"@cline/shared";import{nowIso as vV}from"@cline/shared/db";import{basename as mO,resolve as vO}from"node:path";import{performance as xV}from"node:perf_hooks";import{processWorkspaceInfo as gV}from"@cline/shared";import cO from"simple-git";function b$($){return vO($)}async function U5($){return(await K7($)).info}function f5($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function K7($){let Z=b$($),Q={rootPath:Z,hint:mO(Z)},W;try{let J=cO({baseDir:Z});if(!await J.checkIsRepo())return{info:Q,vcsType:"none"};try{let Y=await J.getRemotes(!0);if(Y.length>0){let j=Y.map((V)=>{let H=V.refs.fetch||V.refs.push;return`${V.name}: ${H}`});Q.associatedRemoteUrls=j}}catch(Y){W??=f5(Y)}try{let Y=(await J.revparse(["HEAD"])).trim();if(Y.length>0)Q.latestGitCommitHash=Y}catch(Y){W??=f5(Y)}try{let Y=(await J.branch()).current.trim();if(Y.length>0)Q.latestGitBranchName=Y}catch(Y){W??=f5(Y)}return{info:Q,vcsType:"git",error:W}}catch(J){return{info:Q,vcsType:"none",error:f5(J)}}}async function F7($){let Z=await U5($);return gV(Z)}async function mV($){let Z=xV.now(),Q=await K7($),W=xV.now()-Z,J=Q.info;return{workspaceInfo:J,workspaceMetadata:gV(J),durationMs:W,vcsType:Q.vcsType,initError:Q.error}}import{mkdirSync as uO,writeFileSync as dO}from"node:fs";import{join as lO}from"node:path";import{resolveCronReportsDir as pO}from"@cline/shared/storage";function p1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function y$($,Z){if(Z===void 0||Z===null)return;return`${$}: ${p1(Z)}`}function rO($,Z,Q){let W=[`runId: ${p1($.runId)}`,`specId: ${p1(Z.specId)}`,`externalId: ${p1(Z.externalId)}`,`title: ${p1(Z.title)}`,`triggerKind: ${p1($.triggerKind)}`,`status: ${p1($.status)}`,`sourcePath: ${p1(Z.sourcePath)}`],J=[y$("sessionId",$.sessionId),y$("startedAt",$.startedAt),y$("completedAt",$.completedAt),y$("triggerEventId",$.triggerEventId),y$("triggerEventType",Q?.eventType),y$("triggerEventSource",Q?.source),y$("triggerEventSubject",Q?.subject)];for(let X of J)if(X)W.push(X);return`---
184
184
  ${W.join(`
185
185
  `)}
186
186
  ---
187
- `}function dO($){let Z=[];if($.triggerEvent){let Q=$.triggerEvent,W=[`- eventId: ${Q.eventId}`,`- eventType: ${Q.eventType}`,`- source: ${Q.source}`,Q.subject?`- subject: ${Q.subject}`:"",`- occurredAt: ${Q.occurredAt}`,Q.dedupeKey?`- dedupeKey: ${Q.dedupeKey}`:"",Q.attributes?`- attributes: ${JSON.stringify(Q.attributes)}`:""].filter((J)=>J.length>0);Z.push(`## Trigger Event
187
+ `}function iO($){let Z=[];if($.triggerEvent){let Q=$.triggerEvent,W=[`- eventId: ${Q.eventId}`,`- eventType: ${Q.eventType}`,`- source: ${Q.source}`,Q.subject?`- subject: ${Q.subject}`:"",`- occurredAt: ${Q.occurredAt}`,Q.dedupeKey?`- dedupeKey: ${Q.dedupeKey}`:"",Q.attributes?`- attributes: ${JSON.stringify(Q.attributes)}`:""].filter((J)=>J.length>0);Z.push(`## Trigger Event
188
188
 
189
189
  ${W.join(`
190
190
  `)}
@@ -203,17 +203,17 @@ ${W.join(`
203
203
  ${Q.join(`
204
204
  `)}
205
205
  `)}return Z.join(`
206
- `)}function A7($){let Z=cO($.specs);gO(Z,{recursive:!0});let Q=vO(Z,`${$.run.runId}.md`),W=`${uO($.run,$.spec,$.data.triggerEvent)}
207
- ${dO($.data)}`;return mO(Q,W,"utf8"),Q}class f7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,Z,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(Q)),J=this.activeExecutions.get($)??new Set;if(J.size>=W)return!1;return J.add(Z),this.activeExecutions.set($,J),!0}release($,Z){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(Z),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let Z of this.activeExecutions.values())$+=Z.size;return $}}var rO=15000,iO=90,cV=["rules","skills","plugins"];function nO($,Z){return new Set($.extensions??cV).has(Z)}function aO($,Z){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)Q[W]={enabled:!0,autoApprove:!0};if(Z==="yolo")Q[D0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function sO($){let Z=$?.trim();if(!Z)return;return["# Notes Directory",`Use ${Z} 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(`
208
- `)}class U7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function oO($,Z){if(Z<=0)return $;let Q,W=new Promise((J,X)=>{Q=setTimeout(()=>{X(new U7("cron run timed out"))},Z)});try{return await Promise.race([$,W])}finally{if(Q)clearTimeout(Q)}}class l8{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 f7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??iO)*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??rO);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 Z=[...this.activeRuns.entries()];await Promise.all(Z.map(async([Q,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:W.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:vV(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((Z)=>this.executeClaim(Z)))}catch($){let Z=this.options.logger;if(Z)if(Z.error)Z.error("cron.runner.tick.failed",{error:$});else Z.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,Z])=>{let Q=this.store.getRun($);return Q?[{...Q,...Z}]:[]})}async executeClaim($){let Z=$.run,Q=this.store.getSpec(Z.specId);if(!Q){this.store.completeRun(Z.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(Z.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,Z.runId,W)){this.store.requeueRun({runId:Z.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,Z.runId),this.store.requeueRun({runId:Z.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(Z.runId,{claimToken:$.claimToken});let X=Z.triggerEventId?this.store.getEventLog(Z.triggerEventId):void 0,Y,j,V=Date.now(),H;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)H=V+Q.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat($);let B=await this.buildStartRequest(Q);if(Y=(await this.options.runtimeHandlers.startSession(B)).sessionId.trim(),!Y)throw Error("runtime returned empty sessionId");this.activeRuns.set(Z.runId,{claimToken:$.claimToken,sessionId:Y}),this.store.attachSessionIdToRun(Z.runId,Y);let K={config:B,prompt:this.buildPrompt(Q,X)},F=this.options.runtimeHandlers.sendSession(Y,K),A=H?Math.max(1,H-Date.now()):0,f=(await oO(F,A)).result,D=Date.now(),U=A7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...Z,sessionId:Y,status:"done"},spec:Q,data:{finalText:f.text,usage:f.usage,toolCalls:f.toolCalls,durationMs:D-V,triggerEvent:X}});this.store.completeRun(Z.runId,{status:"done",sessionId:Y,reportPath:U,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,Z.runId),this.store.updateSpecLastRunAt(Q.specId,vV())}catch(B){let G=B instanceof U7;if(Y&&G)try{await this.options.runtimeHandlers.abortSession(Y)}catch{}let K=B instanceof Error?B.message:String(B),F=Date.now(),A=A7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...Z,sessionId:Y,status:"failed"},spec:Q,data:{error:K,durationMs:F-V,triggerEvent:X}});this.store.completeRun(Z.runId,{status:"failed",sessionId:Y,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,Z.runId)}finally{if(j?.(),Y)try{await this.options.runtimeHandlers.stopSession(Y)}catch{}this.activeRuns.delete(Z.runId),this.limiter.release(Q.specId,Z.runId)}}publishScheduleExecutionEvent($,Z,Q){if(Z.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(Q);if(!W)return;let J=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:Z.externalId,executionId:W.runId,sessionId:W.sessionId,triggeredAt:new Date(W.scheduledFor??W.createdAt).getTime(),startedAt:W.startedAt?new Date(W.startedAt).getTime():void 0,endedAt:W.completedAt?new Date(W.completedAt).getTime():void 0,status:J,errorMessage:W.error})}buildPrompt($,Z){let Q=$.prompt??"";if(!Z)return Q;let W={eventId:Z.eventId,eventType:Z.eventType,source:Z.source,subject:Z.subject,occurredAt:Z.occurredAt,workspaceRoot:Z.workspaceRoot,dedupeKey:Z.dedupeKey,attributes:Z.attributes,payload:Z.payload};return`${Q}
206
+ `)}function A7($){let Z=pO($.specs);uO(Z,{recursive:!0});let Q=lO(Z,`${$.run.runId}.md`),W=`${rO($.run,$.spec,$.data.triggerEvent)}
207
+ ${iO($.data)}`;return dO(Q,W,"utf8"),Q}class f7{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,Z,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(Q)),J=this.activeExecutions.get($)??new Set;if(J.size>=W)return!1;return J.add(Z),this.activeExecutions.set($,J),!0}release($,Z){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(Z),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let Z of this.activeExecutions.values())$+=Z.size;return $}}var sO=15000,oO=90,cV=["rules","skills","plugins"];function tO($,Z){return new Set($.extensions??cV).has(Z)}function eO($,Z){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)Q[W]={enabled:!0,autoApprove:!0};if(Z==="yolo")Q[L0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function $q($){let Z=$?.trim();if(!Z)return;return["# Notes Directory",`Use ${Z} 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(`
208
+ `)}class U7 extends Error{constructor($){super($);this.name="TimeoutError"}}async function Zq($,Z){if(Z<=0)return $;let Q,W=new Promise((J,X)=>{Q=setTimeout(()=>{X(new U7("cron run timed out"))},Z)});try{return await Promise.race([$,W])}finally{if(Q)clearTimeout(Q)}}class l8{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 f7($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??oO)*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??sO);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 Z=[...this.activeRuns.entries()];await Promise.all(Z.map(async([Q,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:W.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:vV(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((Z)=>this.executeClaim(Z)))}catch($){let Z=this.options.logger;if(Z)if(Z.error)Z.error("cron.runner.tick.failed",{error:$});else Z.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,Z])=>{let Q=this.store.getRun($);return Q?[{...Q,...Z}]:[]})}async executeClaim($){let Z=$.run,Q=this.store.getSpec(Z.specId);if(!Q){this.store.completeRun(Z.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(Z.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,Z.runId,W)){this.store.requeueRun({runId:Z.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,Z.runId),this.store.requeueRun({runId:Z.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(Z.runId,{claimToken:$.claimToken});let X=Z.triggerEventId?this.store.getEventLog(Z.triggerEventId):void 0,Y,j,V=Date.now(),H;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)H=V+Q.timeoutSeconds*1000;try{j=this.startClaimLeaseHeartbeat($);let B=await this.buildStartRequest(Q);if(Y=(await this.options.runtimeHandlers.startSession(B)).sessionId.trim(),!Y)throw Error("runtime returned empty sessionId");this.activeRuns.set(Z.runId,{claimToken:$.claimToken,sessionId:Y}),this.store.attachSessionIdToRun(Z.runId,Y);let K={config:B,prompt:this.buildPrompt(Q,X)},F=this.options.runtimeHandlers.sendSession(Y,K),A=H?Math.max(1,H-Date.now()):0,f=(await Zq(F,A)).result,D=Date.now(),U=A7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...Z,sessionId:Y,status:"done"},spec:Q,data:{finalText:f.text,usage:f.usage,toolCalls:f.toolCalls,durationMs:D-V,triggerEvent:X}});this.store.completeRun(Z.runId,{status:"done",sessionId:Y,reportPath:U,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,Z.runId),this.store.updateSpecLastRunAt(Q.specId,vV())}catch(B){let G=B instanceof U7;if(Y&&G)try{await this.options.runtimeHandlers.abortSession(Y)}catch{}let K=B instanceof Error?B.message:String(B),F=Date.now(),A=A7({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...Z,sessionId:Y,status:"failed"},spec:Q,data:{error:K,durationMs:F-V,triggerEvent:X}});this.store.completeRun(Z.runId,{status:"failed",sessionId:Y,reportPath:A,error:K,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,Z.runId)}finally{if(j?.(),Y)try{await this.options.runtimeHandlers.stopSession(Y)}catch{}this.activeRuns.delete(Z.runId),this.limiter.release(Q.specId,Z.runId)}}publishScheduleExecutionEvent($,Z,Q){if(Z.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(Q);if(!W)return;let J=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:Z.externalId,executionId:W.runId,sessionId:W.sessionId,triggeredAt:new Date(W.scheduledFor??W.createdAt).getTime(),startedAt:W.startedAt?new Date(W.startedAt).getTime():void 0,endedAt:W.completedAt?new Date(W.completedAt).getTime():void 0,status:J,errorMessage:W.error})}buildPrompt($,Z){let Q=$.prompt??"";if(!Z)return Q;let W={eventId:Z.eventId,eventType:Z.eventType,source:Z.source,subject:Z.subject,occurredAt:Z.occurredAt,workspaceRoot:Z.workspaceRoot,dedupeKey:Z.dedupeKey,attributes:Z.attributes,payload:Z.payload};return`${Q}
209
209
 
210
210
  Trigger event:
211
- ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let Z=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(Q)},Z);return()=>clearInterval(Q)}async buildSystemPrompt($,Z,Q,W){let J=sO($.notesDirectory),X=R6(void 0,J),Y=await F7(Z),j=pO({ide:"Cline Cron",workspaceRoot:Z,workspaceName:lO(Z),metadata:Y,rules:$.systemPrompt?void 0:X,mode:Q,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?R6(j,X)??j:j}async buildStartRequest($){let Z=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),W=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,X=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():Z;if(!Z)throw Error("cron spec requires workspaceRoot");let Y=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:Z,cwd:X,provider:Q,model:W,mode:Y,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,Z,Y,Q),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:aO($,Y),configExtensions:cV.filter((j)=>nO($,j))}}}import{existsSync as zq,readdirSync as Tq,readFileSync as Oq,statSync as qq}from"node:fs";import{relative as Mq}from"node:path";import{resolveCronSpecsDir as Rq}from"@cline/shared/storage";function p8($,Z,Q,W){let J=new Set;function X(Y){let j=Y.toLowerCase();if(W){let H=W.indexOf(j);if(H!==-1)return H+Z}let V=Number(Y);if(!Number.isInteger(V)||V<Z||V>Q)throw Error(`Invalid cron value "${Y}" for range [${Z}-${Q}]`);return V}for(let Y of $.split(",")){if(Y==="*"){for(let H=Z;H<=Q;H+=1)J.add(H);continue}let j=Y.indexOf("/");if(j!==-1){let H=Y.slice(0,j),B=Number(Y.slice(j+1));if(!Number.isInteger(B)||B<1)throw Error(`Invalid step "${Y.slice(j+1)}"`);let G=Z,K=Q;if(H!=="*"){let F=H.indexOf("-");if(F!==-1)G=X(H.slice(0,F)),K=X(H.slice(F+1));else G=X(H)}if(G>K)throw Error(`Invalid cron range "${H}"`);for(let F=G;F<=K;F+=B)J.add(F);continue}let V=Y.indexOf("-");if(V!==-1){let H=X(Y.slice(0,V)),B=X(Y.slice(V+1));if(H>B)throw Error(`Invalid cron range "${Y}"`);for(let G=H;G<=B;G+=1)J.add(G);continue}J.add(X(Y))}return[...J].sort((Y,j)=>Y-j)}var tO=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dV=["sun","mon","tue","wed","thu","fri","sat"];function r8($,Z,Q){let W=$[Z];if(typeof W!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${Z+1}`);return W}function D7($,Z){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${Z}`);return Q}function L7($){let Z=$.trim().split(/\s+/);if(Z.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${Z.length}`);return{minutes:p8(r8(Z,0,$),0,59),hours:p8(r8(Z,1,$),0,23),daysOfMonth:p8(r8(Z,2,$),1,31),months:p8(r8(Z,3,$),1,12,tO),daysOfWeek:p8(r8(Z,4,$),0,6,dV)}}function _7($){L7($)}function lV($,Z,Q=Date.now()){y$($,Q,Z)}var uV=new Map,eO=new Map(dV.map(($,Z)=>[$,Z]));function pV($){let Z=$?.trim();return Z?Z:void 0}function rV($){let Z=uV.get($);if(Z)return Z;let Q=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 uV.set($,Q),Q}function $q($){let Z=pV($);if(!Z)return;rV(Z).format(new Date)}function Zq($,Z){let Q=rV(Z).formatToParts(new Date($)),W=new Map(Q.map((Y)=>[Y.type,Y.value])),J=W.get("weekday")?.toLowerCase().slice(0,3)??"",X=eO.get(J);if(X===void 0)throw Error(`Unable to resolve weekday for timezone "${Z}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:X,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function Qq($){let Z=new Date($);return{month:Z.getMonth()+1,dayOfMonth:Z.getDate(),dayOfWeek:Z.getDay(),hour:Z.getHours(),minute:Z.getMinutes()}}function Wq($,Z){return $.months.includes(Z.month)&&$.daysOfMonth.includes(Z.dayOfMonth)&&$.daysOfWeek.includes(Z.dayOfWeek)&&$.hours.includes(Z.hour)&&$.minutes.includes(Z.minute)}function Jq($,Z,Q){let W=L7($),J=new Date(Z);J.setSeconds(0,0);let X=J.getTime()+60000,Y=new Date(Z);Y.setFullYear(Y.getFullYear()+4);let j=Y.getTime();while(X<=j){if(Wq(W,Zq(X,Q)))return X;X+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function y$($,Z,Q){let W=pV(Q);if(W)return $q(W),Jq($,Z,W);let J=L7($),X=new Date(Z);X.setSeconds(0,0),X=new Date(X.getTime()+60000);let Y=new Date(Z);Y.setFullYear(Y.getFullYear()+4);while(X<=Y){let{month:j,dayOfMonth:V,dayOfWeek:H,hour:B,minute:G}=Qq(X.getTime());if(!J.months.includes(j)){let K=J.months.find((A)=>A>j)??D7(J.months,"months"),F=K<=j?1:0;X=new Date(X.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(H)){X=new Date(X.getFullYear(),X.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(B)){let K=J.hours.find((A)=>A>B)??D7(J.hours,"hours"),F=K<=B?1:0;X=new Date(X.getFullYear(),X.getMonth(),X.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??D7(J.minutes,"minutes"),F=K<=G?1:0;X=new Date(X.getFullYear(),X.getMonth(),X.getDate(),X.getHours()+F,K,0,0);continue}return X.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as Xq}from"node:crypto";import Yq from"yaml";function jq($){let Z=$.replace(/\\/g,"/");if(Z.startsWith("events/")&&Z.endsWith(".event.md"))return"event";if(Z.endsWith(".cron.md"))return"schedule";return"one_off"}function Vq($){let Z=$.replace(/\r\n/g,`
211
+ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let Z=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(Q)},Z);return()=>clearInterval(Q)}async buildSystemPrompt($,Z,Q,W){let J=$q($.notesDirectory),X=R6(void 0,J),Y=await F7(Z),j=aO({ide:"Cline Cron",workspaceRoot:Z,workspaceName:nO(Z),metadata:Y,rules:$.systemPrompt?void 0:X,mode:Q,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?R6(j,X)??j:j}async buildStartRequest($){let Z=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),W=($.modelId??"").trim(),J=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,X=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():Z;if(!Z)throw Error("cron spec requires workspaceRoot");let Y=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:Z,cwd:X,provider:Q,model:W,mode:Y,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,Z,Y,Q),maxIterations:$.maxIterations,enableTools:J?.enableTools??!0,enableSpawn:J?.enableSpawn??!0,enableTeams:J?.enableTeams??!0,autoApproveTools:J?.autoApproveTools??!0,toolPolicies:eO($,Y),configExtensions:cV.filter((j)=>tO($,j))}}}import{existsSync as Mq,readdirSync as Rq,readFileSync as Eq,statSync as Nq}from"node:fs";import{relative as wq}from"node:path";import{resolveCronSpecsDir as Cq}from"@cline/shared/storage";function p8($,Z,Q,W){let J=new Set;function X(Y){let j=Y.toLowerCase();if(W){let H=W.indexOf(j);if(H!==-1)return H+Z}let V=Number(Y);if(!Number.isInteger(V)||V<Z||V>Q)throw Error(`Invalid cron value "${Y}" for range [${Z}-${Q}]`);return V}for(let Y of $.split(",")){if(Y==="*"){for(let H=Z;H<=Q;H+=1)J.add(H);continue}let j=Y.indexOf("/");if(j!==-1){let H=Y.slice(0,j),B=Number(Y.slice(j+1));if(!Number.isInteger(B)||B<1)throw Error(`Invalid step "${Y.slice(j+1)}"`);let G=Z,K=Q;if(H!=="*"){let F=H.indexOf("-");if(F!==-1)G=X(H.slice(0,F)),K=X(H.slice(F+1));else G=X(H)}if(G>K)throw Error(`Invalid cron range "${H}"`);for(let F=G;F<=K;F+=B)J.add(F);continue}let V=Y.indexOf("-");if(V!==-1){let H=X(Y.slice(0,V)),B=X(Y.slice(V+1));if(H>B)throw Error(`Invalid cron range "${Y}"`);for(let G=H;G<=B;G+=1)J.add(G);continue}J.add(X(Y))}return[...J].sort((Y,j)=>Y-j)}var Qq=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],dV=["sun","mon","tue","wed","thu","fri","sat"];function r8($,Z,Q){let W=$[Z];if(typeof W!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${Z+1}`);return W}function D7($,Z){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${Z}`);return Q}function L7($){let Z=$.trim().split(/\s+/);if(Z.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${Z.length}`);return{minutes:p8(r8(Z,0,$),0,59),hours:p8(r8(Z,1,$),0,23),daysOfMonth:p8(r8(Z,2,$),1,31),months:p8(r8(Z,3,$),1,12,Qq),daysOfWeek:p8(r8(Z,4,$),0,6,dV)}}function _7($){L7($)}function lV($,Z,Q=Date.now()){h$($,Q,Z)}var uV=new Map,Wq=new Map(dV.map(($,Z)=>[$,Z]));function pV($){let Z=$?.trim();return Z?Z:void 0}function rV($){let Z=uV.get($);if(Z)return Z;let Q=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 uV.set($,Q),Q}function Jq($){let Z=pV($);if(!Z)return;rV(Z).format(new Date)}function Xq($,Z){let Q=rV(Z).formatToParts(new Date($)),W=new Map(Q.map((Y)=>[Y.type,Y.value])),J=W.get("weekday")?.toLowerCase().slice(0,3)??"",X=Wq.get(J);if(X===void 0)throw Error(`Unable to resolve weekday for timezone "${Z}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:X,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function Yq($){let Z=new Date($);return{month:Z.getMonth()+1,dayOfMonth:Z.getDate(),dayOfWeek:Z.getDay(),hour:Z.getHours(),minute:Z.getMinutes()}}function jq($,Z){return $.months.includes(Z.month)&&$.daysOfMonth.includes(Z.dayOfMonth)&&$.daysOfWeek.includes(Z.dayOfWeek)&&$.hours.includes(Z.hour)&&$.minutes.includes(Z.minute)}function Vq($,Z,Q){let W=L7($),J=new Date(Z);J.setSeconds(0,0);let X=J.getTime()+60000,Y=new Date(Z);Y.setFullYear(Y.getFullYear()+4);let j=Y.getTime();while(X<=j){if(jq(W,Xq(X,Q)))return X;X+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function h$($,Z,Q){let W=pV(Q);if(W)return Jq(W),Vq($,Z,W);let J=L7($),X=new Date(Z);X.setSeconds(0,0),X=new Date(X.getTime()+60000);let Y=new Date(Z);Y.setFullYear(Y.getFullYear()+4);while(X<=Y){let{month:j,dayOfMonth:V,dayOfWeek:H,hour:B,minute:G}=Yq(X.getTime());if(!J.months.includes(j)){let K=J.months.find((A)=>A>j)??D7(J.months,"months"),F=K<=j?1:0;X=new Date(X.getFullYear()+F,K-1,1,0,0,0,0);continue}if(!J.daysOfMonth.includes(V)||!J.daysOfWeek.includes(H)){X=new Date(X.getFullYear(),X.getMonth(),V+1,0,0,0,0);continue}if(!J.hours.includes(B)){let K=J.hours.find((A)=>A>B)??D7(J.hours,"hours"),F=K<=B?1:0;X=new Date(X.getFullYear(),X.getMonth(),X.getDate()+F,K,0,0,0);continue}if(!J.minutes.includes(G)){let K=J.minutes.find((A)=>A>G)??D7(J.minutes,"minutes"),F=K<=G?1:0;X=new Date(X.getFullYear(),X.getMonth(),X.getDate(),X.getHours()+F,K,0,0);continue}return X.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as Hq}from"node:crypto";import Bq from"yaml";function Gq($){let Z=$.replace(/\\/g,"/");if(Z.startsWith("events/")&&Z.endsWith(".event.md"))return"event";if(Z.endsWith(".cron.md"))return"schedule";return"one_off"}function Kq($){let Z=$.replace(/\r\n/g,`
212
212
  `);if(!Z.startsWith(`---
213
213
  `))return{frontmatter:void 0,body:$};let Q=Z.slice(4),W=Q.indexOf(`
214
214
  ---`);if(W===-1)return{frontmatter:void 0,body:$};let J=Q.slice(0,W),X=Q.slice(W+4);if(X.startsWith(`
215
- `))X=X.slice(1);return{frontmatter:J,body:X}}function I0($){if(typeof $!=="string")return;let Z=$.trim();return Z.length>0?Z:void 0}function Hq($){if(!Array.isArray($))return;let Z=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return Z.length>0?Z:void 0}function O7($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function Bq($){let Z=O7($);if(!Z)return;let Q=I0(Z.providerId),W=I0(Z.modelId);if(Q===void 0&&W===void 0)return;return{providerId:Q,modelId:W}}function Gq($){if(typeof $!=="string")return;let Z=$.trim().toLowerCase();if(Z==="act"||Z==="plan"||Z==="yolo")return Z;return}function nV($,Z={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let W=[...new Set(Q.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&Z.preserveEmptyArray)return W;return W.length>0?W:void 0}var Kq=new Set(U2);function Fq($){let Z=nV($,{preserveEmptyArray:!0});if(!Z)return;let Q=Z.filter((W)=>!Kq.has(W));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return Z}var Aq=new Set(["rules","skills","plugins"]);function fq($){let Z=nV($,{preserveEmptyArray:!0});if(!Z)return;let Q=Z.filter((W)=>!Aq.has(W));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return Z}function z7($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function T7($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function q7($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>q7(Q)).join(",")}]`;let Z=Object.entries($).filter(([,Q])=>Q!==void 0);return Z.sort(([Q],[W])=>Q<W?-1:Q>W?1:0),`{${Z.map(([Q,W])=>`${JSON.stringify(Q)}:${q7(W)}`).join(",")}}`}function aV($,Z){let Q=Xq("sha256");return Q.update(q7($)),Q.update(`
216
- `),Q.update(Z),Q.digest("hex")}function Uq($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var Dq=["schedule","timezone"],Lq=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],_q=["cwd"];function iV($,Z,Q,W,J){return{externalId:$,relativePath:$,triggerKind:Z,body:Q,contentHash:aV(W,Q),error:J}}function Z1($,Z,Q,W,J,X){return{externalId:$,relativePath:Z,triggerKind:Q,body:W,contentHash:J,error:X}}function sV($){let Z=$.relativePath.replace(/\\/g,"/"),Q=jq(Z),{frontmatter:W,body:J}=Vq($.raw),X={};if(W!==void 0&&W.trim().length>0)try{let U=Yq.parse(W);if(U&&typeof U==="object"&&!Array.isArray(U))X=U;else if(U!==null&&U!==void 0)return iV(Z,Q,J,{},"frontmatter must be a YAML mapping")}catch(U){return iV(Z,Q,J,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let Y=aV(X,J),j=I0(X.id),V=j??Z;if(Q!=="schedule"){for(let U of Dq)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of _q)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let U of Lq)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is only allowed on .event.md specs`)}let H=I0(X.prompt),B=J.trim(),G=H??(B.length>0?B:void 0);if(!G)return Z1(V,Z,Q,J,Y,"prompt is required (frontmatter `prompt` or markdown body)");let K=I0(X.workspaceRoot);if(!K)return Z1(V,Z,Q,J,Y,"workspaceRoot is required");let F,A;try{F=Fq(X.tools),A=fq(X.extensions)}catch(U){return Z1(V,Z,Q,J,Y,U instanceof Error?U.message:String(U))}let L=Gq(X.mode);if(X.mode!==void 0&&L===void 0)return Z1(V,Z,Q,J,Y,"mode must be one of: act, plan, yolo");let f={id:j,title:I0(X.title)??j??Uq(Z),prompt:G,workspaceRoot:K,mode:L??"yolo",systemPrompt:I0(X.systemPrompt),modelSelection:Bq(X.modelSelection),maxIterations:z7(X.maxIterations),timeoutSeconds:z7(X.timeoutSeconds),tools:F,notesDirectory:I0(X.notesDirectory),extensions:A,source:I0(X.source)??"user",tags:Hq(X.tags),enabled:typeof X.enabled==="boolean"?X.enabled:!0,metadata:O7(X.metadata)},D;if(Q==="schedule"){let U=I0(X.schedule);if(!U)return Z1(V,Z,Q,J,Y,"schedule is required for *.cron.md specs");let T=I0(X.timezone);try{lV(U,T)}catch(z){return Z1(V,Z,Q,J,Y,z instanceof Error?z.message:String(z))}D={...f,triggerKind:"schedule",schedule:U,timezone:T}}else if(Q==="event"){let U=I0(X.event);if(!U)return Z1(V,Z,Q,J,Y,"event is required for .event.md specs");D={...f,triggerKind:"event",event:U,filters:O7(X.filters),debounceSeconds:T7(X.debounceSeconds),dedupeWindowSeconds:T7(X.dedupeWindowSeconds),cooldownSeconds:T7(X.cooldownSeconds),maxParallel:z7(X.maxParallel)}}else D={...f,triggerKind:"one_off"};return{externalId:V,relativePath:Z,triggerKind:Q,body:J,contentHash:Y,spec:D}}function Eq($,Z){return Mq($,Z).replace(/\\/g,"/")}function Nq($){if(!zq($))return[];let Z=[],Q=[$];while(Q.length>0){let W=Q.pop();if(!W)continue;let J;try{J=Tq(W,{withFileTypes:!0})}catch{continue}for(let X of J){let Y=`${W}/${X.name}`;if(X.isDirectory()){if(X.name==="reports")continue;Q.push(Y);continue}if(!X.isFile())continue;if(!X.name.endsWith(".md"))continue;Z.push(Y)}}return Z}class M7{store;cronDir;constructor($){this.store=$.store,this.cronDir=Rq($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},Z=Nq(this.cronDir),Q=new Set;for(let J of Z){let X=Eq(this.cronDir,J);Q.add(X),$.scanned+=1;let Y=await this.reconcileFile(X,J);if(Y){if($.changes.push(Y),$.upserted+=1,Y.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of W)if(!Q.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,Z){let Q=this.store.getSpecBySourcePath($),W,J;try{W=Oq(Z,"utf8"),J=qq(Z).mtimeMs}catch{return}let Y=sV({relativePath:$,raw:W}),j=this.store.upsertSpec({externalId:Y.externalId,sourcePath:$,triggerKind:Y.triggerKind,sourceMtimeMs:J,sourceHash:Y.contentHash,parseStatus:Y.error?"invalid":"valid",parseError:Y.error,spec:Y.spec});if(!Y.error&&Y.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==j.record.scheduleExpr||Q.timezone!==j.record.timezone});return{relativePath:$,result:j,parse:Y}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of $)this.applyScheduleNextRunAt(Z,{forceReset:!1})}applyScheduleNextRunAt($,Z){if(!$.scheduleExpr)return;if(!Z.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),W=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,J=y$($.scheduleExpr,W,$.timezone),X=new Date(J).toISOString();if($.nextRunAt!==X)this.store.updateSpecNextRunAt($.specId,X)}catch{}}}import{existsSync as wq,mkdirSync as Cq,watch as Pq}from"node:fs";import{relative as Sq,resolve as bq}from"node:path";var yq=250;class R7{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??yq),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{Cq($,{recursive:!0}),this.watcher=Pq($,{recursive:!0},(Z,Q)=>{if(!Q)return;let W=String(Q).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(Z){this.onError(Z)}}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 Z=this.pending.get($);if(Z)clearTimeout(Z);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let Z=bq(this.reconciler.getCronDir(),$);if(!wq(Z)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=Sq(this.reconciler.getCronDir(),Z).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,Z),await this.onReconciled()}catch(Z){this.onError(Z)}}}import{randomUUID as i8}from"node:crypto";import{asOptionalString as k,asString as s,loadSqliteDb as kq,nowIso as F0}from"@cline/shared/db";import{resolveCronDbPath as Iq}from"@cline/shared/storage";var hq=[`CREATE TABLE IF NOT EXISTS cron_specs (
215
+ `))X=X.slice(1);return{frontmatter:J,body:X}}function I0($){if(typeof $!=="string")return;let Z=$.trim();return Z.length>0?Z:void 0}function Fq($){if(!Array.isArray($))return;let Z=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return Z.length>0?Z:void 0}function O7($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function Aq($){let Z=O7($);if(!Z)return;let Q=I0(Z.providerId),W=I0(Z.modelId);if(Q===void 0&&W===void 0)return;return{providerId:Q,modelId:W}}function fq($){if(typeof $!=="string")return;let Z=$.trim().toLowerCase();if(Z==="act"||Z==="plan"||Z==="yolo")return Z;return}function nV($,Z={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let W=[...new Set(Q.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0))];if(Array.isArray($)&&Z.preserveEmptyArray)return W;return W.length>0?W:void 0}var Uq=new Set(U2);function Dq($){let Z=nV($,{preserveEmptyArray:!0});if(!Z)return;let Q=Z.filter((W)=>!Uq.has(W));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return Z}var Lq=new Set(["rules","skills","plugins"]);function _q($){let Z=nV($,{preserveEmptyArray:!0});if(!Z)return;let Q=Z.filter((W)=>!Lq.has(W));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return Z}function z7($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function T7($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function q7($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>q7(Q)).join(",")}]`;let Z=Object.entries($).filter(([,Q])=>Q!==void 0);return Z.sort(([Q],[W])=>Q<W?-1:Q>W?1:0),`{${Z.map(([Q,W])=>`${JSON.stringify(Q)}:${q7(W)}`).join(",")}}`}function aV($,Z){let Q=Hq("sha256");return Q.update(q7($)),Q.update(`
216
+ `),Q.update(Z),Q.digest("hex")}function zq($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var Tq=["schedule","timezone"],Oq=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],qq=["cwd"];function iV($,Z,Q,W,J){return{externalId:$,relativePath:$,triggerKind:Z,body:Q,contentHash:aV(W,Q),error:J}}function Z1($,Z,Q,W,J,X){return{externalId:$,relativePath:Z,triggerKind:Q,body:W,contentHash:J,error:X}}function sV($){let Z=$.relativePath.replace(/\\/g,"/"),Q=Gq(Z),{frontmatter:W,body:J}=Kq($.raw),X={};if(W!==void 0&&W.trim().length>0)try{let U=Bq.parse(W);if(U&&typeof U==="object"&&!Array.isArray(U))X=U;else if(U!==null&&U!==void 0)return iV(Z,Q,J,{},"frontmatter must be a YAML mapping")}catch(U){return iV(Z,Q,J,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let Y=aV(X,J),j=I0(X.id),V=j??Z;if(Q!=="schedule"){for(let U of Tq)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of qq)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let U of Oq)if(X[U]!==void 0)return Z1(V,Z,Q,J,Y,`field "${U}" is only allowed on .event.md specs`)}let H=I0(X.prompt),B=J.trim(),G=H??(B.length>0?B:void 0);if(!G)return Z1(V,Z,Q,J,Y,"prompt is required (frontmatter `prompt` or markdown body)");let K=I0(X.workspaceRoot);if(!K)return Z1(V,Z,Q,J,Y,"workspaceRoot is required");let F,A;try{F=Dq(X.tools),A=_q(X.extensions)}catch(U){return Z1(V,Z,Q,J,Y,U instanceof Error?U.message:String(U))}let L=fq(X.mode);if(X.mode!==void 0&&L===void 0)return Z1(V,Z,Q,J,Y,"mode must be one of: act, plan, yolo");let f={id:j,title:I0(X.title)??j??zq(Z),prompt:G,workspaceRoot:K,mode:L??"yolo",systemPrompt:I0(X.systemPrompt),modelSelection:Aq(X.modelSelection),maxIterations:z7(X.maxIterations),timeoutSeconds:z7(X.timeoutSeconds),tools:F,notesDirectory:I0(X.notesDirectory),extensions:A,source:I0(X.source)??"user",tags:Fq(X.tags),enabled:typeof X.enabled==="boolean"?X.enabled:!0,metadata:O7(X.metadata)},D;if(Q==="schedule"){let U=I0(X.schedule);if(!U)return Z1(V,Z,Q,J,Y,"schedule is required for *.cron.md specs");let T=I0(X.timezone);try{lV(U,T)}catch(z){return Z1(V,Z,Q,J,Y,z instanceof Error?z.message:String(z))}D={...f,triggerKind:"schedule",schedule:U,timezone:T}}else if(Q==="event"){let U=I0(X.event);if(!U)return Z1(V,Z,Q,J,Y,"event is required for .event.md specs");D={...f,triggerKind:"event",event:U,filters:O7(X.filters),debounceSeconds:T7(X.debounceSeconds),dedupeWindowSeconds:T7(X.dedupeWindowSeconds),cooldownSeconds:T7(X.cooldownSeconds),maxParallel:z7(X.maxParallel)}}else D={...f,triggerKind:"one_off"};return{externalId:V,relativePath:Z,triggerKind:Q,body:J,contentHash:Y,spec:D}}function Pq($,Z){return wq($,Z).replace(/\\/g,"/")}function Sq($){if(!Mq($))return[];let Z=[],Q=[$];while(Q.length>0){let W=Q.pop();if(!W)continue;let J;try{J=Rq(W,{withFileTypes:!0})}catch{continue}for(let X of J){let Y=`${W}/${X.name}`;if(X.isDirectory()){if(X.name==="reports")continue;Q.push(Y);continue}if(!X.isFile())continue;if(!X.name.endsWith(".md"))continue;Z.push(Y)}}return Z}class M7{store;cronDir;constructor($){this.store=$.store,this.cronDir=Cq($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},Z=Sq(this.cronDir),Q=new Set;for(let J of Z){let X=Pq(this.cronDir,J);Q.add(X),$.scanned+=1;let Y=await this.reconcileFile(X,J);if(Y){if($.changes.push(Y),$.upserted+=1,Y.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let J of W)if(!Q.has(J.sourcePath))this.handleFileDeleted(J),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,Z){let Q=this.store.getSpecBySourcePath($),W,J;try{W=Eq(Z,"utf8"),J=Nq(Z).mtimeMs}catch{return}let Y=sV({relativePath:$,raw:W}),j=this.store.upsertSpec({externalId:Y.externalId,sourcePath:$,triggerKind:Y.triggerKind,sourceMtimeMs:J,sourceHash:Y.contentHash,parseStatus:Y.error?"invalid":"valid",parseError:Y.error,spec:Y.spec});if(!Y.error&&Y.triggerKind==="schedule"&&j.record.enabled)this.applyScheduleNextRunAt(j.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==j.record.scheduleExpr||Q.timezone!==j.record.timezone});return{relativePath:$,result:j,parse:Y}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of $)this.applyScheduleNextRunAt(Z,{forceReset:!1})}applyScheduleNextRunAt($,Z){if(!$.scheduleExpr)return;if(!Z.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),W=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,J=h$($.scheduleExpr,W,$.timezone),X=new Date(J).toISOString();if($.nextRunAt!==X)this.store.updateSpecNextRunAt($.specId,X)}catch{}}}import{existsSync as bq,mkdirSync as yq,watch as hq}from"node:fs";import{relative as kq,resolve as Iq}from"node:path";var xq=250;class R7{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??xq),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{yq($,{recursive:!0}),this.watcher=hq($,{recursive:!0},(Z,Q)=>{if(!Q)return;let W=String(Q).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(Z){this.onError(Z)}}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 Z=this.pending.get($);if(Z)clearTimeout(Z);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let Z=Iq(this.reconciler.getCronDir(),$);if(!bq(Z)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=kq(this.reconciler.getCronDir(),Z).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,Z),await this.onReconciled()}catch(Z){this.onError(Z)}}}import{randomUUID as i8}from"node:crypto";import{asOptionalString as k,asString as s,loadSqliteDb as mq,nowIso as F0}from"@cline/shared/db";import{resolveCronDbPath as vq}from"@cline/shared/storage";var gq=[`CREATE TABLE IF NOT EXISTS cron_specs (
217
217
  spec_id TEXT PRIMARY KEY,
218
218
  external_id TEXT NOT NULL,
219
219
  source_path TEXT NOT NULL UNIQUE,
@@ -304,17 +304,17 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let Z=Math.max(1000,Mat
304
304
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
305
305
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
306
306
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
307
- ON cron_specs(source_path);`];function oV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let Z of hq)$.exec(Z)}function U5($){if(!$)return;try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function E7($,Z={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let W=Q.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(Z.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function h$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function r1($){return{specId:s($.spec_id),externalId:s($.external_id),sourcePath:s($.source_path),triggerKind:s($.trigger_kind),sourceMtimeMs:h$($.source_mtime_ms),sourceHash:k($.source_hash),parseStatus:s($.parse_status)==="invalid"?"invalid":"valid",parseError:k($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:s($.title),prompt:k($.prompt),workspaceRoot:k($.workspace_root),scheduleExpr:k($.schedule_expr),timezone:k($.timezone),eventType:k($.event_type),filters:U5(k($.filters_json)),debounceSeconds:h$($.debounce_seconds),dedupeWindowSeconds:h$($.dedupe_window_seconds),cooldownSeconds:h$($.cooldown_seconds),mode:k($.mode),systemPrompt:k($.system_prompt),providerId:k($.provider_id),modelId:k($.model_id),maxIterations:h$($.max_iterations),timeoutSeconds:h$($.timeout_seconds),maxParallel:h$($.max_parallel),tools:E7(k($.tools_json),{preserveEmpty:!0}),notesDirectory:k($.notes_directory),extensions:E7(k($.extensions_json),{preserveEmpty:!0}),source:k($.source),tags:E7(k($.tags_json)),metadata:U5(k($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:k($.last_materialized_run_id),lastRunAt:k($.last_run_at),nextRunAt:k($.next_run_at),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function N7($){return{runId:s($.run_id),specId:s($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:s($.trigger_kind),status:s($.status),claimToken:k($.claim_token),claimStartedAt:k($.claim_started_at),claimUntilAt:k($.claim_until_at),scheduledFor:k($.scheduled_for),triggerEventId:k($.trigger_event_id),startedAt:k($.started_at),completedAt:k($.completed_at),sessionId:k($.session_id),reportPath:k($.report_path),error:k($.error),attemptCount:Number($.attempt_count??0),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function tV($){return{eventId:s($.event_id),eventType:s($.event_type),source:s($.source),subject:k($.subject),occurredAt:s($.occurred_at),receivedAt:s($.received_at),workspaceRoot:k($.workspace_root),dedupeKey:k($.dedupe_key),payload:U5(k($.payload_json)),attributes:U5(k($.attributes_json)),processingStatus:s($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:k($.error),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function eV($){return $?JSON.stringify($):null}var xq=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function $H($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function gq($,Z,Q,W){for(let J of xq){let X=$[J],Y=Z[J];if($H(X)!==$H(Y))return!0}if(Q===!1&&W===!0)return!0;return!1}function mq($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function vq($){return`hub/schedules/${$}.cron.md`}function cq($){let Z={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(Z).length>0?Z:void 0}function w7($){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((Z)=>Z.trim().length>0),enabled:$.enabled!==!1,metadata:cq($)}}function ZH($){return JSON.stringify(w7($))}function uq($,Z){let Q=$.metadata?{...$.metadata}:{},W=Z.createdBy===null?void 0:Z.createdBy!==void 0?Z.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,J=Z.cwd!==void 0?Z.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,X=Z.runtimeOptions!==void 0?Z.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:Z.name??$.title,cronPattern:Z.cronPattern??$.scheduleExpr??"",prompt:Z.prompt??$.prompt??"",workspaceRoot:Z.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:Z.modelSelection!==void 0?Z.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:Z.enabled??$.enabled,mode:Z.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:Z.systemPrompt===null?void 0:Z.systemPrompt!==void 0?Z.systemPrompt:$.systemPrompt,maxIterations:Z.maxIterations===null?void 0:Z.maxIterations!==void 0?Z.maxIterations:$.maxIterations,timeoutSeconds:Z.timeoutSeconds===null?void 0:Z.timeoutSeconds!==void 0?Z.timeoutSeconds:$.timeoutSeconds,maxParallel:Z.maxParallel??$.maxParallel??1,createdBy:W,tags:Z.tags??$.tags,runtimeOptions:X,metadata:Z.metadata!==void 0?Z.metadata:Object.keys(Q).length>0?Q:void 0}}class n8{db;constructor($={}){let Z=$.dbPath??Iq();this.db=kq(Z),oV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return Z?r1(Z):void 0}getSpec($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return Z?r1(Z):void 0}getSpecByExternalId($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return Z?r1(Z):void 0}listSpecs($={}){let Z=[],Q=[];if($.triggerKind)Z.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")Z.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)Z.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)Z.push("removed = 0");let W=Z.length>0?`WHERE ${Z.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...Q,J).map((Y)=>r1(Y))}createHubSchedule($){let Z=`sched_${i8()}`,Q=this.upsertSpec({externalId:Z,sourcePath:vq(Z),triggerKind:"schedule",sourceHash:ZH($),parseStatus:"valid",spec:w7($)});this.initializeScheduleNextRun(Q.record.specId);let W=this.getSpec(Q.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let Z=this.db.prepare(`SELECT * FROM cron_specs
307
+ ON cron_specs(source_path);`];function oV($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let Z of gq)$.exec(Z)}function D5($){if(!$)return;try{let Z=JSON.parse($);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return}function E7($,Z={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let W=Q.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);if(Z.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function k$($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function r1($){return{specId:s($.spec_id),externalId:s($.external_id),sourcePath:s($.source_path),triggerKind:s($.trigger_kind),sourceMtimeMs:k$($.source_mtime_ms),sourceHash:k($.source_hash),parseStatus:s($.parse_status)==="invalid"?"invalid":"valid",parseError:k($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:s($.title),prompt:k($.prompt),workspaceRoot:k($.workspace_root),scheduleExpr:k($.schedule_expr),timezone:k($.timezone),eventType:k($.event_type),filters:D5(k($.filters_json)),debounceSeconds:k$($.debounce_seconds),dedupeWindowSeconds:k$($.dedupe_window_seconds),cooldownSeconds:k$($.cooldown_seconds),mode:k($.mode),systemPrompt:k($.system_prompt),providerId:k($.provider_id),modelId:k($.model_id),maxIterations:k$($.max_iterations),timeoutSeconds:k$($.timeout_seconds),maxParallel:k$($.max_parallel),tools:E7(k($.tools_json),{preserveEmpty:!0}),notesDirectory:k($.notes_directory),extensions:E7(k($.extensions_json),{preserveEmpty:!0}),source:k($.source),tags:E7(k($.tags_json)),metadata:D5(k($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:k($.last_materialized_run_id),lastRunAt:k($.last_run_at),nextRunAt:k($.next_run_at),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function N7($){return{runId:s($.run_id),specId:s($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:s($.trigger_kind),status:s($.status),claimToken:k($.claim_token),claimStartedAt:k($.claim_started_at),claimUntilAt:k($.claim_until_at),scheduledFor:k($.scheduled_for),triggerEventId:k($.trigger_event_id),startedAt:k($.started_at),completedAt:k($.completed_at),sessionId:k($.session_id),reportPath:k($.report_path),error:k($.error),attemptCount:Number($.attempt_count??0),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function tV($){return{eventId:s($.event_id),eventType:s($.event_type),source:s($.source),subject:k($.subject),occurredAt:s($.occurred_at),receivedAt:s($.received_at),workspaceRoot:k($.workspace_root),dedupeKey:k($.dedupe_key),payload:D5(k($.payload_json)),attributes:D5(k($.attributes_json)),processingStatus:s($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:k($.error),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function eV($){return $?JSON.stringify($):null}var cq=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function $H($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function uq($,Z,Q,W){for(let J of cq){let X=$[J],Y=Z[J];if($H(X)!==$H(Y))return!0}if(Q===!1&&W===!0)return!0;return!1}function dq($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function lq($){return`hub/schedules/${$}.cron.md`}function pq($){let Z={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(Z).length>0?Z:void 0}function w7($){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((Z)=>Z.trim().length>0),enabled:$.enabled!==!1,metadata:pq($)}}function ZH($){return JSON.stringify(w7($))}function rq($,Z){let Q=$.metadata?{...$.metadata}:{},W=Z.createdBy===null?void 0:Z.createdBy!==void 0?Z.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,J=Z.cwd!==void 0?Z.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,X=Z.runtimeOptions!==void 0?Z.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:Z.name??$.title,cronPattern:Z.cronPattern??$.scheduleExpr??"",prompt:Z.prompt??$.prompt??"",workspaceRoot:Z.workspaceRoot??$.workspaceRoot??"",cwd:J,modelSelection:Z.modelSelection!==void 0?Z.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:Z.enabled??$.enabled,mode:Z.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:Z.systemPrompt===null?void 0:Z.systemPrompt!==void 0?Z.systemPrompt:$.systemPrompt,maxIterations:Z.maxIterations===null?void 0:Z.maxIterations!==void 0?Z.maxIterations:$.maxIterations,timeoutSeconds:Z.timeoutSeconds===null?void 0:Z.timeoutSeconds!==void 0?Z.timeoutSeconds:$.timeoutSeconds,maxParallel:Z.maxParallel??$.maxParallel??1,createdBy:W,tags:Z.tags??$.tags,runtimeOptions:X,metadata:Z.metadata!==void 0?Z.metadata:Object.keys(Q).length>0?Q:void 0}}class n8{db;constructor($={}){let Z=$.dbPath??vq();this.db=mq(Z),oV(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return Z?r1(Z):void 0}getSpec($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return Z?r1(Z):void 0}getSpecByExternalId($){let Z=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return Z?r1(Z):void 0}listSpecs($={}){let Z=[],Q=[];if($.triggerKind)Z.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")Z.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)Z.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)Z.push("removed = 0");let W=Z.length>0?`WHERE ${Z.join(" AND ")}`:"",J=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...Q,J).map((Y)=>r1(Y))}createHubSchedule($){let Z=`sched_${i8()}`,Q=this.upsertSpec({externalId:Z,sourcePath:lq(Z),triggerKind:"schedule",sourceHash:ZH($),parseStatus:"valid",spec:w7($)});this.initializeScheduleNextRun(Q.record.specId);let W=this.getSpec(Q.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let Z=this.db.prepare(`SELECT * FROM cron_specs
308
308
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
309
309
  ORDER BY created_at ASC LIMIT 1`).get($);return Z?r1(Z):void 0}listHubSchedules($={}){let Z=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Q=[];if(typeof $.enabled==="boolean")Z.push("enabled = ?"),Q.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let X of $.tags)Z.push("tags_json LIKE ?"),Q.push(`%"${X.trim()}"%`);let W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
310
310
  WHERE ${Z.join(" AND ")}
311
- ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((X)=>r1(X))}updateHubSchedule($,Z){let Q=this.getHubSchedule($);if(!Q)return;let W=uq(Q,Z),J=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:ZH(W),parseStatus:"valid",spec:w7(W)});if(Z.cronPattern!==void 0||Z.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let Z=this.getHubSchedule($);if(!Z)return!1;return this.markSpecRemoved(Z.specId),this.cancelQueuedRunsForSpec(Z.specId),!0}enqueueHubScheduleRun($,Z="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:Z,scheduledFor:F0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
311
+ ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((X)=>r1(X))}updateHubSchedule($,Z){let Q=this.getHubSchedule($);if(!Q)return;let W=rq(Q,Z),J=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:ZH(W),parseStatus:"valid",spec:w7(W)});if(Z.cronPattern!==void 0||Z.enabled!==void 0)this.initializeScheduleNextRun(J.record.specId);return this.getSpec(J.record.specId)}deleteHubSchedule($){let Z=this.getHubSchedule($);if(!Z)return!1;return this.markSpecRemoved(Z.specId),this.cancelQueuedRunsForSpec(Z.specId),!0}enqueueHubScheduleRun($,Z="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:Z,scheduledFor:F0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
312
312
  WHERE trigger_kind = 'event'
313
313
  AND event_type = ?
314
314
  AND enabled = 1
315
315
  AND removed = 0
316
316
  AND parse_status = 'valid'
317
- ORDER BY created_at ASC`).all($).map((Q)=>r1(Q))}upsertSpec($){let Z=F0(),Q=this.getSpecBySourcePath($.sourcePath),W=$.spec,J={title:W?.title??Q?.title??mq($.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},X=$.parseStatus==="valid"&&(W?.enabled??!0);if(!Q){let B=`cspec_${i8()}`;this.insertSpecRow(B,$,J,X,Z);let G=this.getSpec(B);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let j=Q.sourceHash!==$.sourceHash&&gq(Q,J,Q.enabled,X),V=j?Q.revision+1:Q.revision;this.updateSpecRow(Q.specId,$,J,X,V,Z);let H=this.getSpec(Q.specId);if(!H)throw Error("failed to reload cron_spec after update");return{record:H,created:!1,revisionChanged:j}}insertSpecRow($,Z,Q,W,J){let X=Z.spec;this.db.prepare(`INSERT INTO cron_specs (
317
+ ORDER BY created_at ASC`).all($).map((Q)=>r1(Q))}upsertSpec($){let Z=F0(),Q=this.getSpecBySourcePath($.sourcePath),W=$.spec,J={title:W?.title??Q?.title??dq($.sourcePath),prompt:W?.prompt,workspaceRoot:W?.workspaceRoot,scheduleExpr:W?.triggerKind==="schedule"?W.schedule:void 0,timezone:W?.triggerKind==="schedule"?W.timezone:void 0,eventType:W?.triggerKind==="event"?W.event:void 0,filters:W?.triggerKind==="event"?W.filters:void 0,debounceSeconds:W?.triggerKind==="event"?W.debounceSeconds:void 0,dedupeWindowSeconds:W?.triggerKind==="event"?W.dedupeWindowSeconds:void 0,cooldownSeconds:W?.triggerKind==="event"?W.cooldownSeconds:void 0,mode:W?.mode,systemPrompt:W?.systemPrompt,providerId:W?.modelSelection?.providerId,modelId:W?.modelSelection?.modelId,maxIterations:W?.maxIterations,timeoutSeconds:W?.timeoutSeconds,maxParallel:W&&"maxParallel"in W?W.maxParallel:void 0,tools:W?.tools,notesDirectory:W?.notesDirectory,extensions:W?.extensions,source:W?.source},X=$.parseStatus==="valid"&&(W?.enabled??!0);if(!Q){let B=`cspec_${i8()}`;this.insertSpecRow(B,$,J,X,Z);let G=this.getSpec(B);if(!G)throw Error("failed to insert cron_spec row");return{record:G,created:!0,revisionChanged:!0}}let j=Q.sourceHash!==$.sourceHash&&uq(Q,J,Q.enabled,X),V=j?Q.revision+1:Q.revision;this.updateSpecRow(Q.specId,$,J,X,V,Z);let H=this.getSpec(Q.specId);if(!H)throw Error("failed to reload cron_spec after update");return{record:H,created:!1,revisionChanged:j}}insertSpecRow($,Z,Q,W,J){let X=Z.spec;this.db.prepare(`INSERT INTO cron_specs (
318
318
  spec_id, external_id, source_path, trigger_kind,
319
319
  source_mtime_ms, source_hash, parse_status, parse_error,
320
320
  enabled, removed, title, prompt, workspace_root,
@@ -337,7 +337,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let Z=Math.max(1000,Mat
337
337
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
338
338
  tags_json = ?, metadata_json = ?,
339
339
  revision = ?, updated_at = ?
340
- WHERE spec_id = ?`).run(Z.externalId,Z.triggerKind,Z.sourceMtimeMs??null,Z.sourceHash,Z.parseStatus,Z.parseError??null,W?1:0,Q.title??"",Q.prompt??null,Q.workspaceRoot??null,Q.scheduleExpr??null,Q.timezone??null,Q.eventType??null,Q.filters?JSON.stringify(Q.filters):null,Q.debounceSeconds??null,Q.dedupeWindowSeconds??null,Q.cooldownSeconds??null,Q.mode??null,Q.systemPrompt??null,Q.providerId??null,Q.modelId??null,Q.maxIterations??null,Q.timeoutSeconds??null,Q.maxParallel??null,Q.tools?JSON.stringify(Q.tools):null,Q.notesDirectory??null,Q.extensions?JSON.stringify(Q.extensions):null,Q.source??null,Y?.tags?JSON.stringify(Y.tags):null,Y?.metadata?JSON.stringify(Y.metadata):null,J,X,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(F0(),$)}updateSpecNextRunAt($,Z){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Z??null,F0(),$)}updateSpecLastRunAt($,Z){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Z,F0(),$)}updateLastMaterializedRunId($,Z){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(Z,F0(),$)}initializeScheduleNextRun($){let Z=this.getSpec($);if(!Z||Z.triggerKind!=="schedule"||!Z.enabled||!Z.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Q=new Date(y$(Z.scheduleExpr,Date.now(),Z.timezone)).toISOString();this.updateSpecNextRunAt($,Q)}materializeDueScheduleRun($){let Z=$.nowMs,Q=new Date(Z).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let J=r1(W);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let X=J.nextRunAt;if(!X){let V=new Date(y$(J.scheduleExpr,Z,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Q,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(X).getTime()>Z)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X};let Y=`crun_${i8()}`,j;try{j=new Date(y$(J.scheduleExpr,Z,J.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
340
+ WHERE spec_id = ?`).run(Z.externalId,Z.triggerKind,Z.sourceMtimeMs??null,Z.sourceHash,Z.parseStatus,Z.parseError??null,W?1:0,Q.title??"",Q.prompt??null,Q.workspaceRoot??null,Q.scheduleExpr??null,Q.timezone??null,Q.eventType??null,Q.filters?JSON.stringify(Q.filters):null,Q.debounceSeconds??null,Q.dedupeWindowSeconds??null,Q.cooldownSeconds??null,Q.mode??null,Q.systemPrompt??null,Q.providerId??null,Q.modelId??null,Q.maxIterations??null,Q.timeoutSeconds??null,Q.maxParallel??null,Q.tools?JSON.stringify(Q.tools):null,Q.notesDirectory??null,Q.extensions?JSON.stringify(Q.extensions):null,Q.source??null,Y?.tags?JSON.stringify(Y.tags):null,Y?.metadata?JSON.stringify(Y.metadata):null,J,X,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(F0(),$)}updateSpecNextRunAt($,Z){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Z??null,F0(),$)}updateSpecLastRunAt($,Z){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(Z,F0(),$)}updateLastMaterializedRunId($,Z){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(Z,F0(),$)}initializeScheduleNextRun($){let Z=this.getSpec($);if(!Z||Z.triggerKind!=="schedule"||!Z.enabled||!Z.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let Q=new Date(h$(Z.scheduleExpr,Date.now(),Z.timezone)).toISOString();this.updateSpecNextRunAt($,Q)}materializeDueScheduleRun($){let Z=$.nowMs,Q=new Date(Z).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let W=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!W)return this.db.exec("COMMIT;"),{queued:!1};let J=r1(W);if(J.triggerKind!=="schedule"||!J.enabled||J.removed||J.parseStatus!=="valid"||!J.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let X=J.nextRunAt;if(!X){let V=new Date(h$(J.scheduleExpr,Z,J.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(V,Q,J.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:V}}if(new Date(X).getTime()>Z)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:X};let Y=`crun_${i8()}`,j;try{j=new Date(h$(J.scheduleExpr,Z,J.timezone)).toISOString()}catch{j=void 0}return this.db.prepare(`INSERT INTO cron_runs (
341
341
  run_id, spec_id, spec_revision, trigger_kind, status,
342
342
  scheduled_for, trigger_event_id, attempt_count,
343
343
  created_at, updated_at
@@ -449,41 +449,41 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let Z=Math.max(1000,Mat
449
449
  error = ?,
450
450
  scheduled_for = COALESCE(?, scheduled_for),
451
451
  updated_at = ?
452
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,Z,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,Z){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(Z,F0(),$)}attachReportPathToRun($,Z){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(Z,F0(),$)}}class a8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new n8({dbPath:$.dbPath});let Z=$.specs;this.reconciler=new M7({store:this.store,specs:Z}),this.materializer=new d8({store:this.store}),this.eventIngress=new G7({store:this.store,logger:$.logger}),this.runner=new l8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:Z,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new R7({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:Q});else W.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as $M,readFile as GH}from"node:fs/promises";import{join as KH}from"node:path";import{formatDisplayUserInput as ZM,normalizeUserInput as QM}from"@cline/shared";import{resolveSessionDataDir as FH}from"@cline/shared/storage";import{mkdirSync as pq,writeFileSync as rq}from"node:fs";import{dirname as iq}from"node:path";import{normalizeUserInput as nq}from"@cline/shared";import{nanoid as aq}from"nanoid";import{nanoid as dq}from"nanoid";function s8($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function D5($,Z){let Q=s8($),W=s8(Z),J=`${Q}__${W}`;return J.length>180?J.slice(0,180):J}function C7($,Z){let Q=s8($),W=s8(Z);return`${Q}__teamtask__${W}__${dq(6)}`}function o8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let W=$.slice(0,Q),J=$.slice(Q+12),X=J.lastIndexOf("__");if(X<=0)return null;let Y=J.slice(0,X),j=J.slice(X+2);if(!W||!Y||!j)return null;return{rootSessionId:W,agentId:Y,teamTaskId:j}}function L5($){if(o8($))return null;let Z="__",Q=$.indexOf(Z);if(Q<=0)return null;let W=$.slice(0,Q),J=$.slice(Q+Z.length);if(!W||!J)return null;return{rootSessionId:W,agentId:J}}function P7($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let Z=String($.reason??"").toLowerCase();if(Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt"))return"cancelled";if(Z.includes("fail")||Z.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as o}from"zod";var lq=o.enum(xZ),N0=o.object({version:o.literal(1),session_id:o.string().min(1),source:o.string().min(1),pid:o.number().int(),started_at:o.string().min(1),ended_at:o.string().min(1).optional(),exit_code:o.number().int().nullable().optional(),status:lq,interactive:o.boolean(),provider:o.string().min(1),model:o.string().min(1),cwd:o.string().min(1),workspace_root:o.string().min(1),team_name:o.string().min(1).optional(),enable_tools:o.boolean(),enable_spawn:o.boolean(),enable_teams:o.boolean(),prompt:o.string().optional(),metadata:o.record(o.string(),o.unknown()).optional(),messages_path:o.string().min(1).optional()});function QH($){if(!$)return!1;return Object.values($).some((Z)=>typeof Z==="function")}function b7($,Z){let Q=[...$??[],...Z??[]];if(Q.length===0)return;let W=[],J=new Set;for(let X of Q){if(J.has(X.name))continue;J.add(X.name),W.push(X)}return W}function WH($){return JSON.stringify($,(Z,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function U1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function S7($,Z){let Q={...$};Q.id=U1(Q.id)??aq();let W=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,J={id:U1(W?.id)??U1(Q.modelId)??U1(Z?.id),provider:U1(W?.provider)??U1(Q.providerId)??U1(Z?.provider),family:U1(W?.family)??U1(Z?.family)};if(delete Q.providerId,delete Q.modelId,J.id&&J.provider)Q.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Q.modelInfo;return Q}function _5($){return $.map((Z)=>S7(Z))}function z5($,Z,Q=[]){let W=$.map((V,H)=>{let B=Q[H],K=B?.role===V.role&&JSON.stringify(B.content)===JSON.stringify(V.content)?{...B,...V}:{...V};return S7(K)}),J=Q.length,X=[];for(let V=J;V<W.length;V+=1)if(W[V]?.role==="assistant")X.push(V);if(X.length===0){let V=[...W].reverse().findIndex((H)=>H.role==="assistant");if(V===-1)return W;X.push(W.length-1-V)}let Y=X[X.length-1],j=X.some((V)=>W[V]?.metrics);for(let V of X){let H=W[V],B=H.metrics;if(!B&&V===Y&&!j){let G=Z.usage;B={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}W[V]={...S7(H,{id:Z.model.id,provider:Z.model.provider,family:Z.model.info?.family}),...B?{metrics:B}:{},ts:H.ts??Z.endedAt.getTime()}}return W}function t8($){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 sq=120;function k$($){let Z=$?.trim();return Z?Z.slice(0,sq):void 0}function y7($){let Z=nq($??"").trim();if(!Z)return;return k$(Z.split(`
453
- `)[0]?.trim())}function i1($){if(!$)return;let Z={...$},Q=k$(typeof Z.title==="string"?Z.title:void 0);if(Q)Z.title=Q;else delete Z.title;return Object.keys(Z).length>0?Z:void 0}function e8($){let Z=i1($.metadata)??{},Q=$.title!==void 0?k$($.title):y7($.prompt);if(Q)Z.title=Q;return Object.keys(Z).length>0?Z:void 0}function h7($){let Z=o8($);if(Z)return{agent:"teammate",sessionId:Z.rootSessionId,taskType:"team"};let Q=L5($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function k7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:_5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function JH($,Z,Q){pq(iq($),{recursive:!0}),rq($,`${JSON.stringify(k7({updatedAt:Z,context:Q,messages:[]}),null,2)}
454
- `,"utf8")}function XH($,Z){return N0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:Z?.endedAt??$.endedAt??void 0,exit_code:Z?.exitCode??$.exitCode??void 0,status:Z?.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:Z?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function YH($,Z,Q){let W=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let X=await Z(J);if(typeof X==="object"&&X!==null&&"updated"in X&&X.updated===!1){if(W+=1,W>=Q)return X;continue}return X}}import{existsSync as oq}from"node:fs";import{readFile as tq}from"node:fs/promises";import{formatDisplayUserInput as jH}from"@cline/shared";class $4{listeners=new Set;subscribe($,Z){let Q={listener:$,sessionId:Z?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let Z=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==Z)continue;Q.listener($)}}get size(){return this.listeners.size}}async function n1($){let Z=$?.trim();if(!Z||!oq(Z))return[];try{let Q=(await tq(Z,"utf8")).trim();if(!Q)return[];let W=JSON.parse(Q);if(Array.isArray(W))return VH(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let J=W.messages;if(Array.isArray(J))return VH(J)}return[]}catch{return[]}}function eq($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:jH($.content)};return{...$,content:$.content.map((Z)=>{if(Z.type!=="text"||typeof Z.text!=="string")return Z;return{...Z,text:jH(Z.text)}})}}function VH($){return $.map(eq)}function I7($){return $?{...$}:void 0}async function HH($,Z){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await Z.queueSpawnRequest($);let W=await Z.upsertSubagentSessionFromHook($);if(!W)return;await Z.appendSubagentHookAudit(W,$),await Z.applySubagentStatus(W,$)}function Z4($){if(typeof $!=="string")return;let Z=$.trim();return Z.length>0?Z:void 0}function x0($){let Z=Z4($);if(!Z)return;return Z.toLowerCase()==="unknown"?void 0:Z}function T5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function WM($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function g7($){let Z=$??200;return Number.isFinite(Z)?Math.max(0,Math.floor(Z)):200}function JM($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function XM($){return $.isSubagent!==!0&&!Z4($.parentSessionId)}function YM($){let Z=$.match(/\d{13,}/g);if(!Z||Z.length===0)return 0;let Q=0;for(let W of Z){let J=Number.parseInt(W,10);if(Number.isFinite(J)&&J>Q)Q=J}return Q}function m7($){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 jM($){let Z=g7($);if(Z===0)return[];let Q=FH(),J=(await $M(Q,{withFileTypes:!0}).catch(()=>[])).filter((Y)=>Y.isDirectory()).map((Y)=>({entry:Y,recency:YM(Y.name.trim())})).sort((Y,j)=>j.recency-Y.recency||j.entry.name.localeCompare(Y.entry.name));return(await Promise.all(J.map(async({entry:Y})=>{let j=Y.name.trim();if(!j)return;let V=KH(Q,j,`${j}.json`),H=await GH(V,"utf8").catch(()=>{return});if(!H)return;let B;try{B=JSON.parse(H)}catch{return}let G=N0.safeParse(B);if(!G.success)return;return m7(G.data)}))).filter((Y)=>Boolean(Y)).sort((Y,j)=>j.startedAt.localeCompare(Y.startedAt)).slice(0,Z)}async function VM($,Z,Q){let W=g7(Z);if(W===0)return await $.listSessions(0),[];let J=Q.includeSubagents?W:JM(W),X=await $.listSessions(J);return(Q.includeSubagents?X:X.filter(XM)).slice(0,W)}function HM($){if(typeof $==="string")return $.trim();let Z=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let W=Q;if(W.type!=="text")continue;let J=W.text?.trim();if(J)Z.push(J)}return Z.join(`
455
- `).trim()}function BH($){return $.replace(/\s+/g," ").trim()}function BM($,Z){if($.length<=Z)return $;return`${$.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function GM($){for(let Z of["user","assistant"])for(let Q of $){if(Q.role!==Z)continue;let W=BH(HM(Q.content));if(!W)continue;let J=Z==="user"?BH(ZM(W)):W,X=QM(J.split(`
456
- `)[0]??J);return BM(X,50)}return}function KM($){let Z=0;for(let Q of $)Z+=T5(Q.metrics?.cost)??0;return Z}function FM($){let Z,Q;for(let W=$.length-1;W>=0;W-=1){let J=$[W];if(!Z)Z=x0(J.modelInfo?.provider);if(!Q)Q=x0(J.modelInfo?.id);if(Z&&Q)break}return{provider:Z,model:Q}}function AM($){return x0($?.provider)??x0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function fM($){return x0($?.model)??x0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function x7($,Z){let Q=WM($.metadata),W=Z4(Z?.title)??Z4(Q?.title),J=T5(Z?.totalCost)??T5(Q?.totalCost),X=Q||W!==void 0||J!==void 0?{...Q??{},...W!==void 0?{title:W}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:x0(Z?.provider)??x0($.provider)??AM(Q)??"",model:x0(Z?.model)??x0($.model)??fM(Q)??"",metadata:X}}function UM($){let Z=$.content;if(!Array.isArray(Z))return!1;return Z.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function DM($,Z){if($.status!=="running"||$.interactive!==!0)return!1;let Q=Z.at(-1);return Q?.role==="assistant"&&!UM(Q)}async function LM($,Z){return await Promise.all(Z.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let W=await $.readSessionMessages(Q.sessionId);return DM(Q,W)?{...Q,status:"idle"}:Q}))}async function _M($,Z){return await Promise.all(Z.map(async(Q)=>{let W=x7(Q),J=Boolean(Z4(W.metadata?.title)),X=Boolean(x0(W.provider)),Y=Boolean(x0(W.model)),j=T5(W.metadata?.totalCost),V=j!==void 0&&j>0;if(J&&X&&Y&&V)return W;let H=await $.readSessionMessages(Q.sessionId);if(H.length===0)return W;let B=FM(H),G=KM(H);return x7(Q,{title:J?void 0:GM(H),provider:X?void 0:B.provider,model:Y?void 0:B.model,totalCost:V||G<=0?void 0:G})}))}async function v7($,Z={}){let Q=g7(Z.limit),W=Z.includeSubagents===!0,J=await VM($,Q,{includeSubagents:W}),X=Z.includeManifestFallback===!0&&J.length<Q?await jM(Math.min(Math.max(Q*2,100),500)):[],Y=new Map;for(let H of[...J,...X]){if(Y.has(H.sessionId))continue;Y.set(H.sessionId,H)}let j=X.length===0?J:Array.from(Y.values()).sort((H,B)=>B.startedAt.localeCompare(H.startedAt)).slice(0,Q),V=await LM($,j);if(Z.hydrate===!1)return V.map((H)=>x7(H));return await _M($,V)}async function zM($){let Z=$.trim();if(!Z)return;let Q=KH(FH(),Z,`${Z}.json`),W=await GH(Q,"utf8").catch(()=>{return});if(!W)return;try{let J=N0.safeParse(JSON.parse(W));return J.success?J.data.messages_path:void 0}catch{return}}async function TM($,Z={}){let Q=new Map;return await v7({listSessions:async(J)=>{let X=await $.listSessions(J);Q.clear();for(let Y of X)Q.set(Y.sessionId,Y);return X.map(t8)},readSessionMessages:async(J)=>{let X=Q.get(J)?.messagesPath??await zM(J);return await n1(X)}},Z)}import{captureSdkError as aG}from"@cline/shared";import{createSessionId as OR,isHubProtocolCompatible as qR,resolveClineBuildEnv as MR,resolveHubCommandTimeoutMs as RR}from"@cline/shared";import{spawn as tM}from"node:child_process";import{closeSync as eM,mkdirSync as $R,openSync as ZR}from"node:fs";import{basename as QR,dirname as WR,join as JR}from"node:path";import{fileURLToPath as XR}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as YR,isHubDaemonProcess as wH,isHubProtocolCompatible as jR,resolveClineBuildEnv as CH,withResolvedClineBuildEnv as VR}from"@cline/shared";import{createHash as OM,randomBytes as qM}from"node:crypto";import{existsSync as MM}from"node:fs";import{chmod as RM,mkdir as c7,readFile as LH,rm as u7,writeFile as _H}from"node:fs/promises";import{dirname as zH,join as d7}from"node:path";import{resolveClineDataDir as W4,resolveClineDir as Ed}from"@cline/shared/storage";var fH="0.0.54-nightly.1782962319";var Q4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:fH,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var EM="CLINE_HUB_DISCOVERY_PATH",NM="CLINE_HUB_BUILD_ID",UH=30000,wM=15000,CM=100;function PM($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function SM($){return OM("sha256").update($).digest("hex").slice(0,12)}function bM($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z?String(Z.code)==="EPERM":!1}}function TH(){return qM(32).toString("hex")}function yM($){return new Promise((Z)=>setTimeout(Z,$))}function hM($){return`${$}.lock`}async function kM($){try{let Z=JSON.parse(await LH(d7($,"owner.json"),"utf8"));if(typeof Z.pid!=="number"||typeof Z.acquiredAt!=="string")return;return{pid:Z.pid,acquiredAt:Z.acquiredAt}}catch{return}}async function DH($){await u7($,{recursive:!0,force:!0}).catch(()=>{return})}function OH(){return process.env[NM]?.trim()||String(Q4.version)}function I$($=process.argv[1]?.trim()||process.cwd()){let Z=`hub-${SM($)}`,Q=process.env[EM]?.trim()||d7(W4(),"locks","hub","owners",`${PM(Z)}.json`);return{ownerId:Z,discoveryPath:Q}}function wd($=`hub-${Date.now().toString(36)}`){return I$($)}async function A0($){try{let Z=JSON.parse(await LH($,"utf8"));if(typeof Z.hubId!=="string"||typeof Z.protocolVersion!=="string"||typeof Z.authToken!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string"||typeof Z.startedAt!=="string"||typeof Z.updatedAt!=="string")return;return{hubId:Z.hubId,protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,authToken:Z.authToken,host:Z.host,port:Z.port,url:Z.url,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:Z.startedAt,updatedAt:Z.updatedAt}}catch{return}}async function qH($,Z){await c7(zH($),{recursive:!0}),await u7($,{force:!0}).catch(()=>{return}),await _H($,`${JSON.stringify(Z,null,2)}
457
- `,{encoding:"utf8",mode:384}),await RM($,384)}async function a0($){await u7($,{force:!0}).catch(()=>{return})}async function MH($,Z){let Q=hM($);await c7(zH(Q),{recursive:!0});let W=Date.now()+wM;while(!0)try{await c7(Q,{recursive:!1}),await _H(d7(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
458
- `,"utf8");try{return await Z()}finally{await DH(Q)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let Y=await kM(Q),j=Y?Date.now()-Date.parse(Y.acquiredAt):UH+1;if(!Y||!bM(Y.pid)||j>UH){await DH(Q);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${Q}`);await yM(CM)}}async function x$($,Z){try{let Q=await fetch(Z?.authToken?IM($):RH($),{headers:Z?.authToken?{authorization:`Bearer ${Z.authToken}`}:void 0});if(!Q.ok)return;let W=await Q.json();if(typeof W.protocolVersion!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string")return;return{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((J)=>typeof J==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,host:W.host,port:W.port,url:W.url,hubId:typeof W.hubId==="string"?W.hubId:void 0,authToken:typeof W.authToken==="string"?W.authToken:void 0,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:typeof W.startedAt==="string"?W.startedAt:void 0,updatedAt:typeof W.updatedAt==="string"?W.updatedAt:void 0}}catch{return}}function D1($,Z,Q="/hub"){return new URL(`ws://${$}:${Z}${Q}`).toString()}function RH($){let Z=new URL($);return Z.protocol=Z.protocol==="wss:"?"https:":"http:",Z.pathname="/health",Z.search="",Z.toString()}function IM($){let Z=new URL(RH($));return Z.pathname="/status",Z.toString()}function Cd($){return MM($)}import{CLINE_HUB_DEV_PORT as xM,CLINE_HUB_PORT as gM,resolveClineBuildEnv as mM}from"@cline/shared";var vM="CLINE_HUB_HOST",cM="CLINE_HUB_PORT",uM="CLINE_HUB_PATHNAME",dM="127.0.0.1",lM=gM,pM="/hub";function EH($){return mM($)==="development"?xM:lM}function rM($={}){return($.env??process.env)[vM]?.trim()||dM}function O5($={}){let Q=($.env??process.env)[cM]?.trim();if(!Q)return EH($);let W=Number.parseInt(Q,10);if(!Number.isInteger(W)||W<1||W>65535)return EH($);return W}function iM($={}){return($.env??process.env)[uM]?.trim()||pM}function a1($={},Z={}){return{host:$.host??rM(Z),port:$.port??O5(Z),pathname:$.pathname??iM(Z)}}import{join as nM}from"node:path";var aM="shared:cline",sM="CLINE_HUB_DISCOVERY_PATH",oM="hub-production";function Id($){let Z=S$($.trim());return I$(`workspace:${Z||$.trim()}`)}function L1($=aM){return I$($)}function s1(){return{ownerId:oM,discoveryPath:process.env[sM]?.trim()||nM(W4(),"locks","hub","production.json")}}var HR=8000,BR=200,GR=3000,KR=100,FR=[100,250,500,1000,2000],AR="--cline-hub-daemon";function fR($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function UR(){try{let $=JR(W4(),"logs","hub-daemon.log");return $R(WR($),{recursive:!0}),{fd:ZR($,"a"),logPath:$}}catch{return}}function PH(){return CH()==="production"?s1():L1()}function g$($){return jR($).compatible}function NH($,Z,Q){if(!Z||Z.url!==Q)return $;return{...$,authToken:$.authToken??Z.authToken,pid:$.pid??Z.pid}}async function m$($,Z){try{return await x$($,{authToken:Z})}catch{return}}async function DR($,Z){let Q=Date.now()+Z;while(Date.now()<Q){if(!(await m$($))?.url)return!0;await new Promise((J)=>setTimeout(J,KR))}return!1}async function q5($,Z){if(await l7($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await DR($.url,GR);return await a0(Z).catch(()=>{return}),Q}async function J4($,Z){if(g$($))return!0;return q5($,Z)}async function SH($){if(CH()!=="production")return;let Z=L1();if(Z.discoveryPath===$.discoveryPath)return;let Q=await A0(Z.discoveryPath);if(Q?.url)await q5(Q,Z.discoveryPath);else await a0(Z.discoveryPath).catch(()=>{return})}function LR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return XR(new URL(`./entry.${$}`,import.meta.url))}function _R($,Z){let Q=LR(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let J=QR(W).toLowerCase().includes("bun"),X=Q.startsWith("/$bunfs/"),Y=J&&Q.toLowerCase().endsWith(".ts"),j=X?[AR]:[...Y?["--conditions=development"]:[],Q];return{launcher:W,args:[...j,"--cwd",$,...fR(Z)],cwd:$,env:{...VR(process.env),CLINE_NO_INTERACTIVE:"1",[YR]:"1"}}}function zR($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function TR($,Z={}){if(wH())return;let Q=_R($,Z),W=UR();try{tM(Q.launcher,Q.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(W)eM(W.fd)}}async function M5($,Z={}){for(let Q=0;;Q++)try{TR($,Z);return}catch(W){let J=FR[Q];if(!zR(W)||J===void 0)throw W;await new Promise((X)=>setTimeout(X,J))}}function bH($,Z={}){if(wH())return;let Q=PH(),W=a1(Z),J=D1(W.host,W.port,W.pathname),X=Z.allowPortFallback===!0&&W.port!==0;SH(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(Y)=>{let j=!1;if(Y?.url)if(!Y.authToken){if(j=!0,!await q5(Y,Q.discoveryPath)&&!X)return}else{let B=await m$(Y.url,Y.authToken);if(B?.url&&g$(B)&&await o1(B.url,{authToken:Y.authToken}))return;if(B?.url)await J4({...B,authToken:Y.authToken},Q.discoveryPath);else await a0(Q.discoveryPath).catch(()=>{return})}let V=await m$(J);if(V?.url){if(g$(V)){if(!X||!j)return}else if(!await J4({...V,authToken:void 0},Q.discoveryPath)&&!X)return}let H=X?{...W,port:0}:W;await M5($,H)}).catch(()=>{})}async function id($,Z={}){let Q=PH(),W=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=a1(Z),X=D1(J.host,J.port,J.pathname),Y=(F)=>{if(!W)k2(F.url,F.authToken);return F};await SH(Q).catch(()=>{return});let j=await A0(Q.discoveryPath),V=!1;if(j?.url){let F=j.authToken;if(!F)V=!0,await q5(j,Q.discoveryPath);else{let A=await m$(j.url,F);if(A?.url&&g$(A)&&await o1(A.url,{authToken:F}))return Y({url:A.url,authToken:F});if(A?.url)await J4({...A,authToken:F},Q.discoveryPath);else await a0(Q.discoveryPath).catch(()=>{return})}}let H=await m$(X);if(H?.url){let F=NH(H,j,X);if(g$(H))throw Error(`A compatible Cline Hub is already running at ${X}, 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 J4(F,Q.discoveryPath)&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Z.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await M5($,G);let K=Date.now()+HR;while(Date.now()<K){let F=await A0(Q.discoveryPath);if(F?.url&&F.authToken){let L=await m$(F.url,F.authToken);if(L?.url&&g$(L)&&await o1(L.url,{authToken:F.authToken}))return Y({url:L.url,authToken:F.authToken})}let A=await m$(X);if(A?.url&&!g$(A)){let L=NH(A,F,X);if(!await J4(L,Q.discoveryPath)&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,BR))}throw Error("Timed out waiting for detached hub startup.")}function E5(){return MR()==="production"?s1():L1()}function ER(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function xH($){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((Z)=>Buffer.from(Z))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return xH($.data);return String($)}function NR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function yH($){let Z=$,Q=NR(Z.reason);return new g0("hub_connection_closed",Z.code||Q?`Hub connection closed (code=${Z.code??0}${Q?`, reason=${Q}`:""})`:p7,{closeCode:Z.code,closeReason:Q||void 0})}function wR($,Z){if($ instanceof g0)return $;if($ instanceof Error)return new g0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new g0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new g0("hub_connect_failed",Q);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new g0("hub_connect_failed",W?`Failed to connect to hub at ${Z.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${Z.toString()}.`)}var CR=8000,PR=200,hH="*",kH=8000,SR="cline-hub-auth.",gH=new Map,mH=new Set,bR=3000,yR=3000,hR=100,p7="Hub connection closed",kR=250,IR=5000,IH=0.5;class g0 extends Error{code;details;constructor($,Z,Q){super(Z);this.code=$;this.details=Q;this.name="HubTransportError"}}function xR($){return $ instanceof g0}class R5 extends Error{command;code;constructor($,Z,Q){super(Q);this.command=$;this.code=Z;this.name="HubCommandError"}}function vH($,Z){return $ instanceof R5&&$.code==="hub_command_timeout"&&(Z===void 0||$.command===Z)}function cH($){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;let Q=n7($.toString());return Q?gH.get(Q):void 0}function gR($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function n7($){if(!gR($))return;let Z=new URL(I2($));return Z.search="",Z.hash="",Z.toString()}function r7($){let Z=n7($);return!!Z&&mH.has(Z)}function k2($,Z){let Q=n7($);if(Q){if(mH.add(Q),Z?.trim())gH.set(Q,Z)}return $}class _1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new g0("hub_connection_closed",p7);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),Z=this.options.authToken?.trim()||cH($);$.hash="";let W=new(ER())($.toString(),Z?[`${SR}${Z}`]:void 0);this.socket=W;let J=!1;this.connectPromise=new Promise((X,Y)=>{let j=!1,V=setTimeout(()=>{if(j)return;j=!0,J=!0,this.lastCloseError=new g0("hub_connect_timeout",`Timed out connecting to hub after ${kH}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Y(this.lastCloseError)},kH);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(V),X()}),W.addEventListener("error",(H)=>{if(j)return;j=!0,clearTimeout(V),this.lastCloseError=wR(H,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)}),W.addEventListener("close",(H)=>{if(j)return;if(j=!0,clearTimeout(V),!J)this.lastCloseError=yH(H),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)})}),W.addEventListener("message",(X)=>{this.handleFrame(JSON.parse(xH(X)))}),W.addEventListener("close",(X)=>{if(this.socket!==W)return;if(!J)this.lastCloseError=yH(X),this.sawSocketClose=!0;this.registered=!1;for(let Y of this.pendingReplies.values())Y.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 X of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(X));this.reconnectAttempt=0}subscribe($,Z){let Q=Z?.sessionId?.trim()||void 0,W={listener:$,sessionId:Q};return this.listeners.add(W),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(Q,-1)}}async command($,Z,Q,W){let J=0,X=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,Z,Q,W)}catch(Y){if(!X||J>=1||!await this.recoverLocalHubTransport(Y))throw Y;J+=1}}async commandOnce($,Z,Q,W){await this.connect();let J=OR("hubreq_"),X=RR($,W?.timeoutMs),Y=new Promise((V,H)=>{let B=X===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;H(new R5($,"hub_command_timeout",`Hub command ${$} timed out after ${X}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.`))},X);this.pendingReplies.set(J,{resolve:(G)=>{if(B)clearTimeout(B);V(G)},reject:(G)=>{if(B)clearTimeout(B);H(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Q,timeoutMs:X,payload:Z}})}catch(V){throw this.pendingReplies.delete(J),V}let j=await Y;if(!j.ok){if(j.error?.code===c8){let V=Q??(typeof Z?.sessionId==="string"?Z.sessionId:void 0);throw new C$(V,j.error.message)}throw new R5($,j.error?.code,j.error?.message??`Hub command ${$} failed`)}return j}async recoverLocalHubTransport($){if(!r7(this.currentUrl)||!xR($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Z=await X4({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Z)return!1;return this.currentUrl=Z,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(kR*2**this.reconnectAttempt,IR),Z=Math.round($*(1-IH)+Math.random()*$*IH);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Z)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!r7(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await X4({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 g0("hub_connection_closed",p7),this.sawSocketClose=!1;for(let Z of this.pendingReplies.values())Z.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 g0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,Z){this.sendFrame({kind:$,clientId:this.clientId,...Z?{sessionId:Z}:{}})}adjustSubscriptionCount($,Z){let Q=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(Q)??0)+Z;if(W<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Z<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,W),Z>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??hH}subscriptionSessionIdFromKey($){return $===hH?void 0:$}handleFrame($){switch($.kind){case"reply":{let Z=$.envelope.requestId;if(!Z)return;let Q=this.pendingReplies.get(Z);if(!Q)return;this.pendingReplies.delete(Z),Q.resolve($.envelope);return}case"event":for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==$.envelope.sessionId?.trim())continue;Z.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function I2($){let Z=new URL($);if(Z.protocol==="http:")Z.protocol="ws:";else if(Z.protocol==="https:")Z.protocol="wss:";return Z.toString()}async function o1($,Z){let Q=new _1({url:$,authToken:Z?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function i7($,Z){let Q=I2($),W=await x$(Q,{authToken:Z?.authToken});if(!W)return{status:"unreachable",url:Q};if(!qR(W).compatible)return{status:"protocol_mismatch",url:Q};if(Z?.verifyConnection===!0&&!await o1(Q,{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,authToken:Z.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function mR($){let Z=Date.now()+CR;while(Date.now()<Z){let Q=await A0($.discoveryPath);if(Q?.url){let W=await i7(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(W.status==="compatible")return k2(W.url,Q.authToken)}await new Promise((W)=>setTimeout(W,PR))}return}async function vR($){let Z=Date.now()+yR;while(Date.now()<Z){if(!(await x$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,hR))}return!1}function cR($,Z){try{return I2($)===I2(Z)}catch{return!1}}function uR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let W=Q;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function dR($,Z,Q){let W=new _1({url:$,authToken:Z,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let J=await W.command("session.list",{limit:500},void 0,{timeoutMs:bR});return!uR(J.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function a7($={}){if($.endpoint?.trim()){let J=await i7($.endpoint);return J.status==="compatible"?J.url:void 0}let Z=E5(),Q=await A0(Z.discoveryPath);if(!Q?.url)return;let W=await i7(Q.url,{authToken:Q.authToken});if(W.status==="compatible")return k2(W.url,Q.authToken);if(W.status==="protocol_mismatch")await a0(Z.discoveryPath).catch(()=>{return});return}async function X4($={}){let Z=await a7($);if(Z&&await o1(Z,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return Z;if($.endpoint?.trim())return;let Q=E5();return await M5($.workspaceRoot??process.cwd()),await mR(Q)}async function l7($,Z){let Q=new URL($),W=Z?.trim()||cH(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function lR($=E5()){let Z=await A0($.discoveryPath);if(!Z?.url)return!1;try{if(await l7(Z.url,Z.authToken))return!0}catch{}return!1}async function uH($){if(!r7($.url))return;let Z=E5(),Q=await A0(Z.discoveryPath);if(!Q?.url||!cR(Q.url,$.url))return;if(!await dR(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await lR())return;if(!await vR(Q.url))return;return await a0(Z.discoveryPath).catch(()=>{return}),await X4({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as dH,createSessionId as lH,HUB_CHECKPOINT_CAPABILITY as nR,HUB_COMPACTION_CAPABILITY as aR,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as sR,HUB_HOOK_CAPABILITY_PREFIX as oR,HUB_MISTAKE_LIMIT_CAPABILITY as tR,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as eR,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $E,isHubToolExecutorName as ZE}from"@cline/shared";function pR($){return $?JSON.parse(JSON.stringify($)):void 0}function rR($){return $?JSON.parse(JSON.stringify($)):void 0}function iR($){let Z=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(Z?.history)?Z.history:[]).filter((Y)=>!!Y&&typeof Y==="object"&&!Array.isArray(Y)).flatMap((Y)=>{let j=typeof Y.ref==="string"?Y.ref.trim():"",V=Number(Y.createdAt),H=Number(Y.runCount);if(!j||!Number.isFinite(V)||!Number.isInteger(H))return[];return[{ref:j,createdAt:V,runCount:H,...Y.kind==="stash"||Y.kind==="commit"?{kind:Y.kind}:{}}]}),J=W.at(-1),X=$?.checkpointEnabled===!0?!0:void 0;if(!X&&W.length===0)return;return{...X?{enabled:X}:{},...J?{latest:J}:{},history:W}}function t1($){let{session:Z}=$,Q=pR(Z.metadata);return{version:1,sessionId:Z.sessionId,source:Z.source,status:Z.status,createdAt:Z.startedAt,updatedAt:Z.updatedAt,endedAt:Z.endedAt??null,exitCode:Z.exitCode??null,interactive:Z.interactive,workspace:{cwd:Z.cwd,root:Z.workspaceRoot},model:{providerId:Z.provider,modelId:Z.model},capabilities:{enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams},lineage:{...Z.parentSessionId?{parentSessionId:Z.parentSessionId}:{},...Z.parentAgentId?{parentAgentId:Z.parentAgentId}:{},...Z.agentId?{agentId:Z.agentId}:{},...Z.conversationId?{conversationId:Z.conversationId}:{},isSubagent:Z.isSubagent},...Z.teamName?{team:{name:Z.teamName}}:{},...Z.prompt?{prompt:Z.prompt}:{},...Q?{metadata:Q}:{},...Z.messagesPath?{artifacts:{messagesPath:Z.messagesPath}}:{},...$.messages?{messages:rR($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=iR(Q);return W?{checkpoint:W}:{}})()}}function s7($){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 x2($){if(!$)return;return JSON.parse(JSON.stringify($))}var QE=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function pH($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function rH($){if(!$)return;let{userInstructionService:Z,...Q}=$;return JSON.parse(JSON.stringify(Q))}function iH($){let Z=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof Z.agentId==="string"?Z.agentId:"",conversationId:typeof Z.conversationId==="string"?Z.conversationId:"",iteration:typeof Z.iteration==="number"?Z.iteration:0,metadata:Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0}}function v$($,Z,Q){$.manifest.push(Z),$.handlers.set(Z.capabilityName,Q)}function nH($,Z){let Q={manifest:[],handlers:new Map};for(let J of Object.keys(Z.toolExecutors??{}).filter(ZE)){let X=Z.toolExecutors?.[J];if(typeof X!=="function")continue;v$(Q,{kind:"toolExecutor",executor:J,capabilityName:`${eR}${J}`},async({payload:Y,abortSignal:j})=>{let V=Array.isArray(Y.args)?[...Y.args]:[],H={...iH(Y.context),signal:j};return{result:await X(...V,H)}})}for(let J of $?.extraTools??[])v$(Q,{kind:"tool",name:J.name,description:J.description,inputSchema:x2(J.inputSchema)??{},...J.lifecycle?{lifecycle:x2(J.lifecycle)}:{},capabilityName:`${sR}${J.name}`},async({payload:X,abortSignal:Y,progress:j})=>{let V={...iH(X.context),signal:Y};return{result:await J.execute(X.input,{...V,emitUpdate:(B)=>{j({update:B})}})}});let W=$?.hooks;if(W)for(let J of QE){let X=W[J];if(typeof X!=="function")continue;v$(Q,{kind:"hook",name:J,capabilityName:`${oR}${J}`},async({payload:Y})=>({control:await X(Y.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;v$(Q,{kind:"compaction",capabilityName:aR,config:pH($.compaction)},async({payload:X})=>({result:await J(X.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;v$(Q,{kind:"checkpoint",capabilityName:nR,config:pH($.checkpoint)},async({payload:X})=>({result:await J(X.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;v$(Q,{kind:"mistakeLimit",capabilityName:tR},async({payload:X})=>({result:await J(X.context)}))}if($?.userInstructionService){let J=$.userInstructionService;v$(Q,{kind:"userInstructionService",capabilityName:$E},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Q}function tH($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let Z=$.message;if(typeof Z==="string"&&Z.trim())return Z.trim()}return}function WE($){return tH($)??"Capability request was cancelled."}function JE($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function XE($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function YE($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$,Q=typeof Z.inputTokens==="number"?Z.inputTokens:void 0,W=typeof Z.outputTokens==="number"?Z.outputTokens:void 0;if(Q===void 0||W===void 0)return;return{inputTokens:Q,outputTokens:W,cacheReadTokens:typeof Z.cacheReadTokens==="number"?Z.cacheReadTokens:0,cacheWriteTokens:typeof Z.cacheWriteTokens==="number"?Z.cacheWriteTokens:0,totalCost:typeof Z.totalCost==="number"?Z.totalCost:0}}function aH($){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 o7($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function e1($,Z){return o7($?.[Z])??0}function jE($){let Z=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",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,inputTokens:e1(Z,"inputTokens"),outputTokens:e1(Z,"outputTokens"),cacheReadTokens:e1(Z,"cacheReadTokens"),cacheWriteTokens:e1(Z,"cacheWriteTokens"),cost:o7(Z?.totalCost),totalInputTokens:e1(Q,"inputTokens"),totalOutputTokens:e1(Q,"outputTokens"),totalCacheReadTokens:e1(Q,"cacheReadTokens"),totalCacheWriteTokens:e1(Q,"cacheWriteTokens"),totalCost:o7(Q?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:J}}function VE($){let Z=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??Z?.finishReason,W=XE(Q)?Q:Q==="failed"?"error":"completed",J=YE($?.usage??Z?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof Z?.text==="string"?Z.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof Z?.iterations==="number"?Z.iterations:0,usage:J}}function N5($,Z){return $.error?.message??`hub command failed: ${Z}`}function Y4($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function eH($){let Z=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof Z?.agentId==="string"?Z.agentId:void 0),parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,isSubagent:typeof Z?.isSubagent==="boolean"?Z.isSubagent:!1,source:typeof Z?.source==="string"?Z.source:z0.CORE,pid:typeof Z?.pid==="number"?Z.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:Y4($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:Y4($.status)==="completed"?0:Y4($.status)==="failed"?1:void 0,status:Y4($.status),interactive:Z?.interactive===!0,provider:typeof Z?.provider==="string"?Z.provider:"hub",model:typeof Z?.model==="string"?Z.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof Z?.teamName==="string"?Z.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??Z?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??Z?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??Z?.enableTeams===!0,prompt:typeof Z?.prompt==="string"?Z.prompt:void 0,metadata:Z,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,hookPath:typeof Z?.hookPath==="string"?Z.hookPath:void 0}}function $$($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;return Z.version===1&&typeof Z.sessionId==="string"?JSON.parse(JSON.stringify(Z)):void 0}function HE($){let Z=$$($?.snapshot);if(Z)return s7(Z);let Q=$?.session;return Q?eH(Q):void 0}function sH($,Z,Q){let W=Q?.workspaceRoot?.trim()||Z.config.workspaceRoot||Z.config.cwd;return N0.parse({version:1,session_id:$,source:Z.source??z0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:Y4(Q?.status),interactive:Z.interactive===!0,provider:Z.config.providerId,model:Z.config.modelId,cwd:Q?.cwd?.trim()||Z.config.cwd,workspace_root:W,team_name:Z.config.teamName,enable_tools:Z.config.enableTools,enable_spawn:Z.config.enableSpawnAgent,enable_teams:Z.config.enableAgentTeams,prompt:Z.prompt?.trim()||void 0,metadata:Z.sessionMetadata&&Object.keys(Z.sessionMetadata).length>0?Z.sessionMetadata:void 0})}function oH($,Z){return N0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??Z.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class c${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new $4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,Z){this.clientContext=Z,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd},this.defaultCapabilities=T0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new _1({...this.clientOptions,url:$})}async replaceClient($){let Z=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(Z.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!vH($,"session.create"))return!1;let Z=await uH({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!Z)return!1;return await this.replaceClient(Z),!0}registerPlannedSession($,Z,Q){if(this.sessionCapabilities.set($,Z),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let Z=this.resolveCapabilities($),Q=nH($.localRuntime,Z),W=$.config.sessionId?.trim()||lH(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:x2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??z0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:x2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,Z,Q.handlers);let X;try{X=await J()}catch(H){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(H)){this.registerPlannedSession(W,Z,Q.handlers);try{X=await J()}catch(B){throw this.cleanupPlannedSession(W),B}}else throw H}let Y=$$(X.payload?.snapshot),j=X.payload?.session,V=(Y?.sessionId??j?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(V!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(V,Z,Q.handlers);return{sessionId:V,manifest:Y?oH(Y,$):sH(V,$,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,J=W?this.resolveCapabilities(W):void 0,X=W?nH(W.localRuntime,J??{}):{manifest:[],handlers:new Map},Y=W?W.config.sessionId?.trim()||lH():void 0;if(Y&&J)this.sessionCapabilities.set(Y,J);if(Y&&X.handlers.size>0)this.sessionClientContributionHandlers.set(Y,X.handlers),this.ensureSessionSubscription(Y);let j;try{j=await this.client.command("session.restore",{sessionId:Z,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:x2({...W.config,sessionId:Y}),metadata:{...W.sessionMetadata??{},source:W.source??z0.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...X.manifest.length>0?{clientContributions:X.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:x2(W.toolPolicies)}:{}},Z)}catch(F){if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw F}if(!j.ok){let F=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw Error(F)}let V=$$(j.payload?.snapshot),H=j.payload?.session,B=(V?.sessionId??H?.sessionId)?.trim();if(Q&&!B){if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw Error("Hub checkpoint restore returned no session id")}if(B&&Y&&B!==Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);if(B&&J)this.sessionCapabilities.set(B,J);if(B&&X.handlers.size>0)this.sessionClientContributionHandlers.set(B,X.handlers);if(B)this.ensureSessionSubscription(B);let G=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,K=j.payload?.checkpoint;if(!K)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:B,startResult:B?{sessionId:B,manifest:V?oH(V,W??{}):sH(B,W??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:G,checkpoint:K}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[],prompt:Z.payload?.prompt,updated:Z.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[],prompt:Z.payload?.prompt,removed:Z.payload?.removed===!0}}async getAccumulatedUsage($){let Z=await this.client.command("session.get",{includeSnapshot:!0},$),Q=$$(Z.payload?.snapshot);if(Q){let Y=Q.usage?{...Q.usage}:void 0,j=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return Y||j?{usage:Y,aggregateUsage:j}:void 0}let W=Z.payload?.session,J=aH(W?.usage),X=aH(W?.aggregateUsage);return J||X?{usage:J,aggregateUsage:X}:void 0}async abort($,Z){await this.client.command("run.abort",{sessionId:$,reason:tH(Z)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,Z]of this.sessionSubscriptions){Z();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 Z;try{Z=await this.client.command("session.get",void 0,$)}catch(Q){if(P$(Q))return;throw Q}return HE(Z.payload)}async listSessions($=100){let Z=await this.client.command("session.list",{limit:$}),Q=Array.isArray(Z.payload?.snapshots)?Z.payload.snapshots.flatMap((J)=>{let X=$$(J);return X?[s7(X)]:[]}):[];if(Q.length>0)return Q;return(Z.payload?.sessions??[]).map(eH)}async listSettings($){let Z=await this.client.command("settings.list",rH($));if(!Z.ok)throw Error(N5(Z,"settings.list"));return Z.payload?.snapshot}async toggleSetting($){let Z=await this.client.command("settings.toggle",rH($));if(!Z.ok)throw Error(N5(Z,"settings.toggle"));return{snapshot:Z.payload?.snapshot,changedTypes:Array.isArray(Z.payload?.changedTypes)?Z.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,Z){let Q={...Z.metadata??{}};if(typeof Z.prompt==="string")Q.prompt=Z.prompt;if(typeof Z.title==="string")Q.title=Z.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let Z=$.trim();if(!Z)return[];let Q=await this.client.command("session.messages",{sessionId:Z},Z);if(!Q.ok)throw dH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(N5(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:Z,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(N5(Q,"session.messages"));let W=Q.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,Z){return this.events.subscribe($,Z)}ensureSessionSubscription($){let Z=$.trim();if(!Z||this.sessionSubscriptions.has(Z))return;let Q=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:Z});this.sessionSubscriptions.set(Z,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let Z=$.trim();if(!Z)return;this.sessionSubscriptions.get(Z)?.(),this.sessionSubscriptions.delete(Z),this.agentDoneEmittedForCurrentRunBySession.delete(Z)}resolveCapabilities($){return T0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:VE($.payload)}})}handleHubEvent($){let Z=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!Z)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(Z);let Q=$$($.payload?.snapshot),W=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:Z,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:Z,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!Q&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:Z,payload:$.payload});return}case"usage.updated":{let Q=jE($.payload);this.events.emit({type:"agent_event",payload:{sessionId:Z,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:Z,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=$$($.payload?.snapshot),W=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:Z,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:Z,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:Z,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:Z,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount,userImages:Q.userImages,userFiles:Q.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=$$($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:Z,payload:{...$.payload,reason:W}}),Q?.interactive===!0&&j0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:Z,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,Z,Q){try{dH(this.telemetry,{component:"core",operation:$,error:Z,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let Z=$.sessionId?.trim();if(!Z)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let X=this.sessionClientContributionHandlers.get(Z)?.get(J);if(!X){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${Z}.`},Z).catch(()=>{});return}let Y=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let V=(H)=>{this.client.command("capability.progress",{requestId:W,payload:H},Z).catch((B)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",B,$)})};try{let H=await X({payload:Y,abortSignal:j.signal,progress:V});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:H},Z)}catch(H){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:H instanceof Error?H.message:String(H)},Z)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let Z=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!Z)return;let Q=this.activeCapabilityAbortControllers.get(Z);if(!Q)return;Q.abort(WE($.payload.error))}async handleApprovalRequested($){let Z=$.sessionId?.trim();if(!Z)return;let Q=this.sessionCapabilities.get(Z)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",X=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!J||!X)return;let Y=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},j=JE($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:Z,toolCallId:J,toolName:X,toolInput:j});let V=await Promise.resolve(Q({sessionId:Z,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:Z,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:X,input:j,policy:Y})).catch((H)=>({approved:!1,reason:H instanceof Error?H.message:`Tool approval request failed: ${String(H)}`}));await this.client.command("approval.respond",{approvalId:W,approved:V.approved,reason:V.reason},Z).catch(()=>{})}}class w5 extends c${constructor($){super({url:I2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as BE,mkdirSync as GE}from"node:fs";import{join as KE}from"node:path";import{asBool as j4,asOptionalString as Q1,asString as z1,ensureSessionSchema as FE,loadSqliteDb as AE,nowIso as C5,toBoolInt as V4}from"@cline/shared/db";import{resolveDbDataDir as fE}from"@cline/shared/storage";class Z${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??fE()}init(){this.getRawDb()}ensureSessionsDir(){if(!BE(this.sessionsDirPath))GE(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return KE(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=AE(this.sessionDbPath());return FE($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,Z=[]){return this.getRawDb().prepare($).run(...Z)}queryOne($,Z=[]){return this.getRawDb().prepare($).get(...Z)??void 0}queryAll($,Z=[]){return this.getRawDb().prepare($).all(...Z)}create($){let Z=C5();this.run(`INSERT OR REPLACE INTO sessions (
452
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,Z,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,Z){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(Z,F0(),$)}attachReportPathToRun($,Z){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(Z,F0(),$)}}class a8{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new n8({dbPath:$.dbPath});let Z=$.specs;this.reconciler=new M7({store:this.store,specs:Z}),this.materializer=new d8({store:this.store}),this.eventIngress=new G7({store:this.store,logger:$.logger}),this.runner=new l8({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:Z,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new R7({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:Q});else W.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as JM,readFile as GH}from"node:fs/promises";import{join as KH}from"node:path";import{formatDisplayUserInput as XM,normalizeUserInput as YM}from"@cline/shared";import{resolveSessionDataDir as FH}from"@cline/shared/storage";import{mkdirSync as aq,writeFileSync as sq}from"node:fs";import{dirname as oq}from"node:path";import{normalizeUserInput as tq}from"@cline/shared";import{nanoid as eq}from"nanoid";import{nanoid as iq}from"nanoid";function s8($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function L5($,Z){let Q=s8($),W=s8(Z),J=`${Q}__${W}`;return J.length>180?J.slice(0,180):J}function C7($,Z){let Q=s8($),W=s8(Z);return`${Q}__teamtask__${W}__${iq(6)}`}function o8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let W=$.slice(0,Q),J=$.slice(Q+12),X=J.lastIndexOf("__");if(X<=0)return null;let Y=J.slice(0,X),j=J.slice(X+2);if(!W||!Y||!j)return null;return{rootSessionId:W,agentId:Y,teamTaskId:j}}function _5($){if(o8($))return null;let Z="__",Q=$.indexOf(Z);if(Q<=0)return null;let W=$.slice(0,Q),J=$.slice(Q+Z.length);if(!W||!J)return null;return{rootSessionId:W,agentId:J}}function P7($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let Z=String($.reason??"").toLowerCase();if(Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt"))return"cancelled";if(Z.includes("fail")||Z.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as o}from"zod";var nq=o.enum(gZ),N0=o.object({version:o.literal(1),session_id:o.string().min(1),source:o.string().min(1),pid:o.number().int(),started_at:o.string().min(1),ended_at:o.string().min(1).optional(),exit_code:o.number().int().nullable().optional(),status:nq,interactive:o.boolean(),provider:o.string().min(1),model:o.string().min(1),cwd:o.string().min(1),workspace_root:o.string().min(1),team_name:o.string().min(1).optional(),enable_tools:o.boolean(),enable_spawn:o.boolean(),enable_teams:o.boolean(),prompt:o.string().optional(),metadata:o.record(o.string(),o.unknown()).optional(),messages_path:o.string().min(1).optional()});function QH($){if(!$)return!1;return Object.values($).some((Z)=>typeof Z==="function")}function b7($,Z){let Q=[...$??[],...Z??[]];if(Q.length===0)return;let W=[],J=new Set;for(let X of Q){if(J.has(X.name))continue;J.add(X.name),W.push(X)}return W}function WH($){return JSON.stringify($,(Z,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function D1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function S7($,Z){let Q={...$};Q.id=D1(Q.id)??eq();let W=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,J={id:D1(W?.id)??D1(Q.modelId)??D1(Z?.id),provider:D1(W?.provider)??D1(Q.providerId)??D1(Z?.provider),family:D1(W?.family)??D1(Z?.family)};if(delete Q.providerId,delete Q.modelId,J.id&&J.provider)Q.modelInfo={id:J.id,provider:J.provider,...J.family?{family:J.family}:{}};else delete Q.modelInfo;return Q}function z5($){return $.map((Z)=>S7(Z))}function T5($,Z,Q=[]){let W=$.map((V,H)=>{let B=Q[H],K=B?.role===V.role&&JSON.stringify(B.content)===JSON.stringify(V.content)?{...B,...V}:{...V};return S7(K)}),J=Q.length,X=[];for(let V=J;V<W.length;V+=1)if(W[V]?.role==="assistant")X.push(V);if(X.length===0){let V=[...W].reverse().findIndex((H)=>H.role==="assistant");if(V===-1)return W;X.push(W.length-1-V)}let Y=X[X.length-1],j=X.some((V)=>W[V]?.metrics);for(let V of X){let H=W[V],B=H.metrics;if(!B&&V===Y&&!j){let G=Z.usage;B={inputTokens:G.inputTokens,outputTokens:G.outputTokens,cacheReadTokens:G.cacheReadTokens??0,cacheWriteTokens:G.cacheWriteTokens??0,cost:G.totalCost}}W[V]={...S7(H,{id:Z.model.id,provider:Z.model.provider,family:Z.model.info?.family}),...B?{metrics:B}:{},ts:H.ts??Z.endedAt.getTime()}}return W}function t8($){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 $M=120;function I$($){let Z=$?.trim();return Z?Z.slice(0,$M):void 0}function y7($){let Z=tq($??"").trim();if(!Z)return;return I$(Z.split(`
453
+ `)[0]?.trim())}function i1($){if(!$)return;let Z={...$},Q=I$(typeof Z.title==="string"?Z.title:void 0);if(Q)Z.title=Q;else delete Z.title;return Object.keys(Z).length>0?Z:void 0}function e8($){let Z=i1($.metadata)??{},Q=$.title!==void 0?I$($.title):y7($.prompt);if(Q)Z.title=Q;return Object.keys(Z).length>0?Z:void 0}function h7($){let Z=o8($);if(Z)return{agent:"teammate",sessionId:Z.rootSessionId,taskType:"team"};let Q=_5($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function k7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:z5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function JH($,Z,Q){aq(oq($),{recursive:!0}),sq($,`${JSON.stringify(k7({updatedAt:Z,context:Q,messages:[]}),null,2)}
454
+ `,"utf8")}function XH($,Z){return N0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:Z?.endedAt??$.endedAt??void 0,exit_code:Z?.exitCode??$.exitCode??void 0,status:Z?.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:Z?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function YH($,Z,Q){let W=0;while(!0){let J=await $();if(J===void 0)return{updated:!1};let X=await Z(J);if(typeof X==="object"&&X!==null&&"updated"in X&&X.updated===!1){if(W+=1,W>=Q)return X;continue}return X}}import{existsSync as ZM}from"node:fs";import{readFile as QM}from"node:fs/promises";import{formatDisplayUserInput as jH}from"@cline/shared";class $4{listeners=new Set;subscribe($,Z){let Q={listener:$,sessionId:Z?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let Z=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==Z)continue;Q.listener($)}}get size(){return this.listeners.size}}async function n1($){let Z=$?.trim();if(!Z||!ZM(Z))return[];try{let Q=(await QM(Z,"utf8")).trim();if(!Q)return[];let W=JSON.parse(Q);if(Array.isArray(W))return VH(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let J=W.messages;if(Array.isArray(J))return VH(J)}return[]}catch{return[]}}function WM($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:jH($.content)};return{...$,content:$.content.map((Z)=>{if(Z.type!=="text"||typeof Z.text!=="string")return Z;return{...Z,text:jH(Z.text)}})}}function VH($){return $.map(WM)}function I7($){return $?{...$}:void 0}async function HH($,Z){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await Z.queueSpawnRequest($);let W=await Z.upsertSubagentSessionFromHook($);if(!W)return;await Z.appendSubagentHookAudit(W,$),await Z.applySubagentStatus(W,$)}function Z4($){if(typeof $!=="string")return;let Z=$.trim();return Z.length>0?Z:void 0}function x0($){let Z=Z4($);if(!Z)return;return Z.toLowerCase()==="unknown"?void 0:Z}function O5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function jM($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function g7($){let Z=$??200;return Number.isFinite(Z)?Math.max(0,Math.floor(Z)):200}function VM($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function HM($){return $.isSubagent!==!0&&!Z4($.parentSessionId)}function BM($){let Z=$.match(/\d{13,}/g);if(!Z||Z.length===0)return 0;let Q=0;for(let W of Z){let J=Number.parseInt(W,10);if(Number.isFinite(J)&&J>Q)Q=J}return Q}function m7($){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 GM($){let Z=g7($);if(Z===0)return[];let Q=FH(),J=(await JM(Q,{withFileTypes:!0}).catch(()=>[])).filter((Y)=>Y.isDirectory()).map((Y)=>({entry:Y,recency:BM(Y.name.trim())})).sort((Y,j)=>j.recency-Y.recency||j.entry.name.localeCompare(Y.entry.name));return(await Promise.all(J.map(async({entry:Y})=>{let j=Y.name.trim();if(!j)return;let V=KH(Q,j,`${j}.json`),H=await GH(V,"utf8").catch(()=>{return});if(!H)return;let B;try{B=JSON.parse(H)}catch{return}let G=N0.safeParse(B);if(!G.success)return;return m7(G.data)}))).filter((Y)=>Boolean(Y)).sort((Y,j)=>j.startedAt.localeCompare(Y.startedAt)).slice(0,Z)}async function KM($,Z,Q){let W=g7(Z);if(W===0)return await $.listSessions(0),[];let J=Q.includeSubagents?W:VM(W),X=await $.listSessions(J);return(Q.includeSubagents?X:X.filter(HM)).slice(0,W)}function FM($){if(typeof $==="string")return $.trim();let Z=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let W=Q;if(W.type!=="text")continue;let J=W.text?.trim();if(J)Z.push(J)}return Z.join(`
455
+ `).trim()}function BH($){return $.replace(/\s+/g," ").trim()}function AM($,Z){if($.length<=Z)return $;return`${$.slice(0,Math.max(0,Z-3)).trimEnd()}...`}function fM($){for(let Z of["user","assistant"])for(let Q of $){if(Q.role!==Z)continue;let W=BH(FM(Q.content));if(!W)continue;let J=Z==="user"?BH(XM(W)):W,X=YM(J.split(`
456
+ `)[0]??J);return AM(X,50)}return}function UM($){let Z=0;for(let Q of $)Z+=O5(Q.metrics?.cost)??0;return Z}function DM($){let Z,Q;for(let W=$.length-1;W>=0;W-=1){let J=$[W];if(!Z)Z=x0(J.modelInfo?.provider);if(!Q)Q=x0(J.modelInfo?.id);if(Z&&Q)break}return{provider:Z,model:Q}}function LM($){return x0($?.provider)??x0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function _M($){return x0($?.model)??x0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function x7($,Z){let Q=jM($.metadata),W=Z4(Z?.title)??Z4(Q?.title),J=O5(Z?.totalCost)??O5(Q?.totalCost),X=Q||W!==void 0||J!==void 0?{...Q??{},...W!==void 0?{title:W}:{},...J!==void 0?{totalCost:J}:{}}:void 0;return{...$,provider:x0(Z?.provider)??x0($.provider)??LM(Q)??"",model:x0(Z?.model)??x0($.model)??_M(Q)??"",metadata:X}}function zM($){let Z=$.content;if(!Array.isArray(Z))return!1;return Z.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function TM($,Z){if($.status!=="running"||$.interactive!==!0)return!1;let Q=Z.at(-1);return Q?.role==="assistant"&&!zM(Q)}async function OM($,Z){return await Promise.all(Z.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let W=await $.readSessionMessages(Q.sessionId);return TM(Q,W)?{...Q,status:"idle"}:Q}))}async function qM($,Z){return await Promise.all(Z.map(async(Q)=>{let W=x7(Q),J=Boolean(Z4(W.metadata?.title)),X=Boolean(x0(W.provider)),Y=Boolean(x0(W.model)),j=O5(W.metadata?.totalCost),V=j!==void 0&&j>0;if(J&&X&&Y&&V)return W;let H=await $.readSessionMessages(Q.sessionId);if(H.length===0)return W;let B=DM(H),G=UM(H);return x7(Q,{title:J?void 0:fM(H),provider:X?void 0:B.provider,model:Y?void 0:B.model,totalCost:V||G<=0?void 0:G})}))}async function v7($,Z={}){let Q=g7(Z.limit),W=Z.includeSubagents===!0,J=await KM($,Q,{includeSubagents:W}),X=Z.includeManifestFallback===!0&&J.length<Q?await GM(Math.min(Math.max(Q*2,100),500)):[],Y=new Map;for(let H of[...J,...X]){if(Y.has(H.sessionId))continue;Y.set(H.sessionId,H)}let j=X.length===0?J:Array.from(Y.values()).sort((H,B)=>B.startedAt.localeCompare(H.startedAt)).slice(0,Q),V=await OM($,j);if(Z.hydrate===!1)return V.map((H)=>x7(H));return await qM($,V)}async function MM($){let Z=$.trim();if(!Z)return;let Q=KH(FH(),Z,`${Z}.json`),W=await GH(Q,"utf8").catch(()=>{return});if(!W)return;try{let J=N0.safeParse(JSON.parse(W));return J.success?J.data.messages_path:void 0}catch{return}}async function RM($,Z={}){let Q=new Map;return await v7({listSessions:async(J)=>{let X=await $.listSessions(J);Q.clear();for(let Y of X)Q.set(Y.sessionId,Y);return X.map(t8)},readSessionMessages:async(J)=>{let X=Q.get(J)?.messagesPath??await MM(J);return await n1(X)}},Z)}import{captureSdkError as aG}from"@cline/shared";import{createSessionId as ER,isHubProtocolCompatible as NR,resolveClineBuildEnv as wR,resolveHubCommandTimeoutMs as CR}from"@cline/shared";import{spawn as QR}from"node:child_process";import{closeSync as WR,mkdirSync as JR,openSync as XR}from"node:fs";import{basename as YR,dirname as jR,join as VR}from"node:path";import{fileURLToPath as HR}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as BR,isHubDaemonProcess as wH,isHubProtocolCompatible as GR,resolveClineBuildEnv as CH,withResolvedClineBuildEnv as KR}from"@cline/shared";import{createHash as EM,randomBytes as NM}from"node:crypto";import{existsSync as wM}from"node:fs";import{chmod as CM,mkdir as c7,readFile as LH,rm as u7,writeFile as _H}from"node:fs/promises";import{dirname as zH,join as d7}from"node:path";import{resolveClineDataDir as W4,resolveClineDir as Pd}from"@cline/shared/storage";var fH="0.0.55";var Q4={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:fH,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var PM="CLINE_HUB_DISCOVERY_PATH",SM="CLINE_HUB_BUILD_ID",UH=30000,bM=15000,yM=100;function hM($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function kM($){return EM("sha256").update($).digest("hex").slice(0,12)}function IM($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(Z){return Z instanceof Error&&"code"in Z?String(Z.code)==="EPERM":!1}}function TH(){return NM(32).toString("hex")}function xM($){return new Promise((Z)=>setTimeout(Z,$))}function gM($){return`${$}.lock`}async function mM($){try{let Z=JSON.parse(await LH(d7($,"owner.json"),"utf8"));if(typeof Z.pid!=="number"||typeof Z.acquiredAt!=="string")return;return{pid:Z.pid,acquiredAt:Z.acquiredAt}}catch{return}}async function DH($){await u7($,{recursive:!0,force:!0}).catch(()=>{return})}function OH(){return process.env[SM]?.trim()||String(Q4.version)}function x$($=process.argv[1]?.trim()||process.cwd()){let Z=`hub-${kM($)}`,Q=process.env[PM]?.trim()||d7(W4(),"locks","hub","owners",`${hM(Z)}.json`);return{ownerId:Z,discoveryPath:Q}}function bd($=`hub-${Date.now().toString(36)}`){return x$($)}async function A0($){try{let Z=JSON.parse(await LH($,"utf8"));if(typeof Z.hubId!=="string"||typeof Z.protocolVersion!=="string"||typeof Z.authToken!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string"||typeof Z.startedAt!=="string"||typeof Z.updatedAt!=="string")return;return{hubId:Z.hubId,protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,authToken:Z.authToken,host:Z.host,port:Z.port,url:Z.url,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:Z.startedAt,updatedAt:Z.updatedAt}}catch{return}}async function qH($,Z){await c7(zH($),{recursive:!0}),await u7($,{force:!0}).catch(()=>{return}),await _H($,`${JSON.stringify(Z,null,2)}
457
+ `,{encoding:"utf8",mode:384}),await CM($,384)}async function a0($){await u7($,{force:!0}).catch(()=>{return})}async function MH($,Z){let Q=gM($);await c7(zH(Q),{recursive:!0});let W=Date.now()+bM;while(!0)try{await c7(Q,{recursive:!1}),await _H(d7(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
458
+ `,"utf8");try{return await Z()}finally{await DH(Q)}}catch(J){if((J instanceof Error&&"code"in J?String(J.code):"")!=="EEXIST")throw J;let Y=await mM(Q),j=Y?Date.now()-Date.parse(Y.acquiredAt):UH+1;if(!Y||!IM(Y.pid)||j>UH){await DH(Q);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${Q}`);await xM(yM)}}async function g$($,Z){try{let Q=await fetch(Z?.authToken?vM($):RH($),{headers:Z?.authToken?{authorization:`Bearer ${Z.authToken}`}:void 0});if(!Q.ok)return;let W=await Q.json();if(typeof W.protocolVersion!=="string"||typeof W.host!=="string"||typeof W.port!=="number"||typeof W.url!=="string")return;return{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((J)=>typeof J==="string"):void 0,coreVersion:typeof W.coreVersion==="string"?W.coreVersion:void 0,buildId:typeof W.buildId==="string"?W.buildId:void 0,host:W.host,port:W.port,url:W.url,hubId:typeof W.hubId==="string"?W.hubId:void 0,authToken:typeof W.authToken==="string"?W.authToken:void 0,pid:typeof W.pid==="number"?W.pid:void 0,startedAt:typeof W.startedAt==="string"?W.startedAt:void 0,updatedAt:typeof W.updatedAt==="string"?W.updatedAt:void 0}}catch{return}}function L1($,Z,Q="/hub"){return new URL(`ws://${$}:${Z}${Q}`).toString()}function RH($){let Z=new URL($);return Z.protocol=Z.protocol==="wss:"?"https:":"http:",Z.pathname="/health",Z.search="",Z.toString()}function vM($){let Z=new URL(RH($));return Z.pathname="/status",Z.toString()}function yd($){return wM($)}import{CLINE_HUB_DEV_PORT as cM,CLINE_HUB_PORT as uM,resolveClineBuildEnv as dM}from"@cline/shared";var lM="CLINE_HUB_HOST",pM="CLINE_HUB_PORT",rM="CLINE_HUB_PATHNAME",iM="127.0.0.1",nM=uM,aM="/hub";function EH($){return dM($)==="development"?cM:nM}function sM($={}){return($.env??process.env)[lM]?.trim()||iM}function q5($={}){let Q=($.env??process.env)[pM]?.trim();if(!Q)return EH($);let W=Number.parseInt(Q,10);if(!Number.isInteger(W)||W<1||W>65535)return EH($);return W}function oM($={}){return($.env??process.env)[rM]?.trim()||aM}function a1($={},Z={}){return{host:$.host??sM(Z),port:$.port??q5(Z),pathname:$.pathname??oM(Z)}}import{join as tM}from"node:path";var eM="shared:cline",$R="CLINE_HUB_DISCOVERY_PATH",ZR="hub-production";function vd($){let Z=b$($.trim());return x$(`workspace:${Z||$.trim()}`)}function _1($=eM){return x$($)}function s1(){return{ownerId:ZR,discoveryPath:process.env[$R]?.trim()||tM(W4(),"locks","hub","production.json")}}var FR=8000,AR=200,fR=3000,UR=100,DR=[100,250,500,1000,2000],LR="--cline-hub-daemon";function _R($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function zR(){try{let $=VR(W4(),"logs","hub-daemon.log");return JR(jR($),{recursive:!0}),{fd:XR($,"a"),logPath:$}}catch{return}}function PH(){return CH()==="production"?s1():_1()}function m$($){return GR($).compatible}function NH($,Z,Q){if(!Z||Z.url!==Q)return $;return{...$,authToken:$.authToken??Z.authToken,pid:$.pid??Z.pid}}async function v$($,Z){try{return await g$($,{authToken:Z})}catch{return}}async function TR($,Z){let Q=Date.now()+Z;while(Date.now()<Q){if(!(await v$($))?.url)return!0;await new Promise((J)=>setTimeout(J,UR))}return!1}async function M5($,Z){if(await l7($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await TR($.url,fR);return await a0(Z).catch(()=>{return}),Q}async function J4($,Z){if(m$($))return!0;return M5($,Z)}async function SH($){if(CH()!=="production")return;let Z=_1();if(Z.discoveryPath===$.discoveryPath)return;let Q=await A0(Z.discoveryPath);if(Q?.url)await M5(Q,Z.discoveryPath);else await a0(Z.discoveryPath).catch(()=>{return})}function OR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return HR(new URL(`./entry.${$}`,import.meta.url))}function qR($,Z){let Q=OR(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let J=YR(W).toLowerCase().includes("bun"),X=Q.startsWith("/$bunfs/"),Y=J&&Q.toLowerCase().endsWith(".ts"),j=X?[LR]:[...Y?["--conditions=development"]:[],Q];return{launcher:W,args:[...j,"--cwd",$,..._R(Z)],cwd:$,env:{...KR(process.env),CLINE_NO_INTERACTIVE:"1",[BR]:"1"}}}function MR($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function RR($,Z={}){if(wH())return;let Q=qR($,Z),W=zR();try{QR(Q.launcher,Q.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(W)WR(W.fd)}}async function R5($,Z={}){for(let Q=0;;Q++)try{RR($,Z);return}catch(W){let J=DR[Q];if(!MR(W)||J===void 0)throw W;await new Promise((X)=>setTimeout(X,J))}}function bH($,Z={}){if(wH())return;let Q=PH(),W=a1(Z),J=L1(W.host,W.port,W.pathname),X=Z.allowPortFallback===!0&&W.port!==0;SH(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(Y)=>{let j=!1;if(Y?.url)if(!Y.authToken){if(j=!0,!await M5(Y,Q.discoveryPath)&&!X)return}else{let B=await v$(Y.url,Y.authToken);if(B?.url&&m$(B)&&await o1(B.url,{authToken:Y.authToken}))return;if(B?.url)await J4({...B,authToken:Y.authToken},Q.discoveryPath);else await a0(Q.discoveryPath).catch(()=>{return})}let V=await v$(J);if(V?.url){if(m$(V)){if(!X||!j)return}else if(!await J4({...V,authToken:void 0},Q.discoveryPath)&&!X)return}let H=X?{...W,port:0}:W;await R5($,H)}).catch(()=>{})}async function od($,Z={}){let Q=PH(),W=Z.host!==void 0||Z.port!==void 0||Z.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=a1(Z),X=L1(J.host,J.port,J.pathname),Y=(F)=>{if(!W)k2(F.url,F.authToken);return F};await SH(Q).catch(()=>{return});let j=await A0(Q.discoveryPath),V=!1;if(j?.url){let F=j.authToken;if(!F)V=!0,await M5(j,Q.discoveryPath);else{let A=await v$(j.url,F);if(A?.url&&m$(A)&&await o1(A.url,{authToken:F}))return Y({url:A.url,authToken:F});if(A?.url)await J4({...A,authToken:F},Q.discoveryPath);else await a0(Q.discoveryPath).catch(()=>{return})}}let H=await v$(X);if(H?.url){let F=NH(H,j,X);if(m$(H))throw Error(`A compatible Cline Hub is already running at ${X}, 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 J4(F,Q.discoveryPath)&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is already running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let G=Z.allowPortFallback===!0&&J.port!==0?{...J,port:0}:J;await R5($,G);let K=Date.now()+FR;while(Date.now()<K){let F=await A0(Q.discoveryPath);if(F?.url&&F.authToken){let L=await v$(F.url,F.authToken);if(L?.url&&m$(L)&&await o1(L.url,{authToken:F.authToken}))return Y({url:L.url,authToken:F.authToken})}let A=await v$(X);if(A?.url&&!m$(A)){let L=NH(A,F,X);if(!await J4(L,Q.discoveryPath)&&Z.allowPortFallback!==!0&&J.port!==0)throw Error(`An incompatible Cline Hub is still running at ${X} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((L)=>setTimeout(L,AR))}throw Error("Timed out waiting for detached hub startup.")}function N5(){return wR()==="production"?s1():_1()}function PR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function xH($){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((Z)=>Buffer.from(Z))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return xH($.data);return String($)}function SR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function yH($){let Z=$,Q=SR(Z.reason);return new g0("hub_connection_closed",Z.code||Q?`Hub connection closed (code=${Z.code??0}${Q?`, reason=${Q}`:""})`:p7,{closeCode:Z.code,closeReason:Q||void 0})}function bR($,Z){if($ instanceof g0)return $;if($ instanceof Error)return new g0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new g0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new g0("hub_connect_failed",Q);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new g0("hub_connect_failed",W?`Failed to connect to hub at ${Z.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${Z.toString()}.`)}var yR=8000,hR=200,hH="*",kH=8000,kR="cline-hub-auth.",gH=new Map,mH=new Set,IR=3000,xR=3000,gR=100,p7="Hub connection closed",mR=250,vR=5000,IH=0.5;class g0 extends Error{code;details;constructor($,Z,Q){super(Z);this.code=$;this.details=Q;this.name="HubTransportError"}}function cR($){return $ instanceof g0}class E5 extends Error{command;code;constructor($,Z,Q){super(Q);this.command=$;this.code=Z;this.name="HubCommandError"}}function vH($,Z){return $ instanceof E5&&$.code==="hub_command_timeout"&&(Z===void 0||$.command===Z)}function cH($){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;let Q=n7($.toString());return Q?gH.get(Q):void 0}function uR($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function n7($){if(!uR($))return;let Z=new URL(I2($));return Z.search="",Z.hash="",Z.toString()}function r7($){let Z=n7($);return!!Z&&mH.has(Z)}function k2($,Z){let Q=n7($);if(Q){if(mH.add(Q),Z?.trim())gH.set(Q,Z)}return $}class z1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new g0("hub_connection_closed",p7);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),Z=this.options.authToken?.trim()||cH($);$.hash="";let W=new(PR())($.toString(),Z?[`${kR}${Z}`]:void 0);this.socket=W;let J=!1;this.connectPromise=new Promise((X,Y)=>{let j=!1,V=setTimeout(()=>{if(j)return;j=!0,J=!0,this.lastCloseError=new g0("hub_connect_timeout",`Timed out connecting to hub after ${kH}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}Y(this.lastCloseError)},kH);W.addEventListener("open",()=>{if(j)return;j=!0,clearTimeout(V),X()}),W.addEventListener("error",(H)=>{if(j)return;j=!0,clearTimeout(V),this.lastCloseError=bR(H,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)}),W.addEventListener("close",(H)=>{if(j)return;if(j=!0,clearTimeout(V),!J)this.lastCloseError=yH(H),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,Y(this.lastCloseError)})}),W.addEventListener("message",(X)=>{this.handleFrame(JSON.parse(xH(X)))}),W.addEventListener("close",(X)=>{if(this.socket!==W)return;if(!J)this.lastCloseError=yH(X),this.sawSocketClose=!0;this.registered=!1;for(let Y of this.pendingReplies.values())Y.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 X of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(X));this.reconnectAttempt=0}subscribe($,Z){let Q=Z?.sessionId?.trim()||void 0,W={listener:$,sessionId:Q};return this.listeners.add(W),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(Q,-1)}}async command($,Z,Q,W){let J=0,X=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,Z,Q,W)}catch(Y){if(!X||J>=1||!await this.recoverLocalHubTransport(Y))throw Y;J+=1}}async commandOnce($,Z,Q,W){await this.connect();let J=ER("hubreq_"),X=CR($,W?.timeoutMs),Y=new Promise((V,H)=>{let B=X===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(J))return;H(new E5($,"hub_command_timeout",`Hub command ${$} timed out after ${X}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.`))},X);this.pendingReplies.set(J,{resolve:(G)=>{if(B)clearTimeout(B);V(G)},reject:(G)=>{if(B)clearTimeout(B);H(G)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:J,clientId:this.clientId,sessionId:Q,timeoutMs:X,payload:Z}})}catch(V){throw this.pendingReplies.delete(J),V}let j=await Y;if(!j.ok){if(j.error?.code===c8){let V=Q??(typeof Z?.sessionId==="string"?Z.sessionId:void 0);throw new P$(V,j.error.message)}throw new E5($,j.error?.code,j.error?.message??`Hub command ${$} failed`)}return j}async recoverLocalHubTransport($){if(!r7(this.currentUrl)||!cR($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let Z=await X4({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!Z)return!1;return this.currentUrl=Z,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(mR*2**this.reconnectAttempt,vR),Z=Math.round($*(1-IH)+Math.random()*$*IH);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},Z)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!r7(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await X4({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 g0("hub_connection_closed",p7),this.sawSocketClose=!1;for(let Z of this.pendingReplies.values())Z.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 g0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,Z){this.sendFrame({kind:$,clientId:this.clientId,...Z?{sessionId:Z}:{}})}adjustSubscriptionCount($,Z){let Q=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(Q)??0)+Z;if(W<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(Z<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,W),Z>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??hH}subscriptionSessionIdFromKey($){return $===hH?void 0:$}handleFrame($){switch($.kind){case"reply":{let Z=$.envelope.requestId;if(!Z)return;let Q=this.pendingReplies.get(Z);if(!Q)return;this.pendingReplies.delete(Z),Q.resolve($.envelope);return}case"event":for(let Z of this.listeners){if(Z.sessionId&&Z.sessionId!==$.envelope.sessionId?.trim())continue;Z.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function I2($){let Z=new URL($);if(Z.protocol==="http:")Z.protocol="ws:";else if(Z.protocol==="https:")Z.protocol="wss:";return Z.toString()}async function o1($,Z){let Q=new z1({url:$,authToken:Z?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function i7($,Z){let Q=I2($),W=await g$(Q,{authToken:Z?.authToken});if(!W)return{status:"unreachable",url:Q};if(!NR(W).compatible)return{status:"protocol_mismatch",url:Q};if(Z?.verifyConnection===!0&&!await o1(Q,{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,authToken:Z.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function dR($){let Z=Date.now()+yR;while(Date.now()<Z){let Q=await A0($.discoveryPath);if(Q?.url){let W=await i7(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(W.status==="compatible")return k2(W.url,Q.authToken)}await new Promise((W)=>setTimeout(W,hR))}return}async function lR($){let Z=Date.now()+xR;while(Date.now()<Z){if(!(await g$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,gR))}return!1}function pR($,Z){try{return I2($)===I2(Z)}catch{return!1}}function rR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let W=Q;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function iR($,Z,Q){let W=new z1({url:$,authToken:Z,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let J=await W.command("session.list",{limit:500},void 0,{timeoutMs:IR});return!rR(J.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function a7($={}){if($.endpoint?.trim()){let J=await i7($.endpoint);return J.status==="compatible"?J.url:void 0}let Z=N5(),Q=await A0(Z.discoveryPath);if(!Q?.url)return;let W=await i7(Q.url,{authToken:Q.authToken});if(W.status==="compatible")return k2(W.url,Q.authToken);if(W.status==="protocol_mismatch")await a0(Z.discoveryPath).catch(()=>{return});return}async function X4($={}){let Z=await a7($);if(Z&&await o1(Z,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return Z;if($.endpoint?.trim())return;let Q=N5();return await R5($.workspaceRoot??process.cwd()),await dR(Q)}async function l7($,Z){let Q=new URL($),W=Z?.trim()||cH(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function nR($=N5()){let Z=await A0($.discoveryPath);if(!Z?.url)return!1;try{if(await l7(Z.url,Z.authToken))return!0}catch{}return!1}async function uH($){if(!r7($.url))return;let Z=N5(),Q=await A0(Z.discoveryPath);if(!Q?.url||!pR(Q.url,$.url))return;if(!await iR(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await nR())return;if(!await lR(Q.url))return;return await a0(Z.discoveryPath).catch(()=>{return}),await X4({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as dH,createSessionId as lH,HUB_CHECKPOINT_CAPABILITY as tR,HUB_COMPACTION_CAPABILITY as eR,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as $E,HUB_HOOK_CAPABILITY_PREFIX as ZE,HUB_MISTAKE_LIMIT_CAPABILITY as QE,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as WE,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as JE,isHubToolExecutorName as XE}from"@cline/shared";function aR($){return $?JSON.parse(JSON.stringify($)):void 0}function sR($){return $?JSON.parse(JSON.stringify($)):void 0}function oR($){let Z=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(Z?.history)?Z.history:[]).filter((Y)=>!!Y&&typeof Y==="object"&&!Array.isArray(Y)).flatMap((Y)=>{let j=typeof Y.ref==="string"?Y.ref.trim():"",V=Number(Y.createdAt),H=Number(Y.runCount);if(!j||!Number.isFinite(V)||!Number.isInteger(H))return[];return[{ref:j,createdAt:V,runCount:H,...Y.kind==="stash"||Y.kind==="commit"?{kind:Y.kind}:{}}]}),J=W.at(-1),X=$?.checkpointEnabled===!0?!0:void 0;if(!X&&W.length===0)return;return{...X?{enabled:X}:{},...J?{latest:J}:{},history:W}}function t1($){let{session:Z}=$,Q=aR(Z.metadata);return{version:1,sessionId:Z.sessionId,source:Z.source,status:Z.status,createdAt:Z.startedAt,updatedAt:Z.updatedAt,endedAt:Z.endedAt??null,exitCode:Z.exitCode??null,interactive:Z.interactive,workspace:{cwd:Z.cwd,root:Z.workspaceRoot},model:{providerId:Z.provider,modelId:Z.model},capabilities:{enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams},lineage:{...Z.parentSessionId?{parentSessionId:Z.parentSessionId}:{},...Z.parentAgentId?{parentAgentId:Z.parentAgentId}:{},...Z.agentId?{agentId:Z.agentId}:{},...Z.conversationId?{conversationId:Z.conversationId}:{},isSubagent:Z.isSubagent},...Z.teamName?{team:{name:Z.teamName}}:{},...Z.prompt?{prompt:Z.prompt}:{},...Q?{metadata:Q}:{},...Z.messagesPath?{artifacts:{messagesPath:Z.messagesPath}}:{},...$.messages?{messages:sR($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=oR(Q);return W?{checkpoint:W}:{}})()}}function s7($){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 x2($){if(!$)return;return JSON.parse(JSON.stringify($))}var YE=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function pH($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function rH($){if(!$)return;let{userInstructionService:Z,...Q}=$;return JSON.parse(JSON.stringify(Q))}function iH($){let Z=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof Z.agentId==="string"?Z.agentId:"",conversationId:typeof Z.conversationId==="string"?Z.conversationId:"",iteration:typeof Z.iteration==="number"?Z.iteration:0,metadata:Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:void 0}}function c$($,Z,Q){$.manifest.push(Z),$.handlers.set(Z.capabilityName,Q)}function nH($,Z){let Q={manifest:[],handlers:new Map};for(let J of Object.keys(Z.toolExecutors??{}).filter(XE)){let X=Z.toolExecutors?.[J];if(typeof X!=="function")continue;c$(Q,{kind:"toolExecutor",executor:J,capabilityName:`${WE}${J}`},async({payload:Y,abortSignal:j})=>{let V=Array.isArray(Y.args)?[...Y.args]:[],H={...iH(Y.context),signal:j};return{result:await X(...V,H)}})}for(let J of $?.extraTools??[])c$(Q,{kind:"tool",name:J.name,description:J.description,inputSchema:x2(J.inputSchema)??{},...J.lifecycle?{lifecycle:x2(J.lifecycle)}:{},capabilityName:`${$E}${J.name}`},async({payload:X,abortSignal:Y,progress:j})=>{let V={...iH(X.context),signal:Y};return{result:await J.execute(X.input,{...V,emitUpdate:(B)=>{j({update:B})}})}});let W=$?.hooks;if(W)for(let J of YE){let X=W[J];if(typeof X!=="function")continue;c$(Q,{kind:"hook",name:J,capabilityName:`${ZE}${J}`},async({payload:Y})=>({control:await X(Y.context)}))}if($?.compaction?.compact){let J=$.compaction.compact;c$(Q,{kind:"compaction",capabilityName:eR,config:pH($.compaction)},async({payload:X})=>({result:await J(X.context)}))}if($?.checkpoint?.createCheckpoint){let J=$.checkpoint.createCheckpoint;c$(Q,{kind:"checkpoint",capabilityName:tR,config:pH($.checkpoint)},async({payload:X})=>({result:await J(X.context)}))}if($?.onConsecutiveMistakeLimitReached){let J=$.onConsecutiveMistakeLimitReached;c$(Q,{kind:"mistakeLimit",capabilityName:QE},async({payload:X})=>({result:await J(X.context)}))}if($?.userInstructionService){let J=$.userInstructionService;c$(Q,{kind:"userInstructionService",capabilityName:JE},async()=>{return await J.start().catch(()=>{}),{snapshot:{records:{skill:J.listRecords("skill"),rule:J.listRecords("rule"),workflow:J.listRecords("workflow")},runtimeCommands:J.listRuntimeCommands()}}})}return Q}function tH($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let Z=$.message;if(typeof Z==="string"&&Z.trim())return Z.trim()}return}function jE($){return tH($)??"Capability request was cancelled."}function VE($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function HE($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function BE($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$,Q=typeof Z.inputTokens==="number"?Z.inputTokens:void 0,W=typeof Z.outputTokens==="number"?Z.outputTokens:void 0;if(Q===void 0||W===void 0)return;return{inputTokens:Q,outputTokens:W,cacheReadTokens:typeof Z.cacheReadTokens==="number"?Z.cacheReadTokens:0,cacheWriteTokens:typeof Z.cacheWriteTokens==="number"?Z.cacheWriteTokens:0,totalCost:typeof Z.totalCost==="number"?Z.totalCost:0}}function aH($){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 o7($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function e1($,Z){return o7($?.[Z])??0}function GE($){let Z=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,J=W?.teamRole==="teammate"||W?.teamRole==="lead"?W.teamRole:void 0;return{event:{type:"usage",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,inputTokens:e1(Z,"inputTokens"),outputTokens:e1(Z,"outputTokens"),cacheReadTokens:e1(Z,"cacheReadTokens"),cacheWriteTokens:e1(Z,"cacheWriteTokens"),cost:o7(Z?.totalCost),totalInputTokens:e1(Q,"inputTokens"),totalOutputTokens:e1(Q,"outputTokens"),totalCacheReadTokens:e1(Q,"cacheReadTokens"),totalCacheWriteTokens:e1(Q,"cacheWriteTokens"),totalCost:o7(Q?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:J}}function KE($){let Z=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??Z?.finishReason,W=HE(Q)?Q:Q==="failed"?"error":"completed",J=BE($?.usage??Z?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof Z?.text==="string"?Z.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof Z?.iterations==="number"?Z.iterations:0,usage:J}}function w5($,Z){return $.error?.message??`hub command failed: ${Z}`}function Y4($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function eH($){let Z=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof Z?.parentSessionId==="string"?Z.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof Z?.agentId==="string"?Z.agentId:void 0),parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,isSubagent:typeof Z?.isSubagent==="boolean"?Z.isSubagent:!1,source:typeof Z?.source==="string"?Z.source:T0.CORE,pid:typeof Z?.pid==="number"?Z.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:Y4($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:Y4($.status)==="completed"?0:Y4($.status)==="failed"?1:void 0,status:Y4($.status),interactive:Z?.interactive===!0,provider:typeof Z?.provider==="string"?Z.provider:"hub",model:typeof Z?.model==="string"?Z.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof Z?.teamName==="string"?Z.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??Z?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??Z?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??Z?.enableTeams===!0,prompt:typeof Z?.prompt==="string"?Z.prompt:void 0,metadata:Z,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof Z?.messagesPath==="string"?Z.messagesPath:void 0,hookPath:typeof Z?.hookPath==="string"?Z.hookPath:void 0}}function $$($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;return Z.version===1&&typeof Z.sessionId==="string"?JSON.parse(JSON.stringify(Z)):void 0}function FE($){let Z=$$($?.snapshot);if(Z)return s7(Z);let Q=$?.session;return Q?eH(Q):void 0}function sH($,Z,Q){let W=Q?.workspaceRoot?.trim()||Z.config.workspaceRoot||Z.config.cwd;return N0.parse({version:1,session_id:$,source:Z.source??T0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:Y4(Q?.status),interactive:Z.interactive===!0,provider:Z.config.providerId,model:Z.config.modelId,cwd:Q?.cwd?.trim()||Z.config.cwd,workspace_root:W,team_name:Z.config.teamName,enable_tools:Z.config.enableTools,enable_spawn:Z.config.enableSpawnAgent,enable_teams:Z.config.enableAgentTeams,prompt:Z.prompt?.trim()||void 0,metadata:Z.sessionMetadata&&Object.keys(Z.sessionMetadata).length>0?Z.sessionMetadata:void 0})}function oH($,Z){return N0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??Z.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class u${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new $4;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,Z){this.clientContext=Z,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:Z?.workspaceRoot,cwd:Z?.cwd},this.defaultCapabilities=O0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new z1({...this.clientOptions,url:$})}async replaceClient($){let Z=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(Z.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!vH($,"session.create"))return!1;let Z=await uH({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!Z)return!1;return await this.replaceClient(Z),!0}registerPlannedSession($,Z,Q){if(this.sessionCapabilities.set($,Z),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let Z=this.resolveCapabilities($),Q=nH($.localRuntime,Z),W=$.config.sessionId?.trim()||lH(),J=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:x2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??T0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:x2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,Z,Q.handlers);let X;try{X=await J()}catch(H){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(H)){this.registerPlannedSession(W,Z,Q.handlers);try{X=await J()}catch(B){throw this.cleanupPlannedSession(W),B}}else throw H}let Y=$$(X.payload?.snapshot),j=X.payload?.session,V=(Y?.sessionId??j?.sessionId)?.trim();if(!V)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(V!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(V,Z,Q.handlers);return{sessionId:V,manifest:Y?oH(Y,$):sH(V,$,j),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,J=W?this.resolveCapabilities(W):void 0,X=W?nH(W.localRuntime,J??{}):{manifest:[],handlers:new Map},Y=W?W.config.sessionId?.trim()||lH():void 0;if(Y&&J)this.sessionCapabilities.set(Y,J);if(Y&&X.handlers.size>0)this.sessionClientContributionHandlers.set(Y,X.handlers),this.ensureSessionSubscription(Y);let j;try{j=await this.client.command("session.restore",{sessionId:Z,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:x2({...W.config,sessionId:Y}),metadata:{...W.sessionMetadata??{},source:W.source??T0.CORE,provider:W.config.providerId,model:W.config.modelId,enableTools:W.config.enableTools,enableSpawn:W.config.enableSpawnAgent,enableTeams:W.config.enableAgentTeams,teamName:W.config.teamName,prompt:W.prompt,interactive:W.interactive===!0},runtimeOptions:{...X.manifest.length>0?{clientContributions:X.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:x2(W.toolPolicies)}:{}},Z)}catch(F){if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw F}if(!j.ok){let F=typeof j.payload?.error==="string"?j.payload.error:"session.restore failed";if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw Error(F)}let V=$$(j.payload?.snapshot),H=j.payload?.session,B=(V?.sessionId??H?.sessionId)?.trim();if(Q&&!B){if(Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);throw Error("Hub checkpoint restore returned no session id")}if(B&&Y&&B!==Y)this.sessionCapabilities.delete(Y),this.sessionClientContributionHandlers.delete(Y),this.disposeSessionSubscription(Y);if(B&&J)this.sessionCapabilities.set(B,J);if(B&&X.handlers.size>0)this.sessionClientContributionHandlers.set(B,X.handlers);if(B)this.ensureSessionSubscription(B);let G=Array.isArray(j.payload?.messages)?j.payload.messages:void 0,K=j.payload?.checkpoint;if(!K)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:B,startResult:B?{sessionId:B,manifest:V?oH(V,W??{}):sH(B,W??{},H),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:G,checkpoint:K}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[],prompt:Z.payload?.prompt,updated:Z.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let Z=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(Z.payload?.prompts)?Z.payload.prompts:[],prompt:Z.payload?.prompt,removed:Z.payload?.removed===!0}}async getAccumulatedUsage($){let Z=await this.client.command("session.get",{includeSnapshot:!0},$),Q=$$(Z.payload?.snapshot);if(Q){let Y=Q.usage?{...Q.usage}:void 0,j=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return Y||j?{usage:Y,aggregateUsage:j}:void 0}let W=Z.payload?.session,J=aH(W?.usage),X=aH(W?.aggregateUsage);return J||X?{usage:J,aggregateUsage:X}:void 0}async abort($,Z){await this.client.command("run.abort",{sessionId:$,reason:tH(Z)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,Z]of this.sessionSubscriptions){Z();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 Z;try{Z=await this.client.command("session.get",void 0,$)}catch(Q){if(S$(Q))return;throw Q}return FE(Z.payload)}async listSessions($=100){let Z=await this.client.command("session.list",{limit:$}),Q=Array.isArray(Z.payload?.snapshots)?Z.payload.snapshots.flatMap((J)=>{let X=$$(J);return X?[s7(X)]:[]}):[];if(Q.length>0)return Q;return(Z.payload?.sessions??[]).map(eH)}async listSettings($){let Z=await this.client.command("settings.list",rH($));if(!Z.ok)throw Error(w5(Z,"settings.list"));return Z.payload?.snapshot}async toggleSetting($){let Z=await this.client.command("settings.toggle",rH($));if(!Z.ok)throw Error(w5(Z,"settings.toggle"));return{snapshot:Z.payload?.snapshot,changedTypes:Array.isArray(Z.payload?.changedTypes)?Z.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,Z){let Q={...Z.metadata??{}};if(typeof Z.prompt==="string")Q.prompt=Z.prompt;if(typeof Z.title==="string")Q.title=Z.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let Z=$.trim();if(!Z)return[];let Q=await this.client.command("session.messages",{sessionId:Z},Z);if(!Q.ok)throw dH(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(w5(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:Z,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(w5(Q,"session.messages"));let W=Q.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,Z){return this.events.subscribe($,Z)}ensureSessionSubscription($){let Z=$.trim();if(!Z||this.sessionSubscriptions.has(Z))return;let Q=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:Z});this.sessionSubscriptions.set(Z,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let Z=$.trim();if(!Z)return;this.sessionSubscriptions.get(Z)?.(),this.sessionSubscriptions.delete(Z),this.agentDoneEmittedForCurrentRunBySession.delete(Z)}resolveCapabilities($){return O0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:KE($.payload)}})}handleHubEvent($){let Z=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!Z)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(Z);let Q=$$($.payload?.snapshot),W=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:Z,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:Z,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!Q&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:Z,payload:$.payload});return}case"usage.updated":{let Q=GE($.payload);this.events.emit({type:"agent_event",payload:{sessionId:Z,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:Z,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:Z,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=$$($.payload?.snapshot),W=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:Z,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:Z,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:Z,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:Z,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount,userImages:Q.userImages,userFiles:Q.userFiles}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=$$($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:Z,payload:{...$.payload,reason:W}}),Q?.interactive===!0&&j0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:Z,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,Z,Q){try{dH(this.telemetry,{component:"core",operation:$,error:Z,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let Z=$.sessionId?.trim();if(!Z)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",J=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let X=this.sessionClientContributionHandlers.get(Z)?.get(J);if(!X){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${J} in session ${Z}.`},Z).catch(()=>{});return}let Y=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},j=new AbortController;this.activeCapabilityAbortControllers.set(W,j);let V=(H)=>{this.client.command("capability.progress",{requestId:W,payload:H},Z).catch((B)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",B,$)})};try{let H=await X({payload:Y,abortSignal:j.signal,progress:V});if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:H},Z)}catch(H){if(j.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:H instanceof Error?H.message:String(H)},Z)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let Z=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!Z)return;let Q=this.activeCapabilityAbortControllers.get(Z);if(!Q)return;Q.abort(jE($.payload.error))}async handleApprovalRequested($){let Z=$.sessionId?.trim();if(!Z)return;let Q=this.sessionCapabilities.get(Z)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",X=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!J||!X)return;let Y=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},j=VE($.payload?.inputJson);this.pendingApprovalToolCallIds.add(J),this.emitToolCallContentStart({sessionId:Z,toolCallId:J,toolName:X,toolInput:j});let V=await Promise.resolve(Q({sessionId:Z,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:Z,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:J,toolName:X,input:j,policy:Y})).catch((H)=>({approved:!1,reason:H instanceof Error?H.message:`Tool approval request failed: ${String(H)}`}));await this.client.command("approval.respond",{approvalId:W,approved:V.approved,reason:V.reason},Z).catch(()=>{})}}class C5 extends u${constructor($){super({url:I2($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as AE,mkdirSync as fE}from"node:fs";import{join as UE}from"node:path";import{asBool as j4,asOptionalString as Q1,asString as T1,ensureSessionSchema as DE,loadSqliteDb as LE,nowIso as P5,toBoolInt as V4}from"@cline/shared/db";import{resolveDbDataDir as _E}from"@cline/shared/storage";class Z${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??_E()}init(){this.getRawDb()}ensureSessionsDir(){if(!AE(this.sessionsDirPath))fE(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return UE(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=LE(this.sessionDbPath());return DE($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,Z=[]){return this.getRawDb().prepare($).run(...Z)}queryOne($,Z=[]){return this.getRawDb().prepare($).get(...Z)??void 0}queryAll($,Z=[]){return this.getRawDb().prepare($).all(...Z)}create($){let Z=P5();this.run(`INSERT OR REPLACE INTO sessions (
459
459
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
460
460
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
461
461
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
462
462
  metadata_json, transcript_path, hook_path, messages_path, updated_at
463
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,V4($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,V4($.enableTools),V4($.enableSpawn),V4($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,V4($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,Z])}update($){let Z=[],Q=[];if($.endedAt!==void 0)Z.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)Z.push("exit_code = ?"),Q.push($.exitCode);if($.status!==void 0)Z.push("status = ?"),Q.push($.status);if($.prompt!==void 0)Z.push("prompt = ?"),Q.push($.prompt);if($.metadata!==void 0)Z.push("metadata_json = ?"),Q.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)Z.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.parentAgentId!==void 0)Z.push("parent_agent_id = ?"),Q.push($.parentAgentId);if($.agentId!==void 0)Z.push("agent_id = ?"),Q.push($.agentId);if($.conversationId!==void 0)Z.push("conversation_id = ?"),Q.push($.conversationId);if(Z.length===0)return;Z.push("updated_at = ?"),Q.push(C5()),Q.push($.sessionId),this.run(`UPDATE sessions SET ${Z.join(", ")} WHERE session_id = ?`,Q)}updateStatus($,Z,Q){this.update({sessionId:$,status:Z,endedAt:j0(Z)?null:C5(),exitCode:j0(Z)?null:Q??(Z==="failed"?1:0)})}get($){let Z=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
463
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,V4($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,V4($.enableTools),V4($.enableSpawn),V4($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,V4($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,Z])}update($){let Z=[],Q=[];if($.endedAt!==void 0)Z.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)Z.push("exit_code = ?"),Q.push($.exitCode);if($.status!==void 0)Z.push("status = ?"),Q.push($.status);if($.prompt!==void 0)Z.push("prompt = ?"),Q.push($.prompt);if($.metadata!==void 0)Z.push("metadata_json = ?"),Q.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)Z.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.parentAgentId!==void 0)Z.push("parent_agent_id = ?"),Q.push($.parentAgentId);if($.agentId!==void 0)Z.push("agent_id = ?"),Q.push($.agentId);if($.conversationId!==void 0)Z.push("conversation_id = ?"),Q.push($.conversationId);if(Z.length===0)return;Z.push("updated_at = ?"),Q.push(P5()),Q.push($.sessionId),this.run(`UPDATE sessions SET ${Z.join(", ")} WHERE session_id = ?`,Q)}updateStatus($,Z,Q){this.update({sessionId:$,status:Z,endedAt:j0(Z)?null:P5(),exitCode:j0(Z)?null:Q??(Z==="failed"?1:0)})}get($){let Z=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
464
464
  provider, model, cwd, workspace_root, team_name,
465
465
  enable_tools, enable_spawn, enable_teams,
466
466
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
467
467
  prompt, metadata_json, hook_path, messages_path, updated_at
468
- FROM sessions WHERE session_id = ?`,[$]);if(!Z)return;return{sessionId:z1(Z.session_id),source:z1(Z.source),pid:Number(Z.pid??0),startedAt:z1(Z.started_at),endedAt:Z.ended_at??null,exitCode:Z.exit_code??null,status:z1(Z.status),interactive:j4(Z.interactive),provider:z1(Z.provider),model:z1(Z.model),cwd:z1(Z.cwd),workspaceRoot:z1(Z.workspace_root),teamName:Q1(Z.team_name),enableTools:j4(Z.enable_tools),enableSpawn:j4(Z.enable_spawn),enableTeams:j4(Z.enable_teams),parentSessionId:Q1(Z.parent_session_id),parentAgentId:Q1(Z.parent_agent_id),agentId:Q1(Z.agent_id),conversationId:Q1(Z.conversation_id),isSubagent:j4(Z.is_subagent),prompt:Q1(Z.prompt),metadata:(()=>{let Q=Q1(Z.metadata_json);if(!Q)return;try{let W=JSON.parse(Q);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:Q1(Z.hook_path),messagesPath:Q1(Z.messages_path),updatedAt:Q1(Z.updated_at)??C5()}}list($=200){let Z=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let W of Z){let J=this.get(z1(W.session_id));if(J)Q.push(J)}return Q}delete($,Z=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Z)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}g2();import{existsSync as UW,mkdirSync as LN,readFileSync as UB,renameSync as _N,writeFileSync as zN}from"node:fs";import{join as DB}from"node:path";import{resolveSessionDataDir as TN}from"@cline/shared/storage";import{dirname as UN}from"node:path";import{nanoid as DN}from"nanoid";import{execFile as wE}from"node:child_process";import{promisify as CE}from"node:util";var PE=CE(wE);function t7($,Z){$?.log(Z,{severity:"warn"})}function SE($){let Z=$?.checkpoint;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let Q=Z;if(!Q.latest||!Array.isArray(Q.history))return;let W=Q.latest,J=Q.history.filter((X)=>!!X&&typeof X==="object"&&typeof X.ref==="string"&&typeof X.createdAt==="number"&&typeof X.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:J}}async function u$($,Z){let Q=await PE("git",["-C",$,...Z],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function e7($,Z){if(!$)return;let Q=`refs/cline/checkpoints/${Z}/`;try{let{stdout:W}=await u$($,["for-each-ref","--format=%(refname)",Q]),J=W.trim().split(`
469
- `).filter(Boolean);await Promise.allSettled(J.map((X)=>u$($,["update-ref","-d",X])))}catch{}}async function $B($,Z,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((W)=>u$($,["update-ref",`refs/cline/checkpoints/${Z}/${W.runCount}`,W.ref])))}function bE($,Z){let Q=$.findIndex((W)=>W.runCount===Z.runCount);if(Q<0)return[...$,Z];return $.map((W,J)=>J===Q?Z:W)}function ZB($){let Z=$.initialRunCount??0,Q,W=async()=>{if(Q!==void 0)return Q;try{Q=(await u$($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:Z});if(!await W())return;let X=async(H)=>{try{let G=(await u$($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:Z,kind:"commit"}}catch(B){t7($.logger,`${H}: ${B instanceof Error?B.message:String(B)}`);return}},Y=`cline checkpoint session=${$.sessionId} run=${Z}`,j="";try{j=(await u$($.cwd,["stash","create",Y])).stdout.trim()}catch(H){return t7($.logger,`Checkpoint snapshot failed: ${H instanceof Error?H.message:String(H)}`),X("Checkpoint HEAD fallback failed")}if(!j)return X("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${Z}`;try{await u$($.cwd,["update-ref",V,j])}catch(H){t7($.logger,`Checkpoint store failed: ${H instanceof Error?H.message:String(H)}`);return}return{ref:j,createdAt:Date.now(),runCount:Z,kind:"stash"}};return{beforeRun:async({snapshot:X})=>{if(X.parentAgentId!=null)return;Z+=1;return},beforeModel:async({snapshot:X})=>{if(X.parentAgentId!=null||X.iteration!==1||Z<1)return;let Y=await J();if(!Y)return;let j=await $.readSessionMetadata(),V=SE(j);if(V?.latest.ref===Y.ref)return;let H=bE(V?.history??[],Y);await $.writeSessionMetadata({...j??{},checkpoint:{latest:Y,history:H}});return}}}import{existsSync as S5,mkdirSync as yE,readdirSync as hE,rmdirSync as kE,rmSync as IE,unlinkSync as xE}from"node:fs";import{dirname as QB,join as P5}from"node:path";function $0(){return new Date().toISOString()}function H4($){if(!$||!S5($))return;try{xE($)}catch{}}function gE($){let Z=o8($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:`${Z.agentId}__${Z.teamTaskId}`};let Q=L5($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class $W{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return P5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Z=this.sessionArtifactsDir($);if(!S5(Z))yE(Z,{recursive:!0});return Z}sessionMessagesPath($){return P5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Z=!1){let Q=Z?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return P5(Q,`${$}.json`)}removeSessionDirIfEmpty($){let Z=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(Z.startsWith(Q)&&Z!==Q){if(!S5(Z)){Z=QB(Z);continue}try{if(hE(Z).length>0)break;kE(Z)}catch{break}Z=QB(Z)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!S5($))return;try{IE($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,Z,Q){let{rootSessionId:W,fileStem:J}=gE($),X=this.sessionArtifactsDir(W);return{messagesPath:P5(X,`${J}.messages.json`)}}}import{appendFileSync as mE,existsSync as vE,mkdirSync as WB,readFileSync as cE,writeFileSync as JB}from"node:fs";import{dirname as XB,join as uE}from"node:path";import{ensureHookLogDir as dE}from"@cline/shared/storage";class ZW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,Z,Q){this.adapter=$;this.messagesArtifactUploader=Z;this.logger=Q;this.artifacts=new $W(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,Z,Q){JH(Z,Q,h7($))}writeSessionManifest($,Z){WB(XB($),{recursive:!0}),JB($,`${JSON.stringify(N0.parse(Z),null,2)}
470
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let Z=this.artifacts.sessionManifestPath($,!1);if(!vE(Z))return{path:Z};try{return{path:Z,manifest:N0.parse(JSON.parse(cE(Z,"utf8")))}}catch{return{path:Z}}}async resolveArtifactPath($,Z,Q){let J=(await this.adapter.getSession($))?.[Z];return typeof J==="string"&&J.trim().length>0?J:Q($)}async persistSessionMessages($,Z,Q){let W=await this.resolveArtifactPath($,"messagesPath",(Y)=>this.artifacts.sessionMessagesPath(Y)),J=k7({updatedAt:$0(),context:h7($),messages:Z,systemPrompt:Q}),X=`${JSON.stringify(J,null,2)}
471
- `;if(WB(XB(W),{recursive:!0}),JB(W,X,"utf8"),!this.messagesArtifactUploader)return;try{let Y=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:X,row:Y})}catch(Y){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:Y})}}appendStaleSessionHookLog($,Z,Q,W,J){let Y=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??uE(dE(),"hooks.jsonl");mE(Y,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:Z,pid:Q,source:J})}
472
- `,"utf8")}}import{appendFileSync as lE}from"node:fs";import{join as pE}from"node:path";import{resolveRootSessionId as YB}from"@cline/shared";import{ensureHookLogDir as rE}from"@cline/shared/storage";import{z as QW}from"zod";var iE="subagent",nE=QW.looseObject({task:QW.string().optional(),systemPrompt:QW.string().optional()});class b5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,Z,Q,W){this.adapter=$;this.manifestStore=Z;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,Z){return`${$}::${Z}`}activeTeamTaskSessionId($,Z){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Z))?.at(-1)}buildSubsessionRow($,Z){return{sessionId:Z.sessionId,source:iE,pid:process.ppid,startedAt:Z.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:Z.parentSessionId,parentAgentId:Z.parentAgentId,agentId:Z.agentId,conversationId:Z.conversationId??null,isSubagent:!0,prompt:Z.prompt,metadata:e8({prompt:Z.prompt}),hookPath:"",messagesPath:Z.messagesPath,updatedAt:Z.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let Z=YB($.sessionContext);if(!Z)return;let Q=nE.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:Z,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let Z=$.rootSessionId;if(!Z)return;let Q=await this.adapter.getSession(Z);if(!Q)return;let W=D5(Z,$.agentId),J=await this.adapter.getSession(W),X=$0(),Y=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(Z,$.parentAgentId)),j=$.prompt??J?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest(Z,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:W,parentSessionId:Z,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:j,startedAt:X,...Y})),this.manifestStore.initializeMessagesFile(W,Y.messagesPath,X),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:Z,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??j??null,metadata:e8({metadata:J.metadata??void 0,prompt:J.prompt??j??null}),expectedStatusLock:J.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Z=YB($.sessionContext);if(!Z)return;if($.hookName==="session_shutdown"){let Q=D5(Z,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:Z})}async applySubagentStatus($,Z){await this.applySubagentStatusBySessionId($,P7(Z))}async applySubagentStatusBySessionId($,Z){let Q=await this.adapter.getSession($);if(!Q)return;let W=j0(Z)?null:$0(),J=j0(Z)?null:Z==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:Z,endedAt:W,exitCode:J,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,Z){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of Q)await this.applySubagentStatusBySessionId(W.sessionId,Z)}async onTeamTaskStart($,Z,Q){let W=await this.adapter.getSession($);if(!W)return;let J=C7($,Z),X=$0(),{messagesPath:Y}=this.manifestStore.artifacts.subagentArtifactPaths(J,Z);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:Z,prompt:Q||`Team task for ${Z}`,startedAt:X,messagesPath:Y})),this.manifestStore.initializeMessagesFile(J,Y,X);let j=this.teamTaskQueueKey($,Z),V=this.teamTaskSessionsByAgent.get(j)??[];V.push(J),this.teamTaskSessionsByAgent.set(j,V)}async onTeamTaskEnd($,Z,Q,W,J,X){let Y=this.teamTaskQueueKey($,Z),j=this.teamTaskSessionsByAgent.get(Y);if(!j||j.length===0)return;let V=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Y);if(!V)return;let H=J?.messages??X,B=this.toPersistedMessages(H,J,X);if(B)await this.manifestStore.persistSessionMessages(V,B);await this.applySubagentStatusBySessionId(V,Q),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,Z,Q,W){let J=this.teamTaskQueueKey($,Z),X=this.teamTaskSessionsByAgent.get(J)?.[0];if(!X)return;let Y=Q.trim();if(!Y)return;let j=W?.kind??"progress";if(j==="heartbeat"){let H=Date.now(),B=this.teamTaskLastHeartbeatBySession.get(X)??0;if(H-B<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(X,H)}let V=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Y}`:`[progress] ${Y}`;if(this.teamTaskLastProgressLineBySession.get(X)===V)return;this.teamTaskLastProgressLineBySession.set(X,V)}async handleSubAgentStart($,Z){let Q=await this.upsertSubagentSession({agentId:Z.subAgentId,parentAgentId:Z.parentAgentId,conversationId:Z.conversationId,prompt:Z.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,Z){let Q=await this.upsertSubagentSession({agentId:Z.subAgentId,parentAgentId:Z.parentAgentId,conversationId:Z.conversationId,prompt:Z.input.task,rootSessionId:$});if(!Q)return;if(Z.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let W=this.toPersistedMessages(Z.agentResult?.messages,Z.agentResult);if(W)await this.manifestStore.persistSessionMessages(Q,W);let J=Z.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??pE(rE(),"hooks.jsonl");lE(Q,`${JSON.stringify({ts:$0(),...$})}
473
- `,"utf8")}}import{formatUserInputBlock as fN}from"@cline/shared";import{existsSync as aE,readdirSync as sE,readFileSync as oE}from"node:fs";import{basename as jB,extname as tE,join as eE}from"node:path";import{resolveAgentConfigSearchPaths as $N}from"@cline/shared/storage";import HB from"yaml";import{z as O0}from"zod";var BB=O0.object({name:O0.string().trim().min(1),description:O0.string().trim().min(1),tools:O0.union([O0.string(),O0.array(O0.string())]).optional(),skills:O0.union([O0.string(),O0.array(O0.string())]).optional(),providerId:O0.string().trim().min(1).optional(),modelId:O0.string().trim().min(1).optional(),maxIterations:O0.number().int().positive().optional()});function ZN($){let Z=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!Z)throw Error("Missing YAML frontmatter block in agent config file.");let Q=Z[0].length,W=/^---[^\S\r\n]*(?:\r?\n|$)/gm;W.lastIndex=Q;let J,X=Array.from($.matchAll(W)).filter((Y)=>Y.index>=Q);for(let Y of X){let j=Y.index,V=$.slice(Q,j);try{let H=HB.parse(V);if(!H||typeof H!=="object"||Array.isArray(H))continue;BB.parse(H);let B=$.slice(j+Y[0].length);J={frontmatter:V,body:B}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function VB($){if($===void 0)return;let Z=Array.isArray($)?$:$.split(",");return Array.from(new Set(Z.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function QN($){return $.trim().toLowerCase()}function WN($){let Z=tE($).toLowerCase();return Z===".yml"||Z===".yaml"}function WW($,Z={}){let{frontmatter:Q,body:W}=ZN($),J=HB.parse(Q);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let X=BB.parse(J),Y=W.trim();if(!Y)throw Error("Missing system prompt body in agent config file.");return{name:X.name,description:X.description,tools:VB(X.tools),skills:VB(X.skills),providerId:X.providerId,modelId:X.modelId,maxIterations:X.maxIterations,systemPrompt:Y,path:Z.path}}function y5($){let Z=$.searchPaths??$N($.workspaceRoot),Q=new Map,W=[];for(let X of Z.filter(Boolean)){if(!aE(X))continue;let Y;try{Y=sE(X,{withFileTypes:!0})}catch(j){W.push({path:X,error:j instanceof Error?j:Error(String(j))});continue}for(let j of Y){if(!j.isFile()||!WN(j.name))continue;let V=eE(X,j.name);try{let H=oE(V,"utf8"),B=WW(H,{path:V}),G=QN(B.name);if(!Q.has(G))Q.set(G,B)}catch(H){W.push({path:V,error:H instanceof Error?H:Error(String(H))})}}}return{configs:Array.from(Q.values()).sort((X,Y)=>(X.path?jB(X.path):X.name).localeCompare(Y.path?jB(Y.path):Y.name)),errors:W}}import{createTool as JN,zodToJsonSchema as XN}from"@cline/shared";import{z as GB}from"zod";var JW="subagent_",h5=64,YN=GB.object({prompt:GB.string().trim().min(1).describe("Task for the subagent to perform")});function jN($){let Z="",Q=!0;for(let W of $.trim().toLowerCase()){let J=W.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||W==="_")||W==="_"){if(!Q)Z+="_",Q=!0;continue}Z+=W,Q=!1}return Q?Z.slice(0,-1):Z}function VN($){let Z=2166136261;for(let Q=0;Q<$.length;Q++)Z^=$.charCodeAt(Q),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}function XW($){let Z=jN($)||"agent",Q=VN($).slice(0,6),W=`${JW}${Z}`;if(W.length<=h5)return W;let J=h5-JW.length-Q.length-1,X=Z.slice(0,Math.max(1,J));return`${JW}${X}_${Q}`.slice(0,h5)}function YW($){let Z=new Set,Q=[];for(let W of[...$].sort((J,X)=>J.name.localeCompare(X.name))){let J=XW(W.name),X=J,Y=2;while(Z.has(X)){let j=`_${Y++}`,V=Math.max(1,h5-j.length);X=`${J.slice(0,V)}${j}`}Z.add(X),Q.push({toolName:X,config:W})}return Q}function HN($,Z){return{...$,providerId:Z.providerId??$.providerId,modelId:Z.modelId??$.modelId,maxIterations:Z.maxIterations??$.maxIterations}}function k5($){return YW($.agents).map(({toolName:Z,config:Q})=>{return JN({name:Z,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:XN(YN),execute:async(J,X)=>{let Y=$.configProvider.getRuntimeConfig(),j=R2(HN(Y,Q)),V=$.createSubAgentTools?await $.createSubAgentTools(Q,J,X):[],H=E2({kind:"subagent",prompt:Q.systemPrompt,configProvider:j,tools:V,maxIterations:Q.maxIterations,parentAgentId:X.agentId,abortSignal:X.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),B=H.getAgentId(),G=H.getConversationId(),K=X.agentId,F={systemPrompt:Q.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:B,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await H.run(J.prompt),L={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:G,parentAgentId:K,input:F,result:L,agentResult:A})}catch{}return L}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function W1(){return new Date().toISOString()}function KB($,Z){if(Z<=0)return 0;return Math.round($/Z*100)}function BN($,Z){let Q=new Set;for(let J of Z)if(J.status==="reviewed")Q.add(`${J.outcomeId}:${J.section}`);let W=new Set;for(let J of $){if(J.status==="finalized")continue;for(let X of J.requiredSections)if(!Q.has(`${J.id}:${X}`))W.add(`${J.id}:${X}`)}return[...W].sort((J,X)=>J.localeCompare(X))}function I5($,Z){let Q={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},X={draft:0,in_review:0,finalized:0},Y={draft:0,reviewed:0,rejected:0},j=0,V=0;for(let f of Z.members)if(Q[f.status]+=1,f.role==="lead")j+=1;else V+=1;let H=[],B=[],G=Z.tasks.filter((f)=>f.status==="completed").length,K=new Map(Z.tasks.map((f)=>[f.id,f]));for(let f of Z.tasks){if(W[f.status]+=1,f.status==="blocked"){H.push(f.id);continue}if(f.status!=="pending")continue;if(f.dependsOn.every((U)=>{return K.get(U)?.status==="completed"}))B.push(f.id)}let F=[],A,L=0;for(let f of Z.runs){if(J[f.status]+=1,f.status==="queued"||f.status==="running")F.push(f.id);let D=f.startedAt.getTime();if(D>=L)L=D,A=f.id}for(let f of Z.outcomes)X[f.status]+=1;for(let f of Z.outcomeFragments)Y[f.status]+=1;return{teamName:$,updatedAt:W1(),members:{total:Z.members.length,byStatus:Q,leadCount:j,teammateCount:V},tasks:{total:Z.tasks.length,byStatus:W,blockedTaskIds:H,readyTaskIds:B,completionPct:KB(G,Z.tasks.length)},runs:{total:Z.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:Z.outcomes.length,byStatus:X,finalizedPct:KB(X.finalized,Z.outcomes.length),missingRequiredSections:BN(Z.outcomes,Z.outcomeFragments)},fragments:{total:Z.outcomeFragments.length,byStatus:Y}}}function x5($){let{event:Z}=$;switch(Z.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.task.id,agentId:Z.task.assignee??Z.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:Z.type,ts:W1(),runId:Z.run.id,taskId:Z.run.taskId,agentId:Z.run.agentId,message:Z.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),runId:Z.run.id,taskId:Z.run.taskId,agentId:Z.run.agentId,message:Z.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),outcomeId:Z.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),outcomeId:Z.fragment.outcomeId,fragmentId:Z.fragment.id,agentId:Z.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.message.taskId,agentId:Z.message.fromAgentId,message:Z.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.entry.taskId,agentId:Z.entry.agentId,message:Z.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),agentId:Z.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1()}}import{sanitizeFileName as GN,TeamMessageType as y}from"@cline/shared";import{nanoid as KN}from"nanoid";import{TeamMessageType as Gp}from"@cline/shared";function jW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function FB($,Z){return $?.status==="stopped"&&jW(Z)}var FN=600000,AB="recovered_queued";function AN($){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.
468
+ FROM sessions WHERE session_id = ?`,[$]);if(!Z)return;return{sessionId:T1(Z.session_id),source:T1(Z.source),pid:Number(Z.pid??0),startedAt:T1(Z.started_at),endedAt:Z.ended_at??null,exitCode:Z.exit_code??null,status:T1(Z.status),interactive:j4(Z.interactive),provider:T1(Z.provider),model:T1(Z.model),cwd:T1(Z.cwd),workspaceRoot:T1(Z.workspace_root),teamName:Q1(Z.team_name),enableTools:j4(Z.enable_tools),enableSpawn:j4(Z.enable_spawn),enableTeams:j4(Z.enable_teams),parentSessionId:Q1(Z.parent_session_id),parentAgentId:Q1(Z.parent_agent_id),agentId:Q1(Z.agent_id),conversationId:Q1(Z.conversation_id),isSubagent:j4(Z.is_subagent),prompt:Q1(Z.prompt),metadata:(()=>{let Q=Q1(Z.metadata_json);if(!Q)return;try{let W=JSON.parse(Q);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:Q1(Z.hook_path),messagesPath:Q1(Z.messages_path),updatedAt:Q1(Z.updated_at)??P5()}}list($=200){let Z=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let W of Z){let J=this.get(T1(W.session_id));if(J)Q.push(J)}return Q}delete($,Z=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Z)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}g2();import{existsSync as UW,mkdirSync as ON,readFileSync as UB,renameSync as qN,writeFileSync as MN}from"node:fs";import{join as DB}from"node:path";import{resolveSessionDataDir as RN}from"@cline/shared/storage";import{dirname as zN}from"node:path";import{nanoid as TN}from"nanoid";import{execFile as bE}from"node:child_process";import{promisify as yE}from"node:util";var hE=yE(bE);function t7($,Z){$?.log(Z,{severity:"warn"})}function kE($){let Z=$?.checkpoint;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let Q=Z;if(!Q.latest||!Array.isArray(Q.history))return;let W=Q.latest,J=Q.history.filter((X)=>!!X&&typeof X==="object"&&typeof X.ref==="string"&&typeof X.createdAt==="number"&&typeof X.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:J}}async function d$($,Z){let Q=await hE("git",["-C",$,...Z],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function e7($,Z){if(!$)return;let Q=`refs/cline/checkpoints/${Z}/`;try{let{stdout:W}=await d$($,["for-each-ref","--format=%(refname)",Q]),J=W.trim().split(`
469
+ `).filter(Boolean);await Promise.allSettled(J.map((X)=>d$($,["update-ref","-d",X])))}catch{}}async function $B($,Z,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((W)=>d$($,["update-ref",`refs/cline/checkpoints/${Z}/${W.runCount}`,W.ref])))}function IE($,Z){let Q=$.findIndex((W)=>W.runCount===Z.runCount);if(Q<0)return[...$,Z];return $.map((W,J)=>J===Q?Z:W)}function ZB($){let Z=$.initialRunCount??0,Q,W=async()=>{if(Q!==void 0)return Q;try{Q=(await d$($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},J=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:Z});if(!await W())return;let X=async(H)=>{try{let G=(await d$($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!G)return;return{ref:G,createdAt:Date.now(),runCount:Z,kind:"commit"}}catch(B){t7($.logger,`${H}: ${B instanceof Error?B.message:String(B)}`);return}},Y=`cline checkpoint session=${$.sessionId} run=${Z}`,j="";try{j=(await d$($.cwd,["stash","create",Y])).stdout.trim()}catch(H){return t7($.logger,`Checkpoint snapshot failed: ${H instanceof Error?H.message:String(H)}`),X("Checkpoint HEAD fallback failed")}if(!j)return X("Checkpoint HEAD fallback failed");let V=`refs/cline/checkpoints/${$.sessionId}/${Z}`;try{await d$($.cwd,["update-ref",V,j])}catch(H){t7($.logger,`Checkpoint store failed: ${H instanceof Error?H.message:String(H)}`);return}return{ref:j,createdAt:Date.now(),runCount:Z,kind:"stash"}};return{beforeRun:async({snapshot:X})=>{if(X.parentAgentId!=null)return;Z+=1;return},beforeModel:async({snapshot:X})=>{if(X.parentAgentId!=null||X.iteration!==1||Z<1)return;let Y=await J();if(!Y)return;let j=await $.readSessionMetadata(),V=kE(j);if(V?.latest.ref===Y.ref)return;let H=IE(V?.history??[],Y);await $.writeSessionMetadata({...j??{},checkpoint:{latest:Y,history:H}});return}}}import{existsSync as b5,mkdirSync as xE,readdirSync as gE,rmdirSync as mE,rmSync as vE,unlinkSync as cE}from"node:fs";import{dirname as QB,join as S5}from"node:path";function $0(){return new Date().toISOString()}function H4($){if(!$||!b5($))return;try{cE($)}catch{}}function uE($){let Z=o8($);if(Z)return{rootSessionId:Z.rootSessionId,fileStem:`${Z.agentId}__${Z.teamTaskId}`};let Q=_5($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class $W{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return S5(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let Z=this.sessionArtifactsDir($);if(!b5(Z))xE(Z,{recursive:!0});return Z}sessionMessagesPath($){return S5(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,Z=!1){let Q=Z?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return S5(Q,`${$}.json`)}removeSessionDirIfEmpty($){let Z=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(Z.startsWith(Q)&&Z!==Q){if(!b5(Z)){Z=QB(Z);continue}try{if(gE(Z).length>0)break;mE(Z)}catch{break}Z=QB(Z)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!b5($))return;try{vE($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,Z,Q){let{rootSessionId:W,fileStem:J}=uE($),X=this.sessionArtifactsDir(W);return{messagesPath:S5(X,`${J}.messages.json`)}}}import{appendFileSync as dE,existsSync as lE,mkdirSync as WB,readFileSync as pE,writeFileSync as JB}from"node:fs";import{dirname as XB,join as rE}from"node:path";import{ensureHookLogDir as iE}from"@cline/shared/storage";class ZW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,Z,Q){this.adapter=$;this.messagesArtifactUploader=Z;this.logger=Q;this.artifacts=new $W(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,Z,Q){JH(Z,Q,h7($))}writeSessionManifest($,Z){WB(XB($),{recursive:!0}),JB($,`${JSON.stringify(N0.parse(Z),null,2)}
470
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let Z=this.artifacts.sessionManifestPath($,!1);if(!lE(Z))return{path:Z};try{return{path:Z,manifest:N0.parse(JSON.parse(pE(Z,"utf8")))}}catch{return{path:Z}}}async resolveArtifactPath($,Z,Q){let J=(await this.adapter.getSession($))?.[Z];return typeof J==="string"&&J.trim().length>0?J:Q($)}async persistSessionMessages($,Z,Q){let W=await this.resolveArtifactPath($,"messagesPath",(Y)=>this.artifacts.sessionMessagesPath(Y)),J=k7({updatedAt:$0(),context:h7($),messages:Z,systemPrompt:Q}),X=`${JSON.stringify(J,null,2)}
471
+ `;if(WB(XB(W),{recursive:!0}),JB(W,X,"utf8"),!this.messagesArtifactUploader)return;try{let Y=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:X,row:Y})}catch(Y){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:Y})}}appendStaleSessionHookLog($,Z,Q,W,J){let Y=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??rE(iE(),"hooks.jsonl");dE(Y,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:Z,pid:Q,source:J})}
472
+ `,"utf8")}}import{appendFileSync as nE}from"node:fs";import{join as aE}from"node:path";import{resolveRootSessionId as YB}from"@cline/shared";import{ensureHookLogDir as sE}from"@cline/shared/storage";import{z as QW}from"zod";var oE="subagent",tE=QW.looseObject({task:QW.string().optional(),systemPrompt:QW.string().optional()});class y5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,Z,Q,W){this.adapter=$;this.manifestStore=Z;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,Z){return`${$}::${Z}`}activeTeamTaskSessionId($,Z){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,Z))?.at(-1)}buildSubsessionRow($,Z){return{sessionId:Z.sessionId,source:oE,pid:process.ppid,startedAt:Z.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:Z.parentSessionId,parentAgentId:Z.parentAgentId,agentId:Z.agentId,conversationId:Z.conversationId??null,isSubagent:!0,prompt:Z.prompt,metadata:e8({prompt:Z.prompt}),hookPath:"",messagesPath:Z.messagesPath,updatedAt:Z.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let Z=YB($.sessionContext);if(!Z)return;let Q=tE.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:Z,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let Z=$.rootSessionId;if(!Z)return;let Q=await this.adapter.getSession(Z);if(!Q)return;let W=L5(Z,$.agentId),J=await this.adapter.getSession(W),X=$0(),Y=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(Z,$.parentAgentId)),j=$.prompt??J?.prompt??void 0;if(!j)j=await this.adapter.claimSpawnRequest(Z,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!J)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:W,parentSessionId:Z,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:j,startedAt:X,...Y})),this.manifestStore.initializeMessagesFile(W,Y.messagesPath,X),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:Z,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:J.prompt??j??null,metadata:e8({metadata:J.metadata??void 0,prompt:J.prompt??j??null}),expectedStatusLock:J.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let Z=YB($.sessionContext);if(!Z)return;if($.hookName==="session_shutdown"){let Q=L5(Z,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:Z})}async applySubagentStatus($,Z){await this.applySubagentStatusBySessionId($,P7(Z))}async applySubagentStatusBySessionId($,Z){let Q=await this.adapter.getSession($);if(!Q)return;let W=j0(Z)?null:$0(),J=j0(Z)?null:Z==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:Z,endedAt:W,exitCode:J,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,Z){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of Q)await this.applySubagentStatusBySessionId(W.sessionId,Z)}async onTeamTaskStart($,Z,Q){let W=await this.adapter.getSession($);if(!W)return;let J=C7($,Z),X=$0(),{messagesPath:Y}=this.manifestStore.artifacts.subagentArtifactPaths(J,Z);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:J,parentSessionId:$,parentAgentId:"lead",agentId:Z,prompt:Q||`Team task for ${Z}`,startedAt:X,messagesPath:Y})),this.manifestStore.initializeMessagesFile(J,Y,X);let j=this.teamTaskQueueKey($,Z),V=this.teamTaskSessionsByAgent.get(j)??[];V.push(J),this.teamTaskSessionsByAgent.set(j,V)}async onTeamTaskEnd($,Z,Q,W,J,X){let Y=this.teamTaskQueueKey($,Z),j=this.teamTaskSessionsByAgent.get(Y);if(!j||j.length===0)return;let V=j.shift();if(j.length===0)this.teamTaskSessionsByAgent.delete(Y);if(!V)return;let H=J?.messages??X,B=this.toPersistedMessages(H,J,X);if(B)await this.manifestStore.persistSessionMessages(V,B);await this.applySubagentStatusBySessionId(V,Q),this.teamTaskLastHeartbeatBySession.delete(V),this.teamTaskLastProgressLineBySession.delete(V)}async onTeamTaskProgress($,Z,Q,W){let J=this.teamTaskQueueKey($,Z),X=this.teamTaskSessionsByAgent.get(J)?.[0];if(!X)return;let Y=Q.trim();if(!Y)return;let j=W?.kind??"progress";if(j==="heartbeat"){let H=Date.now(),B=this.teamTaskLastHeartbeatBySession.get(X)??0;if(H-B<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(X,H)}let V=j==="heartbeat"?"[progress] heartbeat":j==="text"?`[progress] text: ${Y}`:`[progress] ${Y}`;if(this.teamTaskLastProgressLineBySession.get(X)===V)return;this.teamTaskLastProgressLineBySession.set(X,V)}async handleSubAgentStart($,Z){let Q=await this.upsertSubagentSession({agentId:Z.subAgentId,parentAgentId:Z.parentAgentId,conversationId:Z.conversationId,prompt:Z.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,Z){let Q=await this.upsertSubagentSession({agentId:Z.subAgentId,parentAgentId:Z.parentAgentId,conversationId:Z.conversationId,prompt:Z.input.task,rootSessionId:$});if(!Q)return;if(Z.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let W=this.toPersistedMessages(Z.agentResult?.messages,Z.agentResult);if(W)await this.manifestStore.persistSessionMessages(Q,W);let J=Z.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,J==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??aE(sE(),"hooks.jsonl");nE(Q,`${JSON.stringify({ts:$0(),...$})}
473
+ `,"utf8")}}import{formatUserInputBlock as _N}from"@cline/shared";import{existsSync as eE,readdirSync as $N,readFileSync as ZN}from"node:fs";import{basename as jB,extname as QN,join as WN}from"node:path";import{resolveAgentConfigSearchPaths as JN}from"@cline/shared/storage";import HB from"yaml";import{z as q0}from"zod";var BB=q0.object({name:q0.string().trim().min(1),description:q0.string().trim().min(1),tools:q0.union([q0.string(),q0.array(q0.string())]).optional(),skills:q0.union([q0.string(),q0.array(q0.string())]).optional(),providerId:q0.string().trim().min(1).optional(),modelId:q0.string().trim().min(1).optional(),maxIterations:q0.number().int().positive().optional()});function XN($){let Z=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!Z)throw Error("Missing YAML frontmatter block in agent config file.");let Q=Z[0].length,W=/^---[^\S\r\n]*(?:\r?\n|$)/gm;W.lastIndex=Q;let J,X=Array.from($.matchAll(W)).filter((Y)=>Y.index>=Q);for(let Y of X){let j=Y.index,V=$.slice(Q,j);try{let H=HB.parse(V);if(!H||typeof H!=="object"||Array.isArray(H))continue;BB.parse(H);let B=$.slice(j+Y[0].length);J={frontmatter:V,body:B}}catch{}}if(J)return J;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function VB($){if($===void 0)return;let Z=Array.isArray($)?$:$.split(",");return Array.from(new Set(Z.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function YN($){return $.trim().toLowerCase()}function jN($){let Z=QN($).toLowerCase();return Z===".yml"||Z===".yaml"}function WW($,Z={}){let{frontmatter:Q,body:W}=XN($),J=HB.parse(Q);if(!J||typeof J!=="object"||Array.isArray(J))throw Error("Agent config frontmatter must be a YAML mapping.");let X=BB.parse(J),Y=W.trim();if(!Y)throw Error("Missing system prompt body in agent config file.");return{name:X.name,description:X.description,tools:VB(X.tools),skills:VB(X.skills),providerId:X.providerId,modelId:X.modelId,maxIterations:X.maxIterations,systemPrompt:Y,path:Z.path}}function h5($){let Z=$.searchPaths??JN($.workspaceRoot),Q=new Map,W=[];for(let X of Z.filter(Boolean)){if(!eE(X))continue;let Y;try{Y=$N(X,{withFileTypes:!0})}catch(j){W.push({path:X,error:j instanceof Error?j:Error(String(j))});continue}for(let j of Y){if(!j.isFile()||!jN(j.name))continue;let V=WN(X,j.name);try{let H=ZN(V,"utf8"),B=WW(H,{path:V}),G=YN(B.name);if(!Q.has(G))Q.set(G,B)}catch(H){W.push({path:V,error:H instanceof Error?H:Error(String(H))})}}}return{configs:Array.from(Q.values()).sort((X,Y)=>(X.path?jB(X.path):X.name).localeCompare(Y.path?jB(Y.path):Y.name)),errors:W}}import{createTool as VN,zodToJsonSchema as HN}from"@cline/shared";import{z as GB}from"zod";var JW="subagent_",k5=64,BN=GB.object({prompt:GB.string().trim().min(1).describe("Task for the subagent to perform")});function GN($){let Z="",Q=!0;for(let W of $.trim().toLowerCase()){let J=W.charCodeAt(0);if(!(J>=97&&J<=122||J>=48&&J<=57||W==="_")||W==="_"){if(!Q)Z+="_",Q=!0;continue}Z+=W,Q=!1}return Q?Z.slice(0,-1):Z}function KN($){let Z=2166136261;for(let Q=0;Q<$.length;Q++)Z^=$.charCodeAt(Q),Z=Math.imul(Z,16777619);return(Z>>>0).toString(36)}function XW($){let Z=GN($)||"agent",Q=KN($).slice(0,6),W=`${JW}${Z}`;if(W.length<=k5)return W;let J=k5-JW.length-Q.length-1,X=Z.slice(0,Math.max(1,J));return`${JW}${X}_${Q}`.slice(0,k5)}function YW($){let Z=new Set,Q=[];for(let W of[...$].sort((J,X)=>J.name.localeCompare(X.name))){let J=XW(W.name),X=J,Y=2;while(Z.has(X)){let j=`_${Y++}`,V=Math.max(1,k5-j.length);X=`${J.slice(0,V)}${j}`}Z.add(X),Q.push({toolName:X,config:W})}return Q}function FN($,Z){return{...$,providerId:Z.providerId??$.providerId,modelId:Z.modelId??$.modelId,maxIterations:Z.maxIterations??$.maxIterations}}function I5($){return YW($.agents).map(({toolName:Z,config:Q})=>{return VN({name:Z,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:HN(BN),execute:async(J,X)=>{let Y=$.configProvider.getRuntimeConfig(),j=R2(FN(Y,Q)),V=$.createSubAgentTools?await $.createSubAgentTools(Q,J,X):[],H=E2({kind:"subagent",prompt:Q.systemPrompt,configProvider:j,tools:V,maxIterations:Q.maxIterations,parentAgentId:X.agentId,abortSignal:X.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),B=H.getAgentId(),G=H.getConversationId(),K=X.agentId,F={systemPrompt:Q.systemPrompt,task:J.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:B,conversationId:G,parentAgentId:K,input:F})}catch{}try{let A=await H.run(J.prompt),L={text:A.text,iterations:A.iterations,finishReason:A.finishReason,usage:{inputTokens:A.usage.inputTokens,outputTokens:A.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:G,parentAgentId:K,input:F,result:L,agentResult:A})}catch{}return L}catch(A){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:B,conversationId:G,parentAgentId:K,input:F,error:A instanceof Error?A:Error(String(A))})}catch{}throw A}},timeoutMs:300000,retryable:!1})})}function W1(){return new Date().toISOString()}function KB($,Z){if(Z<=0)return 0;return Math.round($/Z*100)}function AN($,Z){let Q=new Set;for(let J of Z)if(J.status==="reviewed")Q.add(`${J.outcomeId}:${J.section}`);let W=new Set;for(let J of $){if(J.status==="finalized")continue;for(let X of J.requiredSections)if(!Q.has(`${J.id}:${X}`))W.add(`${J.id}:${X}`)}return[...W].sort((J,X)=>J.localeCompare(X))}function x5($,Z){let Q={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},J={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},X={draft:0,in_review:0,finalized:0},Y={draft:0,reviewed:0,rejected:0},j=0,V=0;for(let f of Z.members)if(Q[f.status]+=1,f.role==="lead")j+=1;else V+=1;let H=[],B=[],G=Z.tasks.filter((f)=>f.status==="completed").length,K=new Map(Z.tasks.map((f)=>[f.id,f]));for(let f of Z.tasks){if(W[f.status]+=1,f.status==="blocked"){H.push(f.id);continue}if(f.status!=="pending")continue;if(f.dependsOn.every((U)=>{return K.get(U)?.status==="completed"}))B.push(f.id)}let F=[],A,L=0;for(let f of Z.runs){if(J[f.status]+=1,f.status==="queued"||f.status==="running")F.push(f.id);let D=f.startedAt.getTime();if(D>=L)L=D,A=f.id}for(let f of Z.outcomes)X[f.status]+=1;for(let f of Z.outcomeFragments)Y[f.status]+=1;return{teamName:$,updatedAt:W1(),members:{total:Z.members.length,byStatus:Q,leadCount:j,teammateCount:V},tasks:{total:Z.tasks.length,byStatus:W,blockedTaskIds:H,readyTaskIds:B,completionPct:KB(G,Z.tasks.length)},runs:{total:Z.runs.length,byStatus:J,activeRunIds:F,latestRunId:A},outcomes:{total:Z.outcomes.length,byStatus:X,finalizedPct:KB(X.finalized,Z.outcomes.length),missingRequiredSections:AN(Z.outcomes,Z.outcomeFragments)},fragments:{total:Z.outcomeFragments.length,byStatus:Y}}}function g5($){let{event:Z}=$;switch(Z.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.task.id,agentId:Z.task.assignee??Z.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:Z.type,ts:W1(),runId:Z.run.id,taskId:Z.run.taskId,agentId:Z.run.agentId,message:Z.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),runId:Z.run.id,taskId:Z.run.taskId,agentId:Z.run.agentId,message:Z.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),outcomeId:Z.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),outcomeId:Z.fragment.outcomeId,fragmentId:Z.fragment.id,agentId:Z.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.message.taskId,agentId:Z.message.fromAgentId,message:Z.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),taskId:Z.entry.taskId,agentId:Z.entry.agentId,message:Z.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1(),agentId:Z.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:Z.type,ts:W1()}}import{sanitizeFileName as fN,TeamMessageType as y}from"@cline/shared";import{nanoid as UN}from"nanoid";import{TeamMessageType as fp}from"@cline/shared";function jW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function FB($,Z){return $?.status==="stopped"&&jW(Z)}var DN=600000,AB="recovered_queued";function LN($){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.
474
474
 
475
475
  ${$.message}`}class VW{agents=new Map;configs=new Map;onTeamEvent;constructor($,Z){if(this.onTeamEvent=Z,$)for(let[Q,W]of Object.entries($))this.addAgent(Q,W)}addAgent($,Z){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Q={...Z,onEvent:(J)=>{Z.onEvent?.(J),this.emitEvent({type:y.AgentEvent,agentId:$,event:J})}},W=new l1(Q);if(Q.onEvent)W.subscribeEvents(Q.onEvent);this.agents.set($,W),this.configs.set($,Z)}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($,Z){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:y.TaskStart,agentId:$,message:Z});try{let W=await Q.run(Z);return this.emitEvent({type:y.TaskEnd,agentId:$,result:W}),W}catch(W){let J=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:y.TaskEnd,agentId:$,error:J,messages:Q.getMessages()}),W}}async continueTo($,Z){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:y.TaskStart,agentId:$,message:Z});try{let W=await Q.continue(Z);return this.emitEvent({type:y.TaskEnd,agentId:$,result:W}),W}catch(W){let J=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:y.TaskEnd,agentId:$,error:J,messages:Q.getMessages()}),W}}async runParallel($){let Z=$.map(async(Q)=>{let W=this.agents.get(Q.agentId);if(!W)return{agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata};this.emitEvent({type:y.TaskStart,agentId:Q.agentId,message:Q.message});try{let J=await W.run(Q.message);return this.emitEvent({type:y.TaskEnd,agentId:Q.agentId,result:J}),{agentId:Q.agentId,result:J,metadata:Q.metadata}}catch(J){let X=J instanceof Error?J:Error(String(J));return this.emitEvent({type:y.TaskEnd,agentId:Q.agentId,error:X,messages:W.getMessages()}),{agentId:Q.agentId,result:void 0,error:X,metadata:Q.metadata}}});return Promise.all(Z)}async runSequential($){let Z=[];for(let Q of $){let W=this.agents.get(Q.agentId);if(!W){Z.push({agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata});continue}this.emitEvent({type:y.TaskStart,agentId:Q.agentId,message:Q.message});try{let J=await W.run(Q.message);this.emitEvent({type:y.TaskEnd,agentId:Q.agentId,result:J}),Z.push({agentId:Q.agentId,result:J,metadata:Q.metadata})}catch(J){let X=J instanceof Error?J:Error(String(J));this.emitEvent({type:y.TaskEnd,agentId:Q.agentId,error:X,messages:W.getMessages()}),Z.push({agentId:Q.agentId,result:void 0,error:X,metadata:Q.metadata})}}return Z}async runPipeline($,Z,Q){let W=[],J=Z;for(let X of $){let Y=this.agents.get(X);if(!Y){W.push({agentId:X,result:void 0,error:Error(`Agent "${X}" not found in team`)});break}this.emitEvent({type:y.TaskStart,agentId:X,message:J});try{let j=await Y.run(J);this.emitEvent({type:y.TaskEnd,agentId:X,result:j}),W.push({agentId:X,result:j});let V=$.indexOf(X)+1;if(V<$.length){let H=$[V];J=Q?Q(j,H):`Previous agent output:
476
476
  ${j.text}
477
477
 
478
- Please continue from here.`}}catch(j){let V=j instanceof Error?j:Error(String(j));this.emitEvent({type:y.TaskEnd,agentId:X,error:V,messages:Y.getMessages()}),W.push({agentId:X,result:void 0,error:V});break}}return W}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{}}}class B4{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_${GN(KN(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 Z=$.leadAgentId??"lead";this.members.set(Z,{agentId:Z,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((Z)=>{let Q=this.getUnresolvedDependencies(Z);return{...Z,blockedBy:Q,isReady:Z.status==="pending"&&!Z.assignee&&Q.length===0}}).filter((Z)=>{if($?.status&&Z.status!==$.status)return!1;if($?.assignee&&Z.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,Z){let Q=Z?.unreadOnly??!0,W=Z?.markRead??!0,J=Z?.limit,X=this.mailbox.filter((j)=>j.toAgentId===$&&(!Q||!j.readAt)),Y=typeof J==="number"&&J>0?X.slice(Math.max(0,X.length-J)):X;if(W){let j=new Date;for(let V of Y)if(!V.readAt)V.readAt=j}return Y.map((j)=>({...j}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let Z={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())Z[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:Z}}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 Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let Z=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of Z)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,m2($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,m2($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,m2($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,m2(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,m2(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,m2(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let Z=this.members.get($);return!!Z&&Z.role==="teammate"&&!!Z.agent}spawnTeammate({agentId:$,config:Z}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...Z,apiTimeoutMs:FN,consumePendingUserMessage:()=>{let Y=this.members.get($);if(!Y||!Y.pendingSteerMessage)return;let j=Y.pendingSteerMessage;return Y.pendingSteerMessage=void 0,j},onEvent:(Y)=>{Z.onEvent?.(Y),this.emitEvent({type:y.AgentEvent,agentId:$,event:Y}),this.trackMeaningfulEvent($,Y)}},J=new l1(W);if(W.onEvent)J.subscribeEvents(W.onEvent);let X={agentId:$,role:"teammate",description:Z.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,X),this.emitEvent({type:y.TeammateSpawned,agentId:$,role:Z.role,teammate:{rolePrompt:Z.systemPrompt,modelId:Z.modelId,maxIterations:Z.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:X.agentId,role:X.role,description:X.description,status:X.status}}shutdownTeammate($,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(W){if(!jW(W))throw W}Q.status="stopped",this.emitEvent({type:y.TeammateShutdown,agentId:$,reason:Z})}updateTeammateConnections($){for(let Z of this.members.values()){if(Z.role!=="teammate"||!Z.agent)continue;Z.agent.updateConnection($)}}createTask($){let Z=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,W={id:Z,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(Z,W),this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,Z){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=Z,Q.updatedAt=new Date,this.emitEvent({type:y.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,Z,Q){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=Q,this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"blocked",summary:Q}),{...W}}completeTask($,Z,Q){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=Q,!W.assignee)W.assignee=Z;return this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"done",summary:Q}),{...W}}async routeToTeammate($,Z,Q){let W=this.members.get($);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${$}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:y.TaskStart,agentId:$,message:Z});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),X=J.length>0?`${this.buildMailboxNotification(J)}
478
+ Please continue from here.`}}catch(j){let V=j instanceof Error?j:Error(String(j));this.emitEvent({type:y.TaskEnd,agentId:X,error:V,messages:Y.getMessages()}),W.push({agentId:X,result:void 0,error:V});break}}return W}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{}}}class B4{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_${fN(UN(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 Z=$.leadAgentId??"lead";this.members.set(Z,{agentId:Z,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((Z)=>{let Q=this.getUnresolvedDependencies(Z);return{...Z,blockedBy:Q,isReady:Z.status==="pending"&&!Z.assignee&&Q.length===0}}).filter((Z)=>{if($?.status&&Z.status!==$.status)return!1;if($?.assignee&&Z.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,Z){let Q=Z?.unreadOnly??!0,W=Z?.markRead??!0,J=Z?.limit,X=this.mailbox.filter((j)=>j.toAgentId===$&&(!Q||!j.readAt)),Y=typeof J==="number"&&J>0?X.slice(Math.max(0,X.length-J)):X;if(W){let j=new Date;for(let V of Y)if(!V.readAt)V.readAt=j}return Y.map((j)=>({...j}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let Z={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())Z[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:Z}}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 Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let Z=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of Z)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,m2($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,m2($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,m2($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,m2(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,m2(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,m2(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let Z=this.members.get($);return!!Z&&Z.role==="teammate"&&!!Z.agent}spawnTeammate({agentId:$,config:Z}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...Z,apiTimeoutMs:DN,consumePendingUserMessage:()=>{let Y=this.members.get($);if(!Y||!Y.pendingSteerMessage)return;let j=Y.pendingSteerMessage;return Y.pendingSteerMessage=void 0,j},onEvent:(Y)=>{Z.onEvent?.(Y),this.emitEvent({type:y.AgentEvent,agentId:$,event:Y}),this.trackMeaningfulEvent($,Y)}},J=new l1(W);if(W.onEvent)J.subscribeEvents(W.onEvent);let X={agentId:$,role:"teammate",description:Z.role,status:"idle",agent:J,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,X),this.emitEvent({type:y.TeammateSpawned,agentId:$,role:Z.role,teammate:{rolePrompt:Z.systemPrompt,modelId:Z.modelId,maxIterations:Z.maxIterations,runtimeAgentId:J.getAgentId(),conversationId:J.getConversationId(),parentAgentId:null}}),{agentId:X.agentId,role:X.role,description:X.description,status:X.status}}shutdownTeammate($,Z){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(W){if(!jW(W))throw W}Q.status="stopped",this.emitEvent({type:y.TeammateShutdown,agentId:$,reason:Z})}updateTeammateConnections($){for(let Z of this.members.values()){if(Z.role!=="teammate"||!Z.agent)continue;Z.agent.updateConnection($)}}createTask($){let Z=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,W={id:Z,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(Z,W),this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,Z){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=Z,Q.updatedAt=new Date,this.emitEvent({type:y.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,Z,Q){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=Q,this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"blocked",summary:Q}),{...W}}completeTask($,Z,Q){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=Q,!W.assignee)W.assignee=Z;return this.emitEvent({type:y.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:Z,taskId:$,kind:"done",summary:Q}),{...W}}async routeToTeammate($,Z,Q){let W=this.members.get($);if(!W||W.role!=="teammate"||!W.agent)throw Error(`Teammate "${$}" was not found`);if(!W.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");W.runningCount++,W.status="running",this.emitEvent({type:y.TaskStart,agentId:$,message:Z});try{let J=this.listMailbox($,{unreadOnly:!0,markRead:!0}),X=J.length>0?`${this.buildMailboxNotification(J)}
479
479
 
480
- ${Z}`:Z,Y=Q?.continueConversation?await W.agent.continue(X):await W.agent.run(X);return this.emitEvent({type:y.TaskEnd,agentId:$,result:Y}),this.recordProgressStep($,`Completed a delegated run (${Y.iterations} iterations)`,Q?.taskId,!0),Y}catch(J){let X=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:y.TaskEnd,agentId:$,error:X,messages:W.agent.getMessages()}),!FB(W,X))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:X.message});throw X}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,Z,Q){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:W,agentId:$,taskId:Q?.taskId,status:"queued",message:Z,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,J),this.runQueue.push(W),this.emitEvent({type:y.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let Z=this.selectNextDispatchableQueuedRun();$=Z.nextDelayedAttemptAt;let Q=Z.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(Q,1),J=W?this.runs.get(W):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,Z=Number.NEGATIVE_INFINITY,Q,W=Date.now();for(let J=0;J<this.runQueue.length;J++){let X=this.runs.get(this.runQueue[J]);if(!X||X.status!=="queued")continue;if(X.nextAttemptAt&&X.nextAttemptAt.getTime()>W){if(!Q||X.nextAttemptAt<Q)Q=X.nextAttemptAt;continue}if(X.priority>Z)Z=X.priority,$=J}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let Z=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},Z)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let Z of this.runs.values())if(Z.status==="running")$++;return $}async executeQueuedRun($){let Z=$.currentActivity===AB;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:y.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=Z?AN($):$.message,J=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:y.RunCompleted,run:{...$}})}catch(W){let J=W instanceof Error?W.message:String(W??"Unknown error");$.error=J,$.endedAt=new Date;let X=this.members.get($.agentId);if(FB(X,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:y.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:y.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let Z=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!Z&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let Z=this.runs.get($);return Z?{...Z}:void 0}async awaitRun($,Z=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await fB(Z);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((Z)=>["queued","running"].includes(Z.status)))await fB($);return this.listRuns()}cancelRun($,Z){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=Z,Q.endedAt=new Date,Q.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:y.RunCancelled,run:{...Q},reason:Z}),{...Q}}recoverActiveRuns($="runtime_recovered"){let Z=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let W=this.members.get(Q.agentId);if(!W||W.role!=="teammate"||!W.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:y.RunInterrupted,run:{...Q},reason:Q.error});continue}let J=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=J,Q.lastProgressAt=J,Q.lastProgressMessage=$,Q.currentActivity=AB,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);Z.push({...Q}),this.emitEvent({type:y.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),Z}markStaleRunsInterrupted($="runtime_recovered"){let Z=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",Z.push({...Q}),this.emitEvent({type:y.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),Z}sendMessage($,Z,Q,W,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let X=this.members.get(Z);if(!X)throw Error(`Unknown recipient "${Z}"`);let Y={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:Z,subject:Q,body:W,taskId:J,sentAt:new Date};if(this.mailbox.push(Y),this.emitEvent({type:y.TeamMessage,message:{...Y}}),X.role==="teammate"&&X.runningCount>0&&X.agent)X.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Y}}broadcast($,Z,Q,W){let J=[];for(let X of this.members.values()){if(X.agentId===$)continue;if(X.role==="lead")continue;J.push(this.sendMessage($,X.agentId,Z,Q,W?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let Z={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(Z);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:y.TeamMissionLog,entry:{...Z}}),{...Z}}createOutcome($){let Z={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(Z.id,Z),this.emitEvent({type:y.OutcomeCreated,outcome:{...Z}}),{...Z}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let Z=this.outcomes.get($.outcomeId);if(!Z)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!Z.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={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(Q.id,Q),Z.status==="draft")Z.status="in_review";return this.emitEvent({type:y.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let Z=this.outcomeFragments.get($.fragmentId);if(!Z)throw Error(`Fragment "${$.fragmentId}" was not found`);return Z.status=$.approved?"reviewed":"rejected",Z.reviewedBy=$.reviewedBy,Z.reviewedAt=new Date,this.emitEvent({type:y.OutcomeFragmentReviewed,fragment:{...Z}}),{...Z}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((Z)=>Z.outcomeId===$).map((Z)=>({...Z}))}finalizeOutcome($){let Z=this.outcomes.get($);if(!Z)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let W of Z.requiredSections)if(!Q.some((X)=>X.section===W&&X.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return Z.status="finalized",Z.finalizedAt=new Date,this.emitEvent({type:y.OutcomeFinalized,outcome:{...Z}}),{...Z}}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(Z){if(!jW(Z))throw Z}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[$,Z]of this.members.entries())if(Z.role==="teammate")this.members.delete($)}requireTask($){let Z=this.tasks.get($);if(!Z)throw Error(`Task "${$}" was not found`);return Z}assertDependenciesResolved($){let Z=this.getUnresolvedDependencies($);if(Z.length>0)throw Error(`Task "${$.id}" is blocked by "${Z[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((Z)=>{let Q=this.tasks.get(Z);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,Z){if(this.recordRunActivityFromAgentEvent($,Z),Z.type==="iteration_end"&&Z.hadToolCalls){this.recordProgressStep($,`Completed iteration ${Z.iteration} with ${Z.toolCallCount} tool call(s)`);return}if(Z.type==="content_end"&&Z.contentType==="tool"&&!Z.error){this.recordProgressStep($,`Finished tool "${Z.toolName??"unknown"}"`);return}if(Z.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${Z.iterations} iterations)`});return}if(Z.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:Z.error.message})}recordRunActivityFromAgentEvent($,Z){let Q;switch(Z.type){case"iteration_start":Q=`iteration_${Z.iteration}_started`;break;case"content_start":if(Z.contentType==="tool")Q=`running_tool_${Z.toolName??"unknown"}`;break;case"content_end":if(Z.contentType==="tool")Q=Z.error?this.formatProgressErrorActivity(`tool_${Z.toolName??"unknown"}_error`,Z.error):`finished_tool_${Z.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",Z.error.message);break;default:break}if(!Q)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,Q)}}recordRunProgress($,Z){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=Z,$.currentActivity=Z,this.emitEvent({type:y.RunProgress,run:{...$},message:Z})}formatProgressErrorActivity($,Z){let Q=Z.replace(/\s+/g," ").trim();if(Q.length===0)return $;let W=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${W}`}recordProgressStep($,Z,Q,W=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let X=this.missionStepCounter-J.lastMissionStep,Y=Date.now()-J.lastMissionAt;if(!W&&X<this.missionLogIntervalSteps&&Y<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:Z})}buildMailboxNotification($){if($.length===0)return"";let Z=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)Z.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),Z.push(Q.body);return Z.push("---"),Z.join(`
481
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function fB($){return new Promise((Z)=>setTimeout(Z,$))}function m2($,Z){let Q=0;for(let W of $){if(!W.startsWith(Z))continue;let J=Number.parseInt(W.slice(Z.length),10);if(Number.isFinite(J))Q=Math.max(Q,J)}return Q}function HW($,Z){switch(Z.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(Z.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(Z.type==="run_failed")Q=Z.run.error;else if(Z.type==="run_cancelled"||Z.type==="run_interrupted")Q=Z.run.error??Z.reason;$.activeTeamRunIds.delete(Z.run.id),$.pendingTeamRunUpdates.push({runId:Z.run.id,agentId:Z.run.agentId,taskId:Z.run.taskId,status:Z.type.replace("run_",""),error:Q,iterations:Z.run.result?.iterations}),g5($);break}default:break}}async function BW($,Z,Q){switch(Z.type){case"run_progress":await Q("onTeamTaskProgress",$,Z.run.agentId,Z.message,{kind:Z.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(Z.event.type==="content_start"&&Z.event.contentType==="text"&&typeof Z.event.text==="string"){let W=Z.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await Q("onTeamTaskProgress",$,Z.agentId,W,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,Z.agentId,Z.message);break;case"task_end":{if(Z.error)await Q("onTeamTaskEnd",$,Z.agentId,"failed",`[error] ${Z.error.message}`,void 0,Z.messages);else if(Z.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,Z.agentId,"cancelled","[done] aborted",Z.result,Z.result.messages);else await Q("onTeamTaskEnd",$,Z.agentId,"completed",`[done] ${Z.result?.finishReason??"completed"}`,Z.result,Z.result?.messages);break}default:break}}function GW($,Z,Q,W){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:Z,teamName:J,lifecycle:x5({teamName:J,sessionId:Z,event:Q}),summary:I5(J,$.runtime.teamRuntime.exportState())}})}function G4($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function KW($,Z){if($.aborting)return!1;if(!(Z==="completed"||Z==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&G4($)}function g5($){let Z=$.teamRunWaiters.splice(0);for(let Q of Z)Q()}async function FW($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let Z=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,Z}if($.activeTeamRunIds.size===0)return[];await new Promise((Z)=>{$.teamRunWaiters.push(Z)})}}function AW($,Z){let Q=Z.map((X)=>{let Y=[`- ${X.runId} (${X.agentId}) -> ${X.status}`];if(X.taskId)Y.push(` task=${X.taskId}`);if(typeof X.iterations==="number")Y.push(` iterations=${X.iterations}`);if(X.error)Y.push(` error=${X.error}`);return Y.join("")}),W=$.activeTeamRunIds.size,J=W>0?`There are still ${W} 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 K4(`System-delivered teammate async run updates:
480
+ ${Z}`:Z,Y=Q?.continueConversation?await W.agent.continue(X):await W.agent.run(X);return this.emitEvent({type:y.TaskEnd,agentId:$,result:Y}),this.recordProgressStep($,`Completed a delegated run (${Y.iterations} iterations)`,Q?.taskId,!0),Y}catch(J){let X=J instanceof Error?J:Error(String(J));if(this.emitEvent({type:y.TaskEnd,agentId:$,error:X,messages:W.agent.getMessages()}),!FB(W,X))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:X.message});throw X}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,Z,Q){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,J={id:W,agentId:$,taskId:Q?.taskId,status:"queued",message:Z,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,J),this.runQueue.push(W),this.emitEvent({type:y.RunQueued,run:{...J}}),this.dispatchQueuedRuns(),{...J}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let Z=this.selectNextDispatchableQueuedRun();$=Z.nextDelayedAttemptAt;let Q=Z.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(Q,1),J=W?this.runs.get(W):void 0;if(!J||J.status!=="queued")continue;this.executeQueuedRun(J)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,Z=Number.NEGATIVE_INFINITY,Q,W=Date.now();for(let J=0;J<this.runQueue.length;J++){let X=this.runs.get(this.runQueue[J]);if(!X||X.status!=="queued")continue;if(X.nextAttemptAt&&X.nextAttemptAt.getTime()>W){if(!Q||X.nextAttemptAt<Q)Q=X.nextAttemptAt;continue}if(X.priority>Z)Z=X.priority,$=J}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let Z=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},Z)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let Z of this.runs.values())if(Z.status==="running")$++;return $}async executeQueuedRun($){let Z=$.currentActivity===AB;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:y.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=Z?LN($):$.message,J=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=J,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:y.RunCompleted,run:{...$}})}catch(W){let J=W instanceof Error?W.message:String(W??"Unknown error");$.error=J,$.endedAt=new Date;let X=this.members.get($.agentId);if(FB(X,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:y.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:y.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let Z=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!Z&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let Z=this.runs.get($);return Z?{...Z}:void 0}async awaitRun($,Z=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await fB(Z);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((Z)=>["queued","running"].includes(Z.status)))await fB($);return this.listRuns()}cancelRun($,Z){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=Z,Q.endedAt=new Date,Q.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:y.RunCancelled,run:{...Q},reason:Z}),{...Q}}recoverActiveRuns($="runtime_recovered"){let Z=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let W=this.members.get(Q.agentId);if(!W||W.role!=="teammate"||!W.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:y.RunInterrupted,run:{...Q},reason:Q.error});continue}let J=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=J,Q.lastProgressAt=J,Q.lastProgressMessage=$,Q.currentActivity=AB,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);Z.push({...Q}),this.emitEvent({type:y.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),Z}markStaleRunsInterrupted($="runtime_recovered"){let Z=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",Z.push({...Q}),this.emitEvent({type:y.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),Z}sendMessage($,Z,Q,W,J){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let X=this.members.get(Z);if(!X)throw Error(`Unknown recipient "${Z}"`);let Y={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:Z,subject:Q,body:W,taskId:J,sentAt:new Date};if(this.mailbox.push(Y),this.emitEvent({type:y.TeamMessage,message:{...Y}}),X.role==="teammate"&&X.runningCount>0&&X.agent)X.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...Y}}broadcast($,Z,Q,W){let J=[];for(let X of this.members.values()){if(X.agentId===$)continue;if(X.role==="lead")continue;J.push(this.sendMessage($,X.agentId,Z,Q,W?.taskId))}return J}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let Z={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(Z);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:y.TeamMissionLog,entry:{...Z}}),{...Z}}createOutcome($){let Z={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(Z.id,Z),this.emitEvent({type:y.OutcomeCreated,outcome:{...Z}}),{...Z}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let Z=this.outcomes.get($.outcomeId);if(!Z)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!Z.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={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(Q.id,Q),Z.status==="draft")Z.status="in_review";return this.emitEvent({type:y.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let Z=this.outcomeFragments.get($.fragmentId);if(!Z)throw Error(`Fragment "${$.fragmentId}" was not found`);return Z.status=$.approved?"reviewed":"rejected",Z.reviewedBy=$.reviewedBy,Z.reviewedAt=new Date,this.emitEvent({type:y.OutcomeFragmentReviewed,fragment:{...Z}}),{...Z}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((Z)=>Z.outcomeId===$).map((Z)=>({...Z}))}finalizeOutcome($){let Z=this.outcomes.get($);if(!Z)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let W of Z.requiredSections)if(!Q.some((X)=>X.section===W&&X.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return Z.status="finalized",Z.finalizedAt=new Date,this.emitEvent({type:y.OutcomeFinalized,outcome:{...Z}}),{...Z}}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(Z){if(!jW(Z))throw Z}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[$,Z]of this.members.entries())if(Z.role==="teammate")this.members.delete($)}requireTask($){let Z=this.tasks.get($);if(!Z)throw Error(`Task "${$}" was not found`);return Z}assertDependenciesResolved($){let Z=this.getUnresolvedDependencies($);if(Z.length>0)throw Error(`Task "${$.id}" is blocked by "${Z[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((Z)=>{let Q=this.tasks.get(Z);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,Z){if(this.recordRunActivityFromAgentEvent($,Z),Z.type==="iteration_end"&&Z.hadToolCalls){this.recordProgressStep($,`Completed iteration ${Z.iteration} with ${Z.toolCallCount} tool call(s)`);return}if(Z.type==="content_end"&&Z.contentType==="tool"&&!Z.error){this.recordProgressStep($,`Finished tool "${Z.toolName??"unknown"}"`);return}if(Z.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${Z.iterations} iterations)`});return}if(Z.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:Z.error.message})}recordRunActivityFromAgentEvent($,Z){let Q;switch(Z.type){case"iteration_start":Q=`iteration_${Z.iteration}_started`;break;case"content_start":if(Z.contentType==="tool")Q=`running_tool_${Z.toolName??"unknown"}`;break;case"content_end":if(Z.contentType==="tool")Q=Z.error?this.formatProgressErrorActivity(`tool_${Z.toolName??"unknown"}_error`,Z.error):`finished_tool_${Z.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",Z.error.message);break;default:break}if(!Q)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,Q)}}recordRunProgress($,Z){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=Z,$.currentActivity=Z,this.emitEvent({type:y.RunProgress,run:{...$},message:Z})}formatProgressErrorActivity($,Z){let Q=Z.replace(/\s+/g," ").trim();if(Q.length===0)return $;let W=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${W}`}recordProgressStep($,Z,Q,W=!1){this.missionStepCounter++;let J=this.members.get($);if(!J)return;let X=this.missionStepCounter-J.lastMissionStep,Y=Date.now()-J.lastMissionAt;if(!W&&X<this.missionLogIntervalSteps&&Y<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:Z})}buildMailboxNotification($){if($.length===0)return"";let Z=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)Z.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),Z.push(Q.body);return Z.push("---"),Z.join(`
481
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function fB($){return new Promise((Z)=>setTimeout(Z,$))}function m2($,Z){let Q=0;for(let W of $){if(!W.startsWith(Z))continue;let J=Number.parseInt(W.slice(Z.length),10);if(Number.isFinite(J))Q=Math.max(Q,J)}return Q}function HW($,Z){switch(Z.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(Z.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(Z.type==="run_failed")Q=Z.run.error;else if(Z.type==="run_cancelled"||Z.type==="run_interrupted")Q=Z.run.error??Z.reason;$.activeTeamRunIds.delete(Z.run.id),$.pendingTeamRunUpdates.push({runId:Z.run.id,agentId:Z.run.agentId,taskId:Z.run.taskId,status:Z.type.replace("run_",""),error:Q,iterations:Z.run.result?.iterations}),m5($);break}default:break}}async function BW($,Z,Q){switch(Z.type){case"run_progress":await Q("onTeamTaskProgress",$,Z.run.agentId,Z.message,{kind:Z.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(Z.event.type==="content_start"&&Z.event.contentType==="text"&&typeof Z.event.text==="string"){let W=Z.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await Q("onTeamTaskProgress",$,Z.agentId,W,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,Z.agentId,Z.message);break;case"task_end":{if(Z.error)await Q("onTeamTaskEnd",$,Z.agentId,"failed",`[error] ${Z.error.message}`,void 0,Z.messages);else if(Z.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,Z.agentId,"cancelled","[done] aborted",Z.result,Z.result.messages);else await Q("onTeamTaskEnd",$,Z.agentId,"completed",`[done] ${Z.result?.finishReason??"completed"}`,Z.result,Z.result?.messages);break}default:break}}function GW($,Z,Q,W){if(!$.runtime.teamRuntime)return;let J=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:Z,teamName:J,lifecycle:g5({teamName:J,sessionId:Z,event:Q}),summary:x5(J,$.runtime.teamRuntime.exportState())}})}function G4($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function KW($,Z){if($.aborting)return!1;if(!(Z==="completed"||Z==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&G4($)}function m5($){let Z=$.teamRunWaiters.splice(0);for(let Q of Z)Q()}async function FW($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let Z=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,Z}if($.activeTeamRunIds.size===0)return[];await new Promise((Z)=>{$.teamRunWaiters.push(Z)})}}function AW($,Z){let Q=Z.map((X)=>{let Y=[`- ${X.runId} (${X.agentId}) -> ${X.status}`];if(X.taskId)Y.push(` task=${X.taskId}`);if(typeof X.iterations==="number")Y.push(` iterations=${X.iterations}`);if(X.error)Y.push(` error=${X.error}`);return Y.join("")}),W=$.activeTeamRunIds.size,J=W>0?`There are still ${W} 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 K4(`System-delivered teammate async run updates:
482
482
  ${Q.join(`
483
483
  `)}
484
484
 
485
- ${J}`,$.config.mode)}function K4($,Z){return fN($,Z==="plan"?"plan":Z==="yolo"?"yolo":"act")}var fW=4;class T1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,Z={}){this.adapter=$;this.manifestStore=new ZW($,Z.messagesArtifactUploader,Z.logger),this.teamChildren=new b5($,this.manifestStore,(Q,W,J)=>this.toPersistedMessages(Q,W,J),T1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,Z,Q){if(!$)return;return Z?z5(Z.messages,Z,Q):_5($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,Z){this.manifestStore.writeSessionManifest($,Z)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let Z=$.startedAt??$0(),Q=$.sessionId.trim(),W=Q.length>0?Q:`${Date.now()}_${DN(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(W),X=this.manifestStore.artifacts.sessionManifestPath(W),Y=e8({metadata:$.metadata,prompt:$.prompt}),j={version:1,session_id:W,source:$.source,pid:$.pid,started_at:Z,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:W,source:$.source,pid:$.pid,startedAt:Z,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:j.prompt??null,metadata:i1(j.metadata),hookPath:"",messagesPath:J,updatedAt:$0()}),this.manifestStore.initializeMessagesFile(W,J,Z),this.manifestStore.writeSessionManifest(X,j),{manifestPath:X,messagesPath:J,manifest:j}}async updateSessionStatus($,Z,Q){let W;if((await YH(()=>this.adapter.getSession($),async(X)=>{return W=j0(Z)?void 0:$0(),this.adapter.updateSession({sessionId:$,status:Z,endedAt:W??null,exitCode:j0(Z)?null:typeof Q==="number"?Q:null,expectedStatusLock:X.statusLock})},fW)).updated){if(Z==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let Z=0;Z<fW;Z++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let W=Q.metadata??void 0,J=$.metadata!==void 0?i1($.metadata)??{}:i1(W)??{},X=k$(typeof W?.title==="string"?W.title:void 0),Y=$.title!==void 0?k$($.title):X??y7($.prompt);if(Y)J.title=Y;else delete J.title;let j=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:j?Object.keys(J).length>0?J:null:void 0,title:Y,expectedStatusLock:Q.statusLock})).updated)continue;let{path:H,manifest:B}=this.manifestStore.readManifestFile($.sessionId);if(B){if($.prompt!==void 0)B.prompt=$.prompt??void 0;let G=$.metadata!==void 0?i1($.metadata)??{}:i1(B.metadata)??{};if(Y)G.title=Y;B.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(H,B)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,Z){return this.teamChildren.appendSubagentHookAudit(Z),Promise.resolve()}persistSessionMessages($,Z,Q){let W=_5(Z);return this.manifestStore.persistSessionMessages($,W,Q)}applySubagentStatus($,Z){return this.teamChildren.applySubagentStatus($,Z)}applySubagentStatusBySessionId($,Z){return this.teamChildren.applySubagentStatusBySessionId($,Z)}applyStatusToRunningChildSessions($,Z){return this.teamChildren.applyStatusToRunningChildSessions($,Z)}onTeamTaskStart($,Z,Q){return this.teamChildren.onTeamTaskStart($,Z,Q)}onTeamTaskEnd($,Z,Q,W,J,X){return this.teamChildren.onTeamTaskEnd($,Z,Q,W,J,X)}onTeamTaskProgress($,Z,Q,W){return this.teamChildren.onTeamTaskProgress($,Z,Q,W)}handleSubAgentStart($,Z){return this.teamChildren.handleSubAgentStart($,Z)}handleSubAgentEnd($,Z){return this.teamChildren.handleSubAgentEnd($,Z)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(Z){return typeof Z==="object"&&Z!==null&&"code"in Z&&Z.code==="EPERM"}}async reconcileDeadRunningSession($){if(j0($.status)===!1||this.isPidAlive($.pid))return $;let Z=$0(),Q=T1.STALE_REASON;for(let W=0;W<fW;W++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(j0(J.status)===!1)return J;let X={...J.metadata??{},terminal_marker:Q,terminal_marker_at:Z,terminal_marker_pid:J.pid,terminal_marker_source:T1.STALE_SOURCE},Y=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:Z,exitCode:1,metadata:X,expectedStatusLock:J.statusLock});if(!Y.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let j=XH(J,{status:"failed",endedAt:Z,exitCode:1,metadata:X}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,j),this.manifestStore.appendStaleSessionHookLog(Z,J.sessionId,J.pid,Q,T1.STALE_SOURCE),{...J,status:"failed",endedAt:Z,exitCode:1,metadata:X,statusLock:Y.statusLock,updatedAt:Z}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let Z=Math.max(1,Math.floor($)),Q=Math.min(Z*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,Z).map((J)=>{let X=i1(J.metadata??void 0),Y=this.manifestStore.readSessionManifest(J.sessionId),j=k$(typeof Y?.metadata?.title==="string"?Y.metadata.title:void 0),V=j?{...X??{},title:j}:X;return{...J,metadata:V}})}async reconcileDeadSessions($=2000){let Z=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:Z,status:J})))).flat(),W=0;for(let J of Q){let X=await this.reconcileDeadRunningSession(J);if(X&&X.status!==J.status)W++}return W}async deleteSession($){let Z=$.trim();if(!Z)throw Error("session id is required");let Q=await this.adapter.getSession(Z);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(Z,!1),!Q.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:Z});await this.adapter.deleteSession(Z,!0),await Promise.allSettled(W.map(async(J)=>{await e7(J.cwd,J.sessionId),H4(J.messagesPath),H4(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await e7(Q.cwd,Z),H4(Q.messagesPath),H4(this.manifestStore.artifacts.sessionManifestPath(Z,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(Z);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(Z)]);for(let J of[Q.messagesPath])if(typeof J==="string"&&J.trim().length>0)W.add(UN(J));for(let J of W)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}}function DW(){return new Date().toISOString()}function LB($,Z){let Q=`${$}.tmp`;zN(Q,`${JSON.stringify(Z,null,2)}
486
- `,"utf8"),_N(Q,$)}class _B{sessionsDirPath;constructor($=TN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!UW(this.sessionsDirPath))LN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return DB(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return DB(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!UW($))return{version:1,sessions:{}};try{let Z=JSON.parse(UB($,"utf8"));if(Z?.version===1&&Z.sessions)return Z}catch{}return{version:1,sessions:{}}}writeIndex($){LB(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!UW($))return{version:1,nextId:1,requests:[]};try{let Z=JSON.parse(UB($,"utf8"));if(Z?.version===1&&typeof Z.nextId==="number"&&Array.isArray(Z.requests))return Z}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){LB(this.spawnQueuePath(),$)}async upsertSession($){let Z=this.readIndex();Z.sessions[$.sessionId]=$,this.writeIndex(Z)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((Z)=>$.parentSessionId!==void 0?Z.parentSessionId===$.parentSessionId:!0).filter((Z)=>$.status!==void 0?Z.status===$.status:!0).sort((Z,Q)=>Q.startedAt.localeCompare(Z.startedAt)).slice(0,$.limit)}async updateSession($){let Z=this.readIndex(),Q=Z.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,J={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:DW()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return Z.sessions[$.sessionId]=J,this.writeIndex(Z),{updated:!0,statusLock:J.statusLock}}async deleteSession($,Z){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],Z){for(let J of Object.values(Q.sessions))if(J.parentSessionId===$)delete Q.sessions[J.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let Z=this.readQueue();Z.requests.push({id:Z.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:DW()}),Z.nextId+=1,this.writeQueue(Z)}async claimSpawnRequest($,Z){let Q=this.readQueue(),W=Q.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===Z&&!J.consumedAt);if(!W)return;return W.consumedAt=DW(),this.writeQueue(Q),W.task}}class LW extends T1{constructor($,Z={}){super(new _B($),Z)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as ON,mkdirSync as qN}from"node:fs";import{resolveSessionDataDir as MN}from"@cline/shared/storage";var _W=`
485
+ ${J}`,$.config.mode)}function K4($,Z){return _N($,Z==="plan"?"plan":Z==="yolo"?"yolo":"act")}var fW=4;class O1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,Z={}){this.adapter=$;this.manifestStore=new ZW($,Z.messagesArtifactUploader,Z.logger),this.teamChildren=new y5($,this.manifestStore,(Q,W,J)=>this.toPersistedMessages(Q,W,J),O1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,Z,Q){if(!$)return;return Z?T5(Z.messages,Z,Q):z5($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,Z){this.manifestStore.writeSessionManifest($,Z)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let Z=$.startedAt??$0(),Q=$.sessionId.trim(),W=Q.length>0?Q:`${Date.now()}_${TN(5)}`,J=this.manifestStore.artifacts.sessionMessagesPath(W),X=this.manifestStore.artifacts.sessionManifestPath(W),Y=e8({metadata:$.metadata,prompt:$.prompt}),j={version:1,session_id:W,source:$.source,pid:$.pid,started_at:Z,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:W,source:$.source,pid:$.pid,startedAt:Z,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:j.prompt??null,metadata:i1(j.metadata),hookPath:"",messagesPath:J,updatedAt:$0()}),this.manifestStore.initializeMessagesFile(W,J,Z),this.manifestStore.writeSessionManifest(X,j),{manifestPath:X,messagesPath:J,manifest:j}}async updateSessionStatus($,Z,Q){let W;if((await YH(()=>this.adapter.getSession($),async(X)=>{return W=j0(Z)?void 0:$0(),this.adapter.updateSession({sessionId:$,status:Z,endedAt:W??null,exitCode:j0(Z)?null:typeof Q==="number"?Q:null,expectedStatusLock:X.statusLock})},fW)).updated){if(Z==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let Z=0;Z<fW;Z++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let W=Q.metadata??void 0,J=$.metadata!==void 0?i1($.metadata)??{}:i1(W)??{},X=I$(typeof W?.title==="string"?W.title:void 0),Y=$.title!==void 0?I$($.title):X??y7($.prompt);if(Y)J.title=Y;else delete J.title;let j=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:j?Object.keys(J).length>0?J:null:void 0,title:Y,expectedStatusLock:Q.statusLock})).updated)continue;let{path:H,manifest:B}=this.manifestStore.readManifestFile($.sessionId);if(B){if($.prompt!==void 0)B.prompt=$.prompt??void 0;let G=$.metadata!==void 0?i1($.metadata)??{}:i1(B.metadata)??{};if(Y)G.title=Y;B.metadata=Object.keys(G).length>0?G:void 0,this.manifestStore.writeSessionManifest(H,B)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,Z){return this.teamChildren.appendSubagentHookAudit(Z),Promise.resolve()}persistSessionMessages($,Z,Q){let W=z5(Z);return this.manifestStore.persistSessionMessages($,W,Q)}applySubagentStatus($,Z){return this.teamChildren.applySubagentStatus($,Z)}applySubagentStatusBySessionId($,Z){return this.teamChildren.applySubagentStatusBySessionId($,Z)}applyStatusToRunningChildSessions($,Z){return this.teamChildren.applyStatusToRunningChildSessions($,Z)}onTeamTaskStart($,Z,Q){return this.teamChildren.onTeamTaskStart($,Z,Q)}onTeamTaskEnd($,Z,Q,W,J,X){return this.teamChildren.onTeamTaskEnd($,Z,Q,W,J,X)}onTeamTaskProgress($,Z,Q,W){return this.teamChildren.onTeamTaskProgress($,Z,Q,W)}handleSubAgentStart($,Z){return this.teamChildren.handleSubAgentStart($,Z)}handleSubAgentEnd($,Z){return this.teamChildren.handleSubAgentEnd($,Z)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(Z){return typeof Z==="object"&&Z!==null&&"code"in Z&&Z.code==="EPERM"}}async reconcileDeadRunningSession($){if(j0($.status)===!1||this.isPidAlive($.pid))return $;let Z=$0(),Q=O1.STALE_REASON;for(let W=0;W<fW;W++){let J=await this.adapter.getSession($.sessionId);if(!J)return;if(j0(J.status)===!1)return J;let X={...J.metadata??{},terminal_marker:Q,terminal_marker_at:Z,terminal_marker_pid:J.pid,terminal_marker_source:O1.STALE_SOURCE},Y=await this.adapter.updateSession({sessionId:J.sessionId,status:"failed",endedAt:Z,exitCode:1,metadata:X,expectedStatusLock:J.statusLock});if(!Y.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(J.sessionId,"failed");let j=XH(J,{status:"failed",endedAt:Z,exitCode:1,metadata:X}),{path:V}=this.manifestStore.readManifestFile(J.sessionId);return this.manifestStore.writeSessionManifest(V,j),this.manifestStore.appendStaleSessionHookLog(Z,J.sessionId,J.pid,Q,O1.STALE_SOURCE),{...J,status:"failed",endedAt:Z,exitCode:1,metadata:X,statusLock:Y.statusLock,updatedAt:Z}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let Z=Math.max(1,Math.floor($)),Q=Math.min(Z*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,Z).map((J)=>{let X=i1(J.metadata??void 0),Y=this.manifestStore.readSessionManifest(J.sessionId),j=I$(typeof Y?.metadata?.title==="string"?Y.metadata.title:void 0),V=j?{...X??{},title:j}:X;return{...J,metadata:V}})}async reconcileDeadSessions($=2000){let Z=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((J)=>this.adapter.listSessions({limit:Z,status:J})))).flat(),W=0;for(let J of Q){let X=await this.reconcileDeadRunningSession(J);if(X&&X.status!==J.status)W++}return W}async deleteSession($){let Z=$.trim();if(!Z)throw Error("session id is required");let Q=await this.adapter.getSession(Z);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(Z,!1),!Q.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:Z});await this.adapter.deleteSession(Z,!0),await Promise.allSettled(W.map(async(J)=>{await e7(J.cwd,J.sessionId),H4(J.messagesPath),H4(this.manifestStore.artifacts.sessionManifestPath(J.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(J.sessionId)}))}if(await e7(Q.cwd,Z),H4(Q.messagesPath),H4(this.manifestStore.artifacts.sessionManifestPath(Z,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(Z);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(Z)]);for(let J of[Q.messagesPath])if(typeof J==="string"&&J.trim().length>0)W.add(zN(J));for(let J of W)this.manifestStore.artifacts.removeDir(J)}return{deleted:!0}}}function DW(){return new Date().toISOString()}function LB($,Z){let Q=`${$}.tmp`;MN(Q,`${JSON.stringify(Z,null,2)}
486
+ `,"utf8"),qN(Q,$)}class _B{sessionsDirPath;constructor($=RN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!UW(this.sessionsDirPath))ON(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return DB(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return DB(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!UW($))return{version:1,sessions:{}};try{let Z=JSON.parse(UB($,"utf8"));if(Z?.version===1&&Z.sessions)return Z}catch{}return{version:1,sessions:{}}}writeIndex($){LB(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!UW($))return{version:1,nextId:1,requests:[]};try{let Z=JSON.parse(UB($,"utf8"));if(Z?.version===1&&typeof Z.nextId==="number"&&Array.isArray(Z.requests))return Z}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){LB(this.spawnQueuePath(),$)}async upsertSession($){let Z=this.readIndex();Z.sessions[$.sessionId]=$,this.writeIndex(Z)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((Z)=>$.parentSessionId!==void 0?Z.parentSessionId===$.parentSessionId:!0).filter((Z)=>$.status!==void 0?Z.status===$.status:!0).sort((Z,Q)=>Q.startedAt.localeCompare(Z.startedAt)).slice(0,$.limit)}async updateSession($){let Z=this.readIndex(),Q=Z.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,J={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:DW()};if($.setRunning)J.status="running",J.endedAt=null,J.exitCode=null;return Z.sessions[$.sessionId]=J,this.writeIndex(Z),{updated:!0,statusLock:J.statusLock}}async deleteSession($,Z){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],Z){for(let J of Object.values(Q.sessions))if(J.parentSessionId===$)delete Q.sessions[J.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let Z=this.readQueue();Z.requests.push({id:Z.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:DW()}),Z.nextId+=1,this.writeQueue(Z)}async claimSpawnRequest($,Z){let Q=this.readQueue(),W=Q.requests.find((J)=>J.rootSessionId===$&&J.parentAgentId===Z&&!J.consumedAt);if(!W)return;return W.consumedAt=DW(),this.writeQueue(Q),W.task}}class LW extends O1{constructor($,Z={}){super(new _B($),Z)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as EN,mkdirSync as NN}from"node:fs";import{resolveSessionDataDir as wN}from"@cline/shared/storage";var _W=`
487
487
  session_id AS sessionId,
488
488
  source,
489
489
  pid,
@@ -510,7 +510,7 @@ ${J}`,$.config.mode)}function K4($,Z){return fN($,Z==="plan"?"plan":Z==="yolo"?"
510
510
  metadata_json AS metadata,
511
511
  hook_path AS hookPath,
512
512
  messages_path AS messagesPath,
513
- updated_at AS updatedAt`;function zW($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let Z=$.metadata;if(typeof Z==="string"&&Z.trim())try{let Q=JSON.parse(Z);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function TW($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function zB($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class TB{store;sessionsDirPath;constructor($,Z=MN()){this.store=$;this.sessionsDirPath=Z}ensureSessionsDir(){if(!ON(this.sessionsDirPath))qN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
513
+ updated_at AS updatedAt`;function zW($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let Z=$.metadata;if(typeof Z==="string"&&Z.trim())try{let Q=JSON.parse(Z);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function TW($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function zB($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class TB{store;sessionsDirPath;constructor($,Z=wN()){this.store=$;this.sessionsDirPath=Z}ensureSessionsDir(){if(!EN(this.sessionsDirPath))NN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
514
514
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
515
515
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
516
516
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -526,19 +526,19 @@ ${J}`,$.config.mode)}function K4($,Z){return fN($,Z==="plan"?"plan":Z==="yolo"?"
526
526
  WHERE session_id = ? AND status_lock = ?`,[$0(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let Z=[],Q=[];if($.status!==void 0)Z.push("status = ?"),Q.push($.status);if($.endedAt!==void 0)Z.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)Z.push("exit_code = ?"),Q.push($.exitCode);if($.prompt!==void 0)Z.push("prompt = ?"),Q.push($.prompt??null);if($.metadata!==void 0)Z.push("metadata_json = ?"),Q.push(TW($.metadata));if($.parentSessionId!==void 0)Z.push("parent_session_id = ?"),Q.push($.parentSessionId??null);if($.parentAgentId!==void 0)Z.push("parent_agent_id = ?"),Q.push($.parentAgentId??null);if($.agentId!==void 0)Z.push("agent_id = ?"),Q.push($.agentId??null);if($.conversationId!==void 0)Z.push("conversation_id = ?"),Q.push($.conversationId??null);if(Z.length===0){let Y=await this.getSession($.sessionId);return{updated:!!Y,statusLock:Y?.statusLock??0}}let W=0;if($.expectedStatusLock!==void 0)W=$.expectedStatusLock+1,Z.push("status_lock = ?"),Q.push(W);Z.push("updated_at = ?"),Q.push($0());let J=`UPDATE sessions SET ${Z.join(", ")} WHERE session_id = ?`;if(Q.push($.sessionId),$.expectedStatusLock!==void 0)J+=" AND status_lock = ?",Q.push($.expectedStatusLock);if((this.store.run(J,Q).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)W=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:W}}async deleteSession($,Z){let Q=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(Z)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
527
527
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,$0()])}async claimSpawnRequest($,Z){let Q=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
528
528
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
529
- ORDER BY id ASC LIMIT 1`,[$,Z]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[$0(),Q.id]),Q.task??void 0}}class Q$ extends T1{store;constructor($,Z={}){super(new TB($,Z.sessionArtifactsDir),Z);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
529
+ ORDER BY id ASC LIMIT 1`,[$,Z]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[$0(),Q.id]),Q.task??void 0}}class Q$ extends O1{store;constructor($,Z={}){super(new TB($,Z.sessionArtifactsDir),Z);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
530
530
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
531
531
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
532
532
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
533
533
  metadata_json, transcript_path, hook_path, messages_path, updated_at
534
- ) 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,$0()])}}import{readdirSync as VP}from"node:fs";import{homedir as HP}from"node:os";import{isAbsolute as BP,join as Q3,resolve as W3}from"node:path";import{captureSdkError as r$,createSessionId as GP,isLikelyAuthError as KP,normalizeUserInput as FP}from"@cline/shared";import{setHomeDirIfUnset as AP}from"@cline/shared/storage";G0();import{createHandlerAsync as CN}from"@cline/llms";import{CHARS_PER_TOKEN as ep,estimateTokens as OW}from"@cline/shared";var MB=200000,RB=0.9,m5=0.7,EB=16384,qW=20000,OB=1024,qB=2000,NB=2000,wB=8;function f4($,Z){if($.length<=Z)return $;return`${$.slice(0,Z)}
535
- ...[truncated ${$.length-Z} chars]`}function RN($){let Z=MW($);if(typeof Z==="string")return Z;return Z.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
534
+ ) 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,$0()])}}import{readdirSync as KP}from"node:fs";import{homedir as FP}from"node:os";import{isAbsolute as AP,join as Q3,resolve as W3}from"node:path";import{captureSdkError as i$,createSessionId as fP,isLikelyAuthError as UP,normalizeUserInput as DP}from"@cline/shared";import{setHomeDirIfUnset as LP}from"@cline/shared/storage";G0();import{createHandlerAsync as yN}from"@cline/llms";import{CHARS_PER_TOKEN as Wr,estimateTokens as OW}from"@cline/shared";var MB=200000,RB=0.9,v5=0.7,EB=16384,qW=20000,OB=1024,qB=2000,NB=2000,wB=8;function f4($,Z){if($.length<=Z)return $;return`${$.slice(0,Z)}
535
+ ...[truncated ${$.length-Z} chars]`}function CN($){let Z=MW($);if(typeof Z==="string")return Z;return Z.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
536
536
  ${Q.content}
537
537
  </file>`;case"image":return`[image:${Q.mediaType}]`;default:return""}}).join(`
538
- `)}function MW($){if(typeof $==="string")return f4($,qB);return $.map((Z)=>{switch(Z.type){case"text":return{...Z,text:f4(Z.text,qB)};case"file":return{...Z,content:f4(Z.content,NB)};case"image":return Z;default:return Z}})}function EN($){return Object.entries($).map(([Z,Q])=>`${Z}=${JSON.stringify(Q)}`).join(", ")}function CB($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let Z=[];for(let Q of $.content)switch(Q.type){case"text":Z.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":Z.push(`[Bot thinking]: ${f4(Q.thinking,2000)}`);break;case"redacted_thinking":Z.push("[Bot thinking]: [redacted]");break;case"tool_use":Z.push(`[Bot tool calls]: ${Q.name}(${EN(Q.input)})`);break;case"tool_result":Z.push(`[Tool result]: ${RN(Q.content)}`);break;case"file":Z.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${f4(Q.content,NB)}`);break;case"image":Z.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return Z.join(`
538
+ `)}function MW($){if(typeof $==="string")return f4($,qB);return $.map((Z)=>{switch(Z.type){case"text":return{...Z,text:f4(Z.text,qB)};case"file":return{...Z,content:f4(Z.content,NB)};case"image":return Z;default:return Z}})}function PN($){return Object.entries($).map(([Z,Q])=>`${Z}=${JSON.stringify(Q)}`).join(", ")}function CB($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let Z=[];for(let Q of $.content)switch(Q.type){case"text":Z.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":Z.push(`[Bot thinking]: ${f4(Q.thinking,2000)}`);break;case"redacted_thinking":Z.push("[Bot thinking]: [redacted]");break;case"tool_use":Z.push(`[Bot tool calls]: ${Q.name}(${PN(Q.input)})`);break;case"tool_result":Z.push(`[Tool result]: ${CN(Q.content)}`);break;case"file":Z.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${f4(Q.content,NB)}`);break;case"image":Z.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return Z.join(`
539
539
  `)}function PB($){return $.map(CB).join(`
540
540
 
541
- `).trim()}function SB(){let $=new WeakMap;return(Z)=>{let Q=Z,W=$.get(Q);if(typeof W==="number")return W;let J;try{J=JSON.stringify(Z)}catch{J=CB(Z)}let X=OW(J.length);return $.set(Q,X),X}}function U4($){return $.metadata?.kind==="compaction_summary"}function RW($){if(!U4($))return;let Z=$.metadata;if(!Z)return;let Q=Z.details;return{kind:"compaction_summary",summary:String(Z.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(Z.tokensBefore??0),generatedAt:Number(Z.generatedAt??0)}}function NN($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((Z)=>Z.type==="tool_result")}function D4($){return $.role==="user"&&!NN($)&&!U4($)}function bB($){for(let Z=0;Z<$.length;Z+=1)if(D4($[Z]))return Z;return-1}function v5($){for(let Z=$.length-1;Z>=0;Z-=1)if(D4($[Z]))return Z;return 0}function yB($){for(let Z=$.length-1;Z>=0;Z-=1)if($[Z].role==="assistant")return Z;return-1}function hB($){for(let Z=$.length-1;Z>=0;Z-=1)if(U4($[Z]))return Z;return-1}function kB($,Z,Q){let W=v5($);if(W<=0)return 0;let J=0,X=$.length;for(let j=$.length-1;j>=0;j-=1)if(J+=Q($[j]),X=j,J>=Z)break;if(X<=0)return 0;let Y=Math.min(X,W);while(Y>0&&!D4($[Y]))Y-=1;return Y}function A4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((Z)=>A4(Z));if($&&typeof $==="object"){let Z=$,Q=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...A4(Z[W]));if(Array.isArray(Z.files)){for(let W of Z.files)if(W&&typeof W==="object")Q.push(...A4(W.path))}if(Array.isArray(Z.file_paths))Q.push(...A4(Z.file_paths));return Q}return[]}function F4($,Z){let Q=new Set($);for(let W of Z){let J=W.trim();if(!J)continue;Q.add(J)}return[...Q].sort((W,J)=>W.localeCompare(J))}function IB($){let Z=[],Q=[];for(let W of $){let J=RW(W);if(J){Z=F4(Z,J.details.readFiles),Q=F4(Q,J.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let X of W.content){if(X.type==="file"){Z=F4(Z,[X.path]);continue}if(X.type!=="tool_use")continue;let Y=A4(X.input);if(X.name==="read_files"){Z=F4(Z,Y);continue}if(X.name==="editor"||X.name==="apply_patch")Q=F4(Q,Y)}}return{readFiles:Z,modifiedFiles:Q}}function wN($){let Z=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
541
+ `).trim()}function SB(){let $=new WeakMap;return(Z)=>{let Q=Z,W=$.get(Q);if(typeof W==="number")return W;let J;try{J=JSON.stringify(Z)}catch{J=CB(Z)}let X=OW(J.length);return $.set(Q,X),X}}function U4($){return $.metadata?.kind==="compaction_summary"}function RW($){if(!U4($))return;let Z=$.metadata;if(!Z)return;let Q=Z.details;return{kind:"compaction_summary",summary:String(Z.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(Z.tokensBefore??0),generatedAt:Number(Z.generatedAt??0)}}function SN($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((Z)=>Z.type==="tool_result")}function D4($){return $.role==="user"&&!SN($)&&!U4($)}function bB($){for(let Z=0;Z<$.length;Z+=1)if(D4($[Z]))return Z;return-1}function c5($){for(let Z=$.length-1;Z>=0;Z-=1)if(D4($[Z]))return Z;return 0}function yB($){for(let Z=$.length-1;Z>=0;Z-=1)if($[Z].role==="assistant")return Z;return-1}function hB($){for(let Z=$.length-1;Z>=0;Z-=1)if(U4($[Z]))return Z;return-1}function kB($,Z,Q){let W=c5($);if(W<=0)return 0;let J=0,X=$.length;for(let j=$.length-1;j>=0;j-=1)if(J+=Q($[j]),X=j,J>=Z)break;if(X<=0)return 0;let Y=Math.min(X,W);while(Y>0&&!D4($[Y]))Y-=1;return Y}function A4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((Z)=>A4(Z));if($&&typeof $==="object"){let Z=$,Q=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...A4(Z[W]));if(Array.isArray(Z.files)){for(let W of Z.files)if(W&&typeof W==="object")Q.push(...A4(W.path))}if(Array.isArray(Z.file_paths))Q.push(...A4(Z.file_paths));return Q}return[]}function F4($,Z){let Q=new Set($);for(let W of Z){let J=W.trim();if(!J)continue;Q.add(J)}return[...Q].sort((W,J)=>W.localeCompare(J))}function IB($){let Z=[],Q=[];for(let W of $){let J=RW(W);if(J){Z=F4(Z,J.details.readFiles),Q=F4(Q,J.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let X of W.content){if(X.type==="file"){Z=F4(Z,[X.path]);continue}if(X.type!=="tool_use")continue;let Y=A4(X.input);if(X.name==="read_files"){Z=F4(Z,Y);continue}if(X.name==="editor"||X.name==="apply_patch")Q=F4(Q,Y)}}return{readFiles:Z,modifiedFiles:Q}}function bN($){let Z=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
542
542
  `):"- none",Q=$.modifiedFiles.length>0?$.modifiedFiles.map((W)=>`- ${W}`).join(`
543
543
  `):"- none";return`## Files
544
544
  Read:
@@ -546,7 +546,7 @@ ${Z}
546
546
  Modified:
547
547
  ${Q}`}function xB($,Z){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
548
548
 
549
- ${wN(Z)}`.trim()}function gB($){let Z=[`Summarize this session for continuation. Be concise and factual.
549
+ ${bN(Z)}`.trim()}function gB($){let Z=[`Summarize this session for continuation. Be concise and factual.
550
550
 
551
551
  ## Goal
552
552
  One sentence: what is being built or fixed.
@@ -570,17 +570,17 @@ ${$.conversationText||"(empty)"}`),Z.join(`
570
570
 
571
571
  `)}function mB($){let Z=$.summarizer,Q=(J)=>{if(J.providerId==="openai-codex"){let{maxOutputTokens:X,...Y}=J;return{...Y,thinking:!1}}return{...J,maxOutputTokens:J.maxOutputTokens??OB,thinking:!1}};if(!Z)return Q($.activeProviderConfig);let W=Z.providerConfig?.providerId===Z.providerId?Z.providerConfig:void 0;return Q({...W??{},providerId:Z.providerId,modelId:Z.modelId,apiKey:Z.apiKey??W?.apiKey,baseUrl:Z.baseUrl??W?.baseUrl,headers:Z.headers??W?.headers,knownModels:Z.knownModels??W?.knownModels,maxOutputTokens:Z.maxOutputTokens??OB})}function vB($){return{role:"user",content:`Context summary:
572
572
 
573
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function PN($){let Z=await CN($.providerConfig),Q="";for await(let W of Z.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){Q+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function SN($){try{return JSON.stringify($).length}catch{return String($).length}}async function cB($){let Z=$.context.messages;if(Z.length<2)return;let Q=kB(Z,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=Z.length)return;let W=Z.slice(0,Q),J=hB(W),X=J>=0?RW(W[J])?.summary:void 0,Y=J>=0?W.slice(J+1):W;if(Y.length===0)return;let j=IB(W),V=PB(Y),H=gB({previousSummary:X,conversationText:V,fileOps:j});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:Y.length,preservedMessages:Z.length-Q,previousSummaryChars:X?.length??0,conversationTextChars:V.length,summaryRequestChars:H.length,summaryRequestEstimatedTokens:OW(H.length),newMessagesJsonChars:SN(Y),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let B=await PN({providerConfig:mB({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:H,logger:$.logger});if(!B.trim())return;let G=xB(B,j),K=Z.reduce((L,f)=>L+$.estimateMessageTokens(f),0),F=[vB({summary:G,fileOps:j,tokensBefore:K}),...Z.slice(Q)],A=F.reduce((L,f)=>L+$.estimateMessageTokens(f),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:Z.length,messagesAfter:F.length,messagesSummarized:Q,messagesPreserved:Z.length-Q,tokensBefore:K,tokensAfter:A,maxInputTokens:$.context.maxInputTokens}),{messages:F}}import{CHARS_PER_TOKEN as bN}from"@cline/shared";function yN($){if(U4($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let Z=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(Z.length===0)return;return{...$,content:Z.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:MW(Q.content)}:Q)}}function hN($,Z){return $.reduce((Q,W)=>Q+Z(W),0)}function uB($,Z){if($.length<=Z)return $;let Q=`
574
- ...`,W=Math.max(1,Z-Q.length);return`${$.slice(0,W)}${Q}`}function dB($,Z){let Q=Number.isFinite(Z)?Math.max(1,Z):1,W=Math.max(16,Q*bN);if(typeof $.content==="string"){let Y=uB($.content,W).trim();return{...$,content:Y||"..."}}let J=W,X=$.content.map((Y)=>{if(Y.type!=="text"||J<=0)return Y;let j=uB(Y.text,J).trim();return J-=j.length,{...Y,text:j||"..."}});return{...$,content:X}}function kN($,Z){let Q=bB($),W=v5($),J=yB($),X=[],Y=0;for(let j=0;j<$.length;j+=1){let V=yN($[j]);if(!V)continue;let H=Z(V);Y+=H,X.push({index:j,message:V,estimatedTokens:H,toolPairIds:pB(V),isFirstUser:j===Q,isLastUser:j===W,isLastAssistant:j===J})}return{candidates:X,totalTokens:Y}}function lB($,Z,Q,W){let J=$[Z],X=J.estimatedTokens;return J.message=Q,J.estimatedTokens=W(Q),J.toolPairIds=pB(Q),J.estimatedTokens-X}function pB($){if(!Array.isArray($.content))return[];let Z=[];for(let Q of $.content)if(Q.type==="tool_use")Z.push(Q.id);else if(Q.type==="tool_result")Z.push(Q.tool_use_id);return Z}function IN($){let Z=new Map;for(let Q of $)for(let W of Q.toolPairIds){let J=Z.get(W);if(J)J.add(Q);else Z.set(W,new Set([Q]))}return Z}function xN($,Z,Q){let W=new Set,J=[Q],X=0;while(X<J.length){let Y=J[X];if(X+=1,Y===void 0||!$.has(Y)||W.has(Y))continue;W.add(Y);for(let j of Y.toolPairIds)for(let V of Z.get(j)??[])if(!W.has(V))J.push(V)}return W}function gN($,Z){let Q=0;for(let W of $){if(Z.has(W))continue;$[Q]=W,Q+=1}$.length=Q}function c5($,Z,Q,W){let J=new Set($),X=IN($);for(let Y=0;Y<$.length&&W>Q;){if(!Z($[Y])){Y+=1;continue}let j=xN(J,X,$[Y]);if(j.size===0){Y+=1;continue}let V=0;for(let H of j)V+=H.estimatedTokens,J.delete(H);W-=V,gN($,j)}return W}function mN($,Z,Q,W,J){if(Q<=Z)return Q;for(let Y=$.length-1;Y>=0&&Q>Z;Y-=1){let j=$[Y];if(j.isFirstUser)continue;let V=Math.max(wB,j.estimatedTokens-(Q-Z));if(V>=j.estimatedTokens)continue;Q+=lB($,Y,dB(j.message,V),J)}if(Q<=Z)return Q;let X=$.findIndex((Y)=>Y.isFirstUser);if(X>=0){if($[X].estimatedTokens<=W)return Q;while(Q>Z){let j=$[X],V=Math.max(1,j.estimatedTokens-(Q-Z));if(V>=j.estimatedTokens)break;let H=j.estimatedTokens;if(Q+=lB($,X,dB(j.message,V),J),j.estimatedTokens>=H)break}}return Q}function vN($,Z){return JSON.stringify($)!==JSON.stringify(Z)}function cN($){let Z=v5($);if(Z<0||Z===0&&!D4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,Z),protectedTail:$.slice(Z)}}function rB($){let Z=Math.max(1,Math.min($.context.targetTokens??Math.floor($.context.triggerTokens*m5),$.context.maxInputTokens)),{compactable:Q,protectedTail:W}=cN($.context.messages);if(Q.length===0)return;let J=hN(W,$.estimateMessageTokens),X=Math.max(1,Z-J),Y=kN(Q,$.estimateMessageTokens),{candidates:j}=Y;if(j.length===0)return;let V=Y.totalTokens,H=V;H=c5(j,(F)=>F.message.role==="assistant"&&!F.isLastAssistant,X,H),H=c5(j,(F)=>F.message.role==="user"&&!F.isFirstUser&&!F.isLastUser,X,H),H=c5(j,(F)=>F.message.role==="assistant"&&F.isLastAssistant,X,H),H=c5(j,(F)=>F.message.role==="user"&&F.isLastUser&&!F.isFirstUser,X,H),H=mN(j,X,H,$.context.triggerTokens,$.estimateMessageTokens);let B=[...j.map((F)=>F.message),...W];if(!vN($.context.messages,B))return;let G=V+J,K=H+J;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:B.length,messagesRemoved:$.context.messages.length-B.length,tokensBefore:G,tokensAfter:K,targetTokens:Z,maxInputTokens:$.context.maxInputTokens}),{messages:B}}var uN=0.5,dN=0.5;function iB($){try{return JSON.stringify($).length}catch{return String($).length}}function L4($){return typeof $==="number"&&Number.isFinite($)&&$>0}function lN($){let Z=[];if(L4($.configMaxInputTokens))Z.push($.configMaxInputTokens);if(L4($.modelMaxInputTokens))Z.push($.modelMaxInputTokens);if(L4($.contextWindow)){Z.push($.contextWindow);let Q=L4($.modelMaxTokens)?$.contextWindow-$.modelMaxTokens:void 0;if(L4(Q)&&Q>=$.contextWindow*uN)Z.push(Q)}return Z.length>0?Math.min(...Z):MB}function pN($){let Z=0,Q=0,W=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let X of J.content){if(X.type!=="tool_result")continue;let Y=iB(X.content);Z+=1,Q+=Y,W=Math.max(W,Y)}}return{toolResultCount:Z,toolResultSerializedChars:Q,maxToolResultSerializedChars:W}}var rN={basic:({context:$,estimateMessageTokens:Z,logger:Q})=>rB({context:$,estimateMessageTokens:Z,logger:Q}),agentic:({context:$,providerConfig:Z,compaction:Q,mode:W,estimateMessageTokens:J,logger:X})=>cB({context:$,providerConfig:Z,summarizer:Q?.summarizer,preserveRecentTokens:W==="manual"?Math.min(Q?.preserveRecentTokens??qW,$.triggerTokens):Q?.preserveRecentTokens??qW,estimateMessageTokens:J,logger:X})};function iN($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio==="number"){let Q=$.config.thresholdRatio,W=$.maxInputTokens*Q;return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:Q}}let Z=Math.max(0,Math.min($.maxInputTokens-EB,$.maxInputTokens*RB));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function nN($){let Z=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,Z)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function aN($){let Z=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*dN):Math.floor($.triggerTokens*m5),Q=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(Z,$.maxInputTokens,Q))}function sN($){let Z=0,Q=!1;for(let W of $)if(W.role==="user")Q=!0;else if(W.role==="assistant"&&Q)Z+=1,Q=!1;return Z}function EW($,Z={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=SB(),X=Q?.strategy??"basic",Y=rN[X],j=Z.mode??"auto",V=Q?.compact?"custom":X;return async(H)=>{let B=H.apiMessages.reduce((M,E)=>M+J(E),0),G=lN({configMaxInputTokens:Q?.maxInputTokens,modelMaxInputTokens:H.model.info?.maxInputTokens,contextWindow:H.model.info?.contextWindow,modelMaxTokens:H.model.info?.maxTokens}),K=iN({inputTokens:B,maxInputTokens:G,config:{maxInputTokens:Q?.maxInputTokens,reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:j,strategy:X,iteration:H.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:B,maxInputTokens:G,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,shouldCompact:K.shouldCompact,messageCount:H.messages.length,apiMessageCount:H.apiMessages.length,apiMessagesJsonChars:iB(H.apiMessages),...pN(H.apiMessages)}),j==="auto"&&!K.shouldCompact)return;let F=j==="manual"?nN({inputTokens:B,maxInputTokens:G,autoTriggerTokens:K.triggerTokens,manualTargetRatio:Z.manualTargetRatio}):K,A=j==="auto"?aN({maxInputTokens:G,modelMaxTokens:H.model.info?.maxTokens,triggerTokens:F.triggerTokens,messagePairCount:sN(H.messages)}):void 0,L={agentId:H.agentId,conversationId:H.conversationId,parentAgentId:H.parentAgentId,iteration:H.iteration,messages:H.messages,model:H.model,maxInputTokens:G,triggerTokens:F.triggerTokens,targetTokens:A,thresholdRatio:F.thresholdRatio,utilizationRatio:G>0?B/G:0},f=j==="manual"?"manual_compaction":"auto_compaction";H.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:f,reason:f,iteration:H.iteration,triggerTokens:F.triggerTokens,maxInputTokens:G});let D=H.messages.length,U=Date.now(),T=Q?.compact?await Q.compact(L):await Y({context:L,providerConfig:{...W,abortSignal:H.abortSignal},compaction:Q,mode:j,estimateMessageTokens:J,logger:$.logger}),O=Date.now()-U,z=$.sessionId??H.conversationId,_={agentId:H.agentId,conversationId:H.conversationId,parentAgentId:H.parentAgentId??void 0};if(T?.messages){let M=T.messages.reduce((E,P)=>E+J(P),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:X,maxInputTokens:G,inputTokens:B,afterTokens:M,tokensSaved:B-M,utilizationBefore:`${(B/G*100).toFixed(1)}%`,utilizationAfter:`${(M/G*100).toFixed(1)}%`,thresholdTrigger:`${(F.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:T.messages.length,messagesRemoved:D-T.messages.length}),HZ($.telemetry,{ulid:z,strategy:V,mode:j,messagesBefore:D,messagesAfter:T.messages.length,messagesRemoved:D-T.messages.length,tokensBefore:B,tokensAfter:M,tokensSaved:B-M,triggerTokens:F.triggerTokens,maxInputTokens:G,thresholdRatio:F.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,..._})}else BZ($.telemetry,{ulid:z,strategy:V,mode:j,reason:"no_result",tokensBefore:B,triggerTokens:F.triggerTokens,maxInputTokens:G,thresholdRatio:F.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,..._});return T}}G0();function L0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function f0($,Z){return{inputTokens:$.inputTokens+Math.max(0,Z.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,Z.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,Z.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,Z.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,Z.totalCost??0)}}function u5($){let Z=L0();for(let Q of $)Z=f0(Z,Q);return Z}function v2($){return typeof $==="number"&&Number.isFinite($)?$:0}function d5($){let Z=L0();for(let Q of $){let W=Q.metrics;if(!W)continue;Z=f0(Z,{inputTokens:v2(W.inputTokens),outputTokens:v2(W.outputTokens),cacheReadTokens:v2(W.cacheReadTokens),cacheWriteTokens:v2(W.cacheWriteTokens),totalCost:v2(W.cost)})}return Z}function oN($){for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(Q?.role!=="assistant")continue;let W=v2(Q.metrics?.inputTokens);return W>0?W:void 0}return}function tN($){if(!$||typeof $!=="object")return;let Z=$,Q=Z.skill??Z.skill_name??Z.skillName;if(typeof Q!=="string")return;let W=Q.trim();return W.length>0?W:void 0}function NW($){if(!$||typeof $!=="object")return{};let Z=$;return{agentId:typeof Z.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z.parentAgentId==="string"?Z.parentAgentId:void 0}}function O1($){let Z=$.agentId?.trim();if(!Z)return;let Q=$.parentAgentId?.trim()||void 0,W=$.teamRole,J="root";if(W==="teammate")J="team_teammate";else if(W==="lead")J="team_lead";else if(Q)J="subagent";return{agentId:Z,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function eN($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function $w($){let Z=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of Z){let W=Q?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function wW($,Z,Q){let{sessionId:W,config:J,liveSession:X,emit:Y}=$,j=J.telemetry,V=X?.runtime.teamRuntime,H=Q?.isPrimaryAgentEvent??!0,B=NW(Z),G=O1({agentId:Q?.agentId??B.agentId,conversationId:Q?.conversationId??B.conversationId,parentAgentId:Q?.parentAgentId??B.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??V?.getTeamId(),teamName:Q?.teamName??V?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(Z.type==="content_start"&&Z.contentType==="tool"&&Z.toolName==="skills"){let K=tN(Z.input);if(K)QZ(j,{ulid:W,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(Z.type==="content_end"&&Z.contentType==="tool"){let K=Z.toolName??"unknown",F=!Z.error;if(Q8(j,{ulid:W,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))WZ(j,{ulid:W,modelId:J.modelId,provider:J.providerId,errorType:Z.error,...G})}if(Z.type==="notice"&&Z.reason==="api_error")u4(j,{ulid:W,model:J.modelId,provider:J.providerId,errorMessage:Z.message,...G});if(Z.type==="error")u4(j,{ulid:W,model:J.modelId,provider:J.providerId,errorMessage:Z.error?.message??"unknown error",...G});if(Z.type==="usage"&&X?.turnUsageBaseline){let K=eN(Z);if(H){X.turnPrimaryUsage=f0(X.turnPrimaryUsage??L0(),K);let A=f0(X.turnUsageBaseline,X.turnPrimaryUsage);$.usageBySession.set(W,A),Z8(j,{ulid:W,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),$Z(j,{ulid:W,tokensIn:Z.inputTokens,tokensOut:Z.outputTokens,cacheWriteTokens:Z.cacheWriteTokens,cacheReadTokens:Z.cacheReadTokens,totalCost:Z.cost,model:J.modelId,...G})}else{let A=$w({isPrimaryAgentEvent:H,overrides:Q,eventMetadata:B}),L=X.turnUsageByAgent??new Map;X.turnUsageByAgent=L,L.set(A,f0(L.get(A)??L0(),K))}let F=f0(X.turnPrimaryUsage??L0(),u5(X.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,f0(X.turnAggregateUsageBaseline??X.turnUsageBaseline,F))}if(Z.type==="iteration_end"&&H)$.persistMessages(W,X?.agent.getMessages()??[],X?.config.systemPrompt);Y({type:"agent_event",payload:{sessionId:W,event:Z,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(H?"lead":void 0):void 0}}),Y({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:WH(Z),ts:Date.now()}})}function W$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as ww}from"@cline/shared";import{spawn as Hw}from"node:child_process";import{appendFileSync as Bw,readFileSync as Gw}from"node:fs";import{join as Kw}from"node:path";import{augmentNodeCommandForDebug as oB,withResolvedClineBuildEnv as hW}from"@cline/shared";import{ensureHookLogDir as aB}from"@cline/shared/storage";function l5($,Z){if(!Z)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:Z}}import{existsSync as Zw,readdirSync as Qw}from"node:fs";import{basename as Ww,extname as Jw,join as Xw}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as nB,resolveHooksConfigSearchPaths as Yw}from"@cline/shared/storage";function CW($){return Yw($)}var p5;((B)=>{B.TaskStart="TaskStart";B.TaskResume="TaskResume";B.TaskCancel="TaskCancel";B.TaskComplete="TaskComplete";B.TaskError="TaskError";B.PreToolUse="PreToolUse";B.PostToolUse="PostToolUse";B.UserPromptSubmit="UserPromptSubmit";B.PreCompact="PreCompact";B.SessionShutdown="SessionShutdown"})(p5||={});var PW={["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"},jw=new Map(Object.values(p5).map(($)=>[$.toLowerCase(),$])),Vw=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function SW($){let Z=Jw($).toLowerCase();if(!Vw.has(Z))return;let Q=Ww($,Z).trim().toLowerCase();return jw.get(Q)}function c2($){let Z=[],Q=new Set,W=CW($).filter((J)=>Zw(J));for(let J of W)try{for(let X of Qw(J,{withFileTypes:!0})){if(!X.isFile())continue;let Y=SW(X.name);if(!Y)continue;let j=Xw(J,X.name);if(Q.has(j))continue;Q.add(j),Z.push({fileName:Y,hookEventName:PW[Y],path:j})}}catch{}return Z.sort((J,X)=>J.path.localeCompare(X.path))}function i5($){if(!$||typeof $!=="object")return{};let Z={};for(let[Q,W]of Object.entries($))Z[Q]=typeof W==="string"?W:JSON.stringify(W);return Z}function r5($,Z,Q){let W=Q instanceof Error?`: ${Q.message}`:"",J=`${Z}${W}`;if($){try{$.log(J,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(J)}function Fw($,Z){if(!Z)return $;if(!$)return{...Z};let Q=[$.context,Z.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
575
- `),W=[...$.appendMessages??[],...Z.appendMessages??[]];return{cancel:$.cancel===!0||Z.cancel===!0?!0:void 0,review:$.review===!0||Z.review===!0?!0:void 0,context:Q||void 0,overrideInput:Z.overrideInput!==void 0?Z.overrideInput:$.overrideInput,systemPrompt:Z.systemPrompt!==void 0?Z.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function Aw($){if(!$||typeof $!=="object")return;let Z=$,Q=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:Q,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function bW($){let Z=String($??"").toLowerCase();return Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt")}function U0($,Z){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:Z.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:Z.workspacePath?[Z.workspacePath]:[],workspaceInfo:Z.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function fw($){let Z=$.trim();if(!Z)return{};let W=Z.split(`
576
- `).map((X)=>X.trim()).filter(Boolean).filter((X)=>X.startsWith("HOOK_CONTROL\t")).map((X)=>X.slice(13)),J=W.length>0?W[W.length-1]:Z;try{return{parsedJson:JSON.parse(J)}}catch(X){return{parseError:X instanceof Error?X.message:"Failed to parse hook stdout JSON"}}}async function Uw($,Z){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((W,J)=>{let X=!1,Y=()=>{Q.off("error",V),Q.off("finish",H),$.off("close",B)},j=(G)=>{if(X)return;if(X=!0,Y(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){W();return}J(G);return}W()},V=(G)=>j(G),H=()=>j(),B=()=>j();Q.on("error",V),Q.once("finish",H),$.once("close",B);try{Q.end(Z)}catch(G){j(G)}})}async function tB($,Z){if(Z.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await sB($,Z)}catch(Q){let W=_w(Z.command,process.platform,Q);if(!W)throw Q;return await sB($,{...Z,command:W})}}async function sB($,Z){let Q=oB(Z.command,{env:Z.env,debugRole:"hook"}),W=Hw(Q[0],Q.slice(1),{cwd:Z.cwd,env:hW(Z.env),stdio:Z.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z.detached,windowsHide:!0}),J=new Promise((K)=>{W.once("spawn",()=>K())}),X=new Promise((K,F)=>{W.once("error",(A)=>F(A))}),Y=JSON.stringify($);if(await Promise.race([J,X]),await Uw(W,Y),Z.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let j="",V="",H=!1,B;W.stdout.on("data",(K)=>{j+=K.toString()}),W.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((Z.timeoutMs??0)>0)B=setTimeout(()=>{H=!0,W.kill("SIGKILL")},Z.timeoutMs);W.once("close",(F)=>{if(B)clearTimeout(B);let{parsedJson:A,parseError:L}=fw(j);K({exitCode:F,stdout:j,stderr:V,parsedJson:A,parseError:L,timedOut:H})})});return await Promise.race([G,X])}function Dw($){try{let Q=Gw($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let W=Q.slice(2).trim();if(!W)return;let J=W.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function Lw($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function _w($,Z=process.platform,Q){if(Z!=="win32"||!Lw(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function eB($){if($.length===0)return;let[Z,...Q]=$,W=Z.replace(/\\/g,"/").toLowerCase(),J=W.split("/").at(-1)??W;if(J==="env")return eB(Q);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Q];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Q]:[J,...Q];return $}function zw($){let Z=Dw($);if(Z&&Z.length>0)return[...eB(Z)??Z,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return oB(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Tw($){let Z={};for(let Q of c2($)){if(!Q.hookEventName)continue;let W=Q.hookEventName,J=Z[W]??[];J.push(zw(Q.path)),Z[W]=J}return Z}async function Ow($){let Z;for(let Q of $.commands){let W=Q.join(" ");try{let J=await tB($.payload,{command:Q,cwd:$.cwd,env:hW(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){r5($.logger,`hook command timed out: ${W}`);continue}if(J?.parseError){r5($.logger,`hook command returned invalid JSON control output: ${W} (${J.parseError})`);continue}Z=Fw(Z,Aw(J?.parsedJson))}catch(J){r5($.logger,`hook command failed: ${W}`,J)}}return Z}function d$($){for(let Z of $.commands){let Q=Z.join(" ");tB($.payload,{command:Z,cwd:$.cwd,env:hW(process.env),detached:!0}).catch((W)=>{r5($.logger,`hook command failed: ${Q}`,W)})}}function J$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function yW($,Z){return{...J$($.snapshot),userMessage:Z}}function $G($){return{...J$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function ZG($){return{...J$($.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 QG($){return $.filter((Z)=>Z.type==="text"&&typeof Z.text==="string").map((Z)=>Z.text).join("")}function qw($){if(!$)return;let Z={};if($.cancel===!0)Z.stop=!0;if($.overrideInput!==void 0)Z.input=$.overrideInput;return Object.keys(Z).length>0?Z:void 0}function n5($){let Z={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(W)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...W})}
577
- `,Y=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Kw(aB(),"hooks.jsonl");aB(Y),Bw(Y,J,"utf8")};return{beforeRun:async(W)=>{let J=yW(W,"");Q({...U0(J,Z),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let J=$G(W);Q({...U0(J,Z),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:i5(J.call.input)}});return},afterTool:async(W)=>{let J=ZG(W);Q({...U0(J,Z),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:i5(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:W,result:J})=>{let X=J$(W);if(J.status==="completed"){Q({...U0(X,Z),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||bW(J.error?.message)){Q({...U0(X,Z),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Q({...U0(X,Z),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let J=yW({snapshot:W.snapshot},QG(W.message.content));Q({...U0(J,Z),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function kW($){let Z=Tw($.workspacePath);if(!Object.values(Z).some((G)=>G.length>0))return;let W=async(G,K)=>{let F=Z[K]??[];if(F.length===0)return;d$({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...U0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=Z.prompt_submit??[];if(K.length>0)d$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},X=async(G)=>{let K=Z.tool_call??[];if(K.length===0)return;return Ow({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(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:i5(G.call.input)}}})},Y=async(G)=>{let K=Z.tool_result??[];if(K.length===0)return;d$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:i5(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}}})},j=async(G)=>{let K=Z.agent_end??[];if(K.length===0)return;d$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=Z.agent_error??[];if(K.length===0)return;d$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},H=async(G)=>{if(bW(G.reason)){let F=Z.agent_abort??[];if(F.length>0)d$({commands:F,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=Z.session_shutdown??[];if(K.length===0)return;d$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"session_shutdown",reason:G.reason}})},B={};if((Z.agent_start?.length??0)>0||(Z.agent_resume?.length??0)>0||(Z.prompt_submit?.length??0)>0){if((Z.agent_start?.length??0)>0||(Z.agent_resume?.length??0)>0)B.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(J$(G.snapshot),K);return};if((Z.prompt_submit?.length??0)>0)B.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(yW({snapshot:G.snapshot},QG(G.message.content)))}}if((Z.tool_call?.length??0)>0)B.beforeTool=async(G)=>{let K=await X($G(G));return qw(K)};if((Z.tool_result?.length??0)>0)B.afterTool=async(G)=>{await Y(ZG(G));return};if((Z.agent_end?.length??0)>0)B.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await j({...J$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((Z.agent_error?.length??0)>0||(Z.agent_abort?.length??0)>0||(Z.session_shutdown?.length??0)>0){let G=B.afterRun;B.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||bW(A.error?.message)){await H({...J$(F),reason:A.error?.message});return}if(A.error)await V({...J$(F),iteration:A.iterations,error:A.error})}}return B}function a5($){return l5("core.hook_config_files",kW($))}function l$($,Z){let Q=$.map((W)=>W[Z]).filter((W)=>typeof W==="function");if(Q.length===0)return;return async(W)=>{let J;for(let X of Q){let Y=await X(W);if(!Y||typeof Y!=="object")continue;let j=Y;J={...J??{},...j,stop:J?.stop===!0||j.stop===!0?!0:j.stop,options:J?.options||j.options?{...J?.options??{},...j.options??{}}:void 0}}return J}}function _4($){let Z=$.filter((Q)=>Q!==void 0);if(Z.length===0)return;return{beforeRun:l$(Z,"beforeRun"),afterRun:l$(Z,"afterRun"),beforeModel:l$(Z,"beforeModel"),afterModel:l$(Z,"afterModel"),beforeTool:l$(Z,"beforeTool"),afterTool:l$(Z,"afterTool"),onEvent:l$(Z,"onEvent")}}import{z as X$}from"zod";var z4=V2;var WG=X$.object({settings:V2,updatedAt:X$.string().datetime(),tokenSource:X$.enum(["manual","oauth","migration"]).default("manual")}),s5=X$.object({version:X$.literal(1),lastUsedProvider:X$.string().min(1).optional(),providers:X$.record(X$.string(),WG)});function u2(){return{version:1,providers:{}}}r0();import{upsertWorkspaceInfo as Mw,WorkspaceManifestSchema as IW}from"@cline/shared";class o5{manifest;listeners=new Set;constructor($){this.manifest=IW.parse($??{workspaces:{}})}async addWorkspacePath($){let Z=await f5($);return this.manifest=Mw(this.manifest,Z),this.emit({type:"workspace_added",workspace:Z}),Z}async switchWorkspace($){let Z=S$($),Q=this.manifest.workspaces[Z];if(Q)return this.manifest=IW.parse({...this.manifest,currentWorkspacePath:Z}),this.emit({type:"workspace_switched",workspace:Q}),Q;let W=await this.addWorkspacePath(Z);return this.manifest=IW.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let Z=S$($);return this.manifest.workspaces[Z]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let Z of this.listeners)Z($)}}G0();import{createHash as Rw}from"node:crypto";var JG=new Set,XG=new Set;function Ew($){return Rw("sha256").update($).digest("hex")}function Nw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function YG($){if(!$.telemetry)return;let Z=Ew($.rootPath),Q=$.rootCount??1;if(!JG.has(Z))JG.add(Z),s9($.telemetry,{root_count:Q,vcs_types:Nw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!XG.has(Z)){XG.add(Z);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",o9($.telemetry,W,{fallback_to_single_root:!0,workspace_count:Q})}}function Cw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function Pw($,Z,Q){if(Z.length>0)for(let X of Z)Q?.log(X.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(Cw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${W}${J}. Use --verbose for more details.`,{severity:"warn"});for(let X of $)Q?.log(`Plugin initialization failed (${X.phase}) for ${X.pluginPath}`,{severity:"warn",stack:X.stack,pluginPath:X.pluginPath,pluginName:X.pluginName})}function Sw($,Z){let Q=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!Q&&!W)return Z;return{...Z??{},...Q?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function jG($,Z){return ww($,Z)}function bw($){let Z=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;Z+=1}return Z}function yw($){let Z={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||hw($.accessToken);if(Z.originator="cline",Z.session_id=$.sessionId,Z["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)Z["ChatGPT-Account-Id"]=Q;return Z}function hw($){let Z=$?.trim();if(!Z)return;let Q=_0(Z),W=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let J=Q?.organizations?.[0]?.id;if(typeof J==="string"&&J.length>0)return J;let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return}function kw($,Z,Q,W,J){let X=Q.getProviderSettings($.providerId),Y=W||X?.modelCatalog?{...W??{},...X?.modelCatalog??{}}:void 0,j=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,V={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:$.providerId==="openai-codex"?yw({sessionId:Z,configHeaders:$.headers,storedHeaders:X?.headers,accountId:X?.auth?.accountId,accessToken:$.apiKey??X?.auth?.accessToken??X?.apiKey}):$.headers??X?.headers,reasoning:Sw($,X?.reasoning),modelCatalog:Y},H={...B1(V),...j??{}};if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let G=$.fetch??H.fetch??J;if(G)H.fetch=G;return H}async function VG($){let{input:Z,sessionId:Q,providerSettingsManager:W,defaultTelemetry:J,defaultCapabilities:X,defaultToolPolicies:Y,defaultFetch:j,onPluginEvent:V,onTeamEvent:H,createSubAgentLifecycleCallbacks:B,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,L=W$(Z.config),{modelCatalogDefaults:f,userInstructionService:D,configExtensions:U,onTeamRestored:T,...O}=K??{},z=Object.keys(O).length>0?O:void 0,{workspaceInfo:_,workspaceMetadata:M,durationMs:E,vcsType:P,initError:c}=await mV(L),n=z?.extensionContext,a={...n??{},workspace:{..._,...n?.workspace??{}},session:{...n?.session??{},sessionId:Q},logger:n?.logger??z?.logger,telemetry:n?.telemetry??z?.telemetry??J};YG({telemetry:a.telemetry,rootPath:_.rootPath,workspaceInfo:_,rootCount:1,vcsType:P,durationMs:E,initError:c,featureFlagEnabled:!0});let t=a5({cwd:Z.config.cwd,workspacePath:L,rootSessionId:Q,logger:z?.logger,workspaceInfo:_}),p0=QH(z?.hooks)?void 0:n5({rootSessionId:Q,workspacePath:L,workspaceInfo:_}),K$=_4([z?.hooks,p0]),d;if(jG(U,"plugins"))try{d=await L6({pluginPaths:z?.pluginPaths,workspacePath:L,cwd:Z.config.cwd,onEvent:V,providerId:Z.config.providerId,modelId:Z.config.modelId,workspaceInfo:_,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),Pw(d.failures,d.warnings,z?.logger)}catch(Q2){let p9=Q2 instanceof Error?Q2.message:String(Q2);z?.logger?.log?.(`plugin loading failed; continuing without plugins (${p9})`)}let N=b7(t?[t]:void 0,b7(z?.extensions,uZ(d?.extensions))),X0=jG(U,"plugins")?z$(d?.pluginPaths??[]):void 0,Y0={...Z.config,...z??{},sessionId:Q,hooks:K$,extensions:N,extensionContext:a,telemetry:a.telemetry},M0=kw(Y0,Q,W,f,j),$2=_4([Y0.hooks,Y0.checkpoint?.enabled===!0?ZB({cwd:Y0.cwd,sessionId:Q,logger:Y0.logger,createCheckpoint:Y0.checkpoint?.createCheckpoint,initialRunCount:bw(Z.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),Y1={...Y0,providerConfig:M0,workspaceMetadata:M,hooks:$2},t0=Z.toolPolicies??Y0.toolPolicies??Y,$8=T0(X,Z.capabilities),Z2=$8?.requestToolApproval,I4=$8?.toolExecutors,j1=B?.(Y1),x4=new o5({currentWorkspacePath:_.rootPath,workspaces:{[_.rootPath]:_}});return{effectiveInput:Z,config:Y1,providerConfig:M0,workspaceMetadata:M,workspaceInfo:_,extensions:N,hooks:$2,toolPolicies:t0,requestToolApproval:Z2,pluginSandboxShutdown:d?.shutdown,runtimeBuilderInput:{config:Y1,hooks:$2,extensions:N,onTeamEvent:H,createSpawnTool:G,onTeamRestored:T,onSubAgentEvent:j1?.onSubAgentEvent,onSubAgentStart:j1?.onSubAgentStart,onSubAgentEnd:j1?.onSubAgentEnd,userInstructionService:D,pluginSkillDirectories:X0,configExtensions:U,toolExecutors:I4,toolPolicies:t0,workspaceManager:x4,logger:Y1.logger,telemetry:Y1.telemetry,requestToolApproval:Z2}}}import{resolveDocumentsExtensionPath as Iw}from"@cline/shared/storage";G0();function HG($,Z,Q,W,J){if(Q)e9($.telemetry,{ulid:Z,apiProvider:$.providerId,...J});else t9($.telemetry,{ulid:Z,apiProvider:$.providerId,...J});xw($.telemetry,{workspacePath:W})}function xw($,Z){let Q=Iw("Hooks"),W=c2(Z.workspacePath),J=new Map;for(let X of W){let Y=X.hookEventName??"unknown",j=J.get(Y)??{global:0,workspace:0};if(X.path===Q||X.path.startsWith(`${Q}/`))j.global+=1;else j.workspace+=1;J.set(Y,j)}for(let[X,Y]of J.entries())VZ($,X,Y.global,Y.workspace)}function BG($,Z){for(let Q of Z.mentions)YZ($,Q,Z.matchedFiles.includes(Q)?1:0,"file",!Z.matchedFiles.includes(Q));for(let Q of Z.matchedFiles)JZ($,"file",Q.length);for(let Q of Z.ignoredMentions)XZ($,"file","not_found",Q)}import{chmodSync as wG,existsSync as uW,mkdirSync as DC,readFileSync as LC,writeFileSync as _C}from"node:fs";import{basename as CG,dirname as dW}from"node:path";import{resolveProviderSettingsPath as zC}from"@cline/shared/storage";import{existsSync as gw,mkdirSync as mw,readFileSync as vw,writeFileSync as cw}from"node:fs";import{mkdir as uw,readFile as dw,writeFile as lw}from"node:fs/promises";import{dirname as xW,join as pw}from"node:path";import*as w0 from"@cline/llms";import{ModelCapabilitySchema as rw,ProviderCapabilitySchema as iw,ProviderClientSchema as nw,ProviderProtocolSchema as aw}from"@cline/shared";import{z as p}from"zod";var sw=p.object({id:p.string().optional(),name:p.string().optional(),maxTokens:p.number().optional(),contextWindow:p.number().optional(),maxInputTokens:p.number().optional(),capabilities:p.array(rw).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),ow=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:aw.optional(),client:nw.optional(),capabilities:p.array(iw).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),GG=p.object({provider:ow.optional(),models:p.record(p.string(),sw).optional()}).passthrough(),KG=p.object({version:p.literal(1),providers:p.record(p.string(),GG)}),tw=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),t5=new Set;function FG($){return $.split(/[-_]/).filter(Boolean).map((Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)).join(" ")}function p$($){return pw(xW($.getFilePath()),"models.json")}function e5(){return{version:1,providers:{}}}function AG($){let Z=tw.safeParse($);if(!Z.success)return e5();let Q={};for(let[W,J]of Object.entries(Z.data.providers)){let X=GG.safeParse(J);if(X.success)Q[W]=X.data}return{version:1,providers:Q}}function gW($){if(!gw($))return e5();try{let Z=vw($,"utf8");return AG(JSON.parse(Z))}catch{}return e5()}async function d2($){try{let Z=await dw($,"utf8");return AG(JSON.parse(Z))}catch{}return e5()}function fG($,Z){mw(xW($),{recursive:!0});let Q=KG.parse(Z);cw($,`${JSON.stringify(Q,null,2)}
578
- `,"utf8")}async function $9($,Z){await uw(xW($),{recursive:!0});let Q=KG.parse(Z);await lw($,`${JSON.stringify(Q,null,2)}
579
- `,"utf8")}function UG($,Z){return{id:$,name:Z.name??$,supportsAttachments:Z.capabilities?.includes("files"),supportsVision:Z.capabilities?.includes("images"),supportsReasoning:Z.capabilities?.includes("reasoning")||Z.thinkingConfig!=null}}function DG($){if(!$||$.length===0)return;let Z=new Set;if($.includes("reasoning"))Z.add("reasoning");if($.includes("prompt-cache"))Z.add("prompt-cache");if($.includes("tools"))Z.add("tools");return Z.size>0?[...Z]:void 0}function LG($){let Z=new Set;if(!$||$.length===0)return[...Z];if($.includes("streaming"))Z.add("streaming");if($.includes("tools"))Z.add("tools");if($.includes("reasoning"))Z.add("reasoning");if($.includes("prompt-cache"))Z.add("prompt-cache");if($.includes("vision"))Z.add("images"),Z.add("files");return[...Z]}function ew($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function _G($,Z){return $??Z??"openai-chat"}function zG($,Z,Q){return $??Q??(Z==="openai-responses"?"openai":"openai-compatible")}function TG($,Z,Q){let W=new Set(Z?.capabilities??Q??[]);if(Z?.supportsVision)W.add("images");if(Z?.supportsAttachments)W.add("files");if(Z?.supportsReasoning)W.add("reasoning");return{id:$,name:Z?.name??$,maxTokens:Z?.maxTokens,contextWindow:Z?.contextWindow,maxInputTokens:Z?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function $C($,Z){for(let[Q,W]of Object.entries(Z??{})){let J=W.id?.trim()||Q.trim();if(!J)continue;w0.registerModel($,J,TG(J,W))}}function ZC($,Z,Q){return{...Z??{},id:$,name:Z?.name??$,capabilities:Z?.capabilities??Q}}function QC($){return Object.assign({},...w0.resolveProviderModelCatalogKeys($).map((Q)=>w0.getGeneratedModelsForProvider(Q)))}function WC($){let Z=$.provider.trim();if(!Z||w0.isBuiltInProviderId(Z))return;let Q=$.baseUrl?.trim();if(!Q)return;let W=w0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z],J=QC(Z),X=LG($.capabilities),Y=X.length>0?X:void 0,j=$.model?.trim(),V={...J,...W?.models??{}};if(j)V[j]=ZC(j,V[j],Y);let H=Object.keys(V).filter(Boolean),B=j||H[0];if(!B)return;let G=_G($.protocol,W?.provider.protocol),K=zG($.client,G,W?.provider.client);w0.registerProvider({provider:{id:Z,name:W?.provider.name??FG(Z),description:W?.provider.description,protocol:G,client:K,baseUrl:Q,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:B,capabilities:DG($.capabilities)??W?.provider.capabilities,source:"file"},models:V})}function Z9($){for(let Z of Object.values($.providers))WC(Z.settings)}function T4($,Z){let Q=Z.models??{};if(!ew(Z.provider)){$C($,Q);return}let W=LG(Z.provider.capabilities),J=Object.entries(Q).map(([H,B])=>({id:B.id?.trim()||H.trim(),model:B})).filter(({id:H})=>H.length>0),X=Z.provider.defaultModelId?.trim()||J[0]?.id||"default",Y=_G(Z.provider.protocol,void 0),j=zG(Z.provider.client,Y,void 0),V=Object.fromEntries(J.map(({id:H,model:B})=>[H,{...TG(H,B,W.length>0?W:void 0),status:"active"}]));w0.registerProvider({provider:{id:$,name:Z.provider.name.trim()||FG($),protocol:Y,client:j,baseUrl:Z.provider.baseUrl,modelsSourceUrl:Z.provider.modelsSourceUrl,defaultModelId:X,capabilities:DG(Z.provider.capabilities),source:"file"},models:V})}function OG($){let Z=p$($);if(t5.has(Z))return;let Q=gW(Z);for(let[W,J]of Object.entries(Q.providers))T4(W,J);t5.add(Z)}async function qG($){let Z=p$($);if(t5.has(Z))return;let Q=await d2(Z);for(let[W,J]of Object.entries(Q.providers))T4(W,J);t5.add(Z)}import{existsSync as JC,readFileSync as XC}from"node:fs";import{dirname as YC,join as mW}from"node:path";import*as l2 from"@cline/llms";import{resolveClineDataDir as jC}from"@cline/shared/storage";var Q9="openai",EG=l2.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,MG=128000;function NG($){let Z=$?.trim();if(!Z)return;try{let Q=JSON.parse(Z);if(!Q)return;let W=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:W,accountId:Q.userInfo?.id}}catch{return}}function C($){let Z=$?.trim();return Z?Z:void 0}function VC($){return $==="credentials"?"iam":$}function RG($){if(!JC($))return;try{let Z=XC($,"utf8"),Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function HC($){let Z=$.dataDir??jC(),Q=$.globalStatePath??mW(Z,"globalState.json"),W=$.secretsPath??mW(Z,"secrets.json"),J=RG(Q),X=RG(W);if(!J&&!X)return;return{globalState:J??{},secrets:X??{}}}function vW($){if($===Q9)return EG;return $}function BC($,Z,Q,W){let J=Q==="plan"?"planMode":"actMode",X=Z===W?C(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,j={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`}[Z];return(j?C(typeof $[j]==="string"?$[j]:void 0):void 0)??X}function GC($,Z,Q){let W=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...Z==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...Z==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(C).find(Boolean),X=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,Y=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function KC($){let Z=$["openai-codex-oauth-credentials"];if(!Z)return;try{let Q=JSON.parse(Z),W=C(Q.access_token),J=C(Q.refresh_token),X=C(Q.accountId);if(!W&&!J&&!X)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...J?{refreshToken:J}:{},...X?{accountId:X}:{}}}}catch{return}}function FC($){let Z=l2.getGeneratedModelsForProvider($),W=l2.getProviderCollectionSync($)?.provider.defaultModelId;if(W&&Z[W])return W;return Object.keys(Z)[0]??void 0}function AC($,Z,Q,W){let J=vW($),X=C(W==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),Y=BC(Z,$,W,X)??FC(J),j=GC(Z,J,W),V=typeof Z.requestTimeoutMs==="number"&&Number.isInteger(Z.requestTimeoutMs)&&Z.requestTimeoutMs>0?Z.requestTimeoutMs:void 0,H={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},B={};if($==="openai-codex")Object.assign(B,KC(Q));if($==="cline")try{let D=C(Q["cline:clineAccountId"]);if(D)B.auth={...B.auth??{},...NG(D)}}catch{}if($===Q9&&Z.openAiHeaders)B.headers=Z.openAiHeaders;if($==="bedrock"){let D=VC(Z.awsAuthentication),U=D==="profile"||Z.awsUseProfile===!0;B.aws={accessKey:C(Q.awsAccessKey),secretKey:C(Q.awsSecretKey),sessionToken:C(Q.awsSessionToken),region:C(Z.awsRegion),authentication:D,profile:U?C(Z.awsProfile):void 0,usePromptCache:Z.awsBedrockUsePromptCache,useCrossRegionInference:Z.awsUseCrossRegionInference,useGlobalInference:Z.awsUseGlobalInference,endpoint:C(Z.awsBedrockEndpoint),customModelBaseId:C(W==="plan"?Z.planModeAwsBedrockCustomModelBaseId:Z.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")B.gcp={projectId:C(Z.vertexProjectId),region:C(Z.vertexRegion)};if($===Q9&&(Z.azureApiVersion||Z.azureIdentity!==void 0))B.azure={apiVersion:C(Z.azureApiVersion),useIdentity:Z.azureIdentity};if($==="sapaicore"){let D=Z.sapAiCoreUseOrchestrationMode??!0;B.sap={clientId:C(Q.sapAiCoreClientId),clientSecret:C(Q.sapAiCoreClientSecret),tokenUrl:C(Z.sapAiCoreTokenUrl),resourceGroup:C(Z.sapAiResourceGroup),deploymentId:D?void 0:C(W==="plan"?Z.planModeSapAiCoreDeploymentId:Z.actModeSapAiCoreDeploymentId),useOrchestrationMode:D}}if($==="oca"){B.oca={mode:Z.ocaMode};let D=C(Q.ocaRefreshToken);if(D)B.auth={...B.auth??{},refreshToken:D}}if($==="qwen")B.apiLine=Z.qwenApiLine;if($==="moonshot")B.apiLine=Z.moonshotApiLine;if($==="zai")B.apiLine=Z.zaiApiLine;if($==="minimax")B.apiLine=Z.minimaxApiLine;let G={anthropic:Z.anthropicBaseUrl,openai:Z.openAiBaseUrl,ollama:Z.ollamaBaseUrl,lmstudio:Z.lmStudioBaseUrl,litellm:Z.liteLlmBaseUrl,gemini:Z.geminiBaseUrl,requesty:Z.requestyBaseUrl,asksage:Z.asksageApiUrl,dify:Z.difyBaseUrl,oca:Z.ocaBaseUrl,aihubmix:Z.aihubmixBaseUrl,sapaicore:Z.sapAiCoreBaseUrl},K=C(H[$]),F=C(G[$]),A={provider:J,...K?{apiKey:K}:{},...Y?{model:Y}:{},...F?{baseUrl:F}:{},...j?{reasoning:j}:{},...V?{timeout:V}:{},...B},L=z4.safeParse(A);if(!L.success)return;return Object.keys(A).filter((D)=>D!=="provider").length>0?L.data:void 0}function fC($,Z){if($!==EG)return;if(!Z.baseUrl||!Z.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:Z.baseUrl,defaultModelId:Z.model},models:{[Z.model]:{id:Z.model,name:Z.model,contextWindow:MG,maxInputTokens:MG,capabilities:["streaming","tools","images"]}}}}function UC($,Z){let Q=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let X=C(J);if(X)Q.add(X)}if(C(Z.apiKey))Q.add("anthropic");if(C(Z.openRouterApiKey))Q.add("openrouter");if(C(Z.openAiApiKey))Q.add(Q9);if(C(Z.openAiNativeApiKey))Q.add("openai-native");if(C(Z["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(C(Z.geminiApiKey))Q.add("gemini");if(C(Z.ollamaApiKey))Q.add("ollama");if(C(Z.awsAccessKey)||C(Z.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||C($.awsProfile))Q.add("bedrock");if(C($.vertexProjectId)||C($.vertexRegion))Q.add("vertex");if(C(Z.clineApiKey))Q.add("cline");let W=NG(C(Z["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)Q.add("cline");if(C(Z.ocaApiKey))Q.add("oca");if(C(Z.sapAiCoreClientId)||C(Z.sapAiCoreClientSecret)||C($.sapAiCoreTokenUrl)||C($.sapAiCoreBaseUrl)||C($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function cW($){let Z=$.providerSettingsManager.read(),Q=HC($);if(!Q)return{migrated:!1,providerCount:Object.keys(Z.providers).length,lastUsedProvider:Z.lastUsedProvider};let{globalState:W,secrets:J}=Q,X=W.mode==="plan"?"plan":"act",Y=UC(W,J),j=u2();j.providers={...Z.providers},j.lastUsedProvider=Z.lastUsedProvider;let V=new Date().toISOString(),H=0,B=mW(YC($.providerSettingsManager.getFilePath()),"models.json"),G=gW(B),K=0;for(let L of Y){let f=vW(L);if(j.providers[f])continue;let D=AC(L,W,J,X);if(!D)continue;j.providers[f]={settings:D,updatedAt:V,tokenSource:"migration"},H+=1;let U=fC(f,D);if(U&&!G.providers[f])G.providers[f]=U,K+=1}if(H===0&&K===0)return{migrated:!1,providerCount:Object.keys(Z.providers).length,lastUsedProvider:Z.lastUsedProvider};let F=C(X==="plan"?W.planModeApiProvider:W.actModeApiProvider),A=F?vW(F):void 0;if(j.lastUsedProvider=Z.lastUsedProvider??(A&&j.providers[A]?A:Object.keys(j.providers)[0]),$.providerSettingsManager.write(j),K>0)fG(B,G);return{migrated:H>0||K>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}function TC(){return new Date().toISOString()}var OC="cline",qC="cline-pass";function MC($){if(CG($)!=="providers.json")return;let Z=dW($);if(CG(Z)!=="settings")return;return dW(Z)}class Y${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??zC(),this.dataDir=$.dataDir??MC(this.filePath),this.dataDir||!$.filePath)cW({providerSettingsManager:this,dataDir:this.dataDir});if(OG(this),Z9(this.read()),uW(this.filePath))try{wG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!uW(this.filePath))return u2();try{let $=LC(this.filePath,"utf8"),Z=JSON.parse($),Q=s5.safeParse(Z);if(Q.success)return Z9(Q.data),Q.data}catch{}return u2()}write($){let Z=s5.parse($),Q=dW(this.filePath);if(!uW(Q))DC(Q,{recursive:!0,mode:448});_C(this.filePath,`${JSON.stringify(Z,null,2)}
580
- `,"utf8");try{wG(this.filePath,384)}catch{}Z9(Z)}saveProviderSettings($,Z={}){let Q=z4.parse($),W=this.read(),J=Q.provider,X=Z.setLastUsed!==!1,Y=W.providers[J],j=Z.tokenSource??Y?.tokenSource??"manual",V={...W,providers:{...W.providers,[J]:{settings:Q,updatedAt:TC(),tokenSource:j}},lastUsedProvider:X?J:W.lastUsedProvider};return this.write(V),V}resolveProviderSettings($,Z){let Q=$.providers[Z]?.settings,J=B0(Z)?.storageProviderId;if(!J||J===Z)return Q;let X=$.providers[J]?.settings;if(!X)return Q;return z4.parse({...X.auth?{auth:X.auth}:{},...X.apiKey?{apiKey:X.apiKey}:{},...X.baseUrl?{baseUrl:X.baseUrl}:{},...Q??{},provider:Z})}getProviderSettings($){let Z=this.read();return this.resolveProviderSettings(Z,$)}resolveLastUsedProviderId($,Z){let Q=$.lastUsedProvider;if(Q===qC&&Z.isClinePassEnabled===!1)return OC;return Q}getLastUsedProviderSettings($={}){let Z=this.read(),Q=this.resolveLastUsedProviderId(Z,$);if(!Q)return;return this.resolveProviderSettings(Z,Q)}getProviderConfig($,Z){let Q=this.getProviderSettings($);if(!Q)return;return B1(Q,Z)}getLastUsedProviderConfig($={}){let Z=this.getLastUsedProviderSettings($);if(!Z)return;return B1(Z,$)}async refreshCatalog(){try{await J6({})}catch{}}}G0();g2();import{execFile as RC}from"node:child_process";import{promisify as EC}from"node:util";var p2=EC(RC);function O4($){let Z=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(Z?.history)?Z.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let J=String(W.ref??"").trim(),X=Number(W.createdAt??0),Y=Number(W.runCount??0);if(J.length===0||!Number.isFinite(X)||!Number.isInteger(Y)||Y<1)return[];let j=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:J,createdAt:X,runCount:Y,...j?{kind:j}:{}}]})}function PG($,Z){let Q=O4($).filter((J)=>J.runCount<=Z),W=Q.at(-1);return W?{latest:W,history:Q}:void 0}function W9($,Z){return $.reduce((Q,W)=>{if(W.runCount>Z)return Q;if(!Q||W.runCount>Q.runCount)return W;return Q},void 0)}function SG($,Z){let Q=0;for(let W=0;W<$.length;W+=1){let J=$[W];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===Z)return W}throw Error(`Could not find user message for checkpoint run ${Z}`)}function NC($,Z){let Q=SG($,Z);return $.slice(0,Q+1)}function bG($,Z){let Q=SG($,Z);return $.slice(0,Q)}function yG($){let Z=$.checkpointRunCount;if(!Number.isInteger(Z)||Z<1)throw Error("checkpointRunCount must be a positive integer");let Q=W9(O4($.session),Z);if(!Q)throw Error(`No checkpoint found at or before run ${Z} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:W,...$.restoreMessages!==!1?{messages:NC($.messages??[],Z)}:{}}}async function hG($,Z){if((await p2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await p2("git",["-C",$,"cat-file","-e",`${Z.ref}^{commit}`],{windowsHide:!0}),await p2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await p2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),Z.kind==="commit"){await p2("git",["-C",$,"reset","--hard",Z.ref],{windowsHide:!0});return}await p2("git",["-C",$,"stash","apply",Z.ref],{windowsHide:!0})}class s0 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="SessionVersioningError"}}function wC($){let Z=$.sessionId.trim();if(!Z)throw new s0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new s0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new s0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new s0("invalid_restore","checkpointRunCount must be a positive integer");return Z}class r2{async restoreCheckpoint($){let Z=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,W=wC({sessionId:$.sessionId,restoreMessages:Z,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(W);if(!J)throw new s0("session_not_found",`Session ${W} not found`);let X=Z?await $.readMessages(W):void 0;if(Z&&X?.length===0)throw new s0("session_messages_not_found",`No messages found for session ${W}`);let Y=yG({session:J,messages:X,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:Z});if(Q)await($.applyWorkspaceCheckpoint??hG)(Y.cwd,Y.checkpoint);let j=t1({session:J,messages:X});if(!Z)return{checkpoint:Y.checkpoint,sourceSnapshot:j};let V=PG(J,$.checkpointRunCount),H=$.restore?.omitCheckpointMessageFromSession?bG(X??[],$.checkpointRunCount):Y.messages??[],B={sourceSession:J,sourceMessages:X,sourceSnapshot:j,plan:Y,restoredCheckpointMetadata:V,initialMessages:H,restoreMessages:Z,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new s0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(B,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??$B)(Y.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:Y.messages,checkpoint:Y.checkpoint,sourceSnapshot:j,...A?{restoredSnapshot:t1({session:A,messages:H})}:{}}}}import{hasRuntimeConfigExtension as uC}from"@cline/shared";import{nanoid as dC}from"nanoid";r0();import{appendFileSync as CC,existsSync as i2,mkdirSync as kG,readdirSync as PC,readFileSync as IG,renameSync as SC,writeFileSync as bC}from"node:fs";import{join as lW}from"node:path";import{resolveTeamDataDir as yC}from"@cline/shared/storage";function xG(){return new Date().toISOString()}function pW($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function gG($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class J9{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??yC()}init(){this.ensureTeamDir()}listTeamNames(){if(!i2(this.teamDirPath))return[];return PC(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>i2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let Z=this.readEnvelope($);return Z?.teamState?gG(Z.teamState):void 0}readHistory($,Z=200){let Q=this.historyPath($);if(!i2(Q))return[];return IG(Q,"utf8").split(`
581
- `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,Z)}loadRuntime($){let Z=this.readEnvelope($);return{state:Z?.teamState?gG(Z.teamState):void 0,teammates:Z?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,Z){this.ensureTeamSubdir($),CC(this.historyPath($),`${JSON.stringify({ts:xG(),eventType:Z.type,payload:Z})}
582
- `,"utf8")}persistRuntime($,Z,Q){this.ensureTeamSubdir($);let W={version:1,updatedAt:xG(),teamState:Z,teammates:Q},J=this.statePath($),X=`${J}.tmp`;bC(X,`${JSON.stringify(W,null,2)}
583
- `,"utf8"),SC(X,J)}markInProgressRunsInterrupted($,Z){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let W=Q.teamState.runs.filter((X)=>X.status==="queued"||X.status==="running").map((X)=>X.id);if(W.length===0)return[];let J=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((X)=>X.status==="queued"||X.status==="running"?{...X,status:"interrupted",error:Z,endedAt:J}:X)},this.persistRuntime($,Q.teamState,Q.teammates),W}ensureTeamDir(){if(!i2(this.teamDirPath))kG(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let Z=lW(this.ensureTeamDir(),pW($));if(!i2(Z))kG(Z,{recursive:!0});return Z}statePath($){return lW(this.ensureTeamDir(),pW($),"state.json")}historyPath($){return lW(this.ensureTeamDir(),pW($),"task-history.jsonl")}readEnvelope($){let Z=this.statePath($);if(!i2(Z))return;try{let Q=JSON.parse(IG(Z,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as hC,mkdirSync as kC}from"node:fs";import{join as IC}from"node:path";import{safeJsonParse as mG}from"@cline/shared";import{loadSqliteDb as xC,nowIso as rW}from"@cline/shared/db";import{resolveDbDataDir as gC}from"@cline/shared/storage";function mC(){return gC()}function n2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function vC($){let Z=mG($);if(!Array.isArray(Z))return[];let Q=[];for(let W of Z){if(!W||typeof W!=="object")continue;let J=W,X=J.agentId,Y=J.rolePrompt;if(typeof X!=="string"||!X.trim())continue;if(typeof Y!=="string"||!Y.trim())continue;let j={agentId:X.trim(),rolePrompt:Y};if(typeof J.modelId==="string"&&J.modelId.trim())j.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))j.maxIterations=Math.max(1,Math.floor(J.maxIterations));Q.push(j)}return Q}function cC($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class q4{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??mC()}init(){this.getRawDb()}ensureTeamDir(){if(!hC(this.teamDirPath))kC(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return IC(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=xC(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
573
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function hN($){let Z=await yN($.providerConfig),Q="";for await(let W of Z.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){Q+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function kN($){try{return JSON.stringify($).length}catch{return String($).length}}async function cB($){let Z=$.context.messages;if(Z.length<2)return;let Q=kB(Z,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=Z.length)return;let W=Z.slice(0,Q),J=hB(W),X=J>=0?RW(W[J])?.summary:void 0,Y=J>=0?W.slice(J+1):W;if(Y.length===0)return;let j=IB(W),V=PB(Y),H=gB({previousSummary:X,conversationText:V,fileOps:j});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:Y.length,preservedMessages:Z.length-Q,previousSummaryChars:X?.length??0,conversationTextChars:V.length,summaryRequestChars:H.length,summaryRequestEstimatedTokens:OW(H.length),newMessagesJsonChars:kN(Y),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let B=await hN({providerConfig:mB({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:H,logger:$.logger});if(!B.trim())return;let G=xB(B,j),K=Z.reduce((L,f)=>L+$.estimateMessageTokens(f),0),F=[vB({summary:G,fileOps:j,tokensBefore:K}),...Z.slice(Q)],A=F.reduce((L,f)=>L+$.estimateMessageTokens(f),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:Z.length,messagesAfter:F.length,messagesSummarized:Q,messagesPreserved:Z.length-Q,tokensBefore:K,tokensAfter:A,maxInputTokens:$.context.maxInputTokens}),{messages:F}}import{CHARS_PER_TOKEN as IN}from"@cline/shared";function xN($){if(U4($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let Z=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(Z.length===0)return;return{...$,content:Z.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:MW(Q.content)}:Q)}}function gN($,Z){return $.reduce((Q,W)=>Q+Z(W),0)}function uB($,Z){if($.length<=Z)return $;let Q=`
574
+ ...`,W=Math.max(1,Z-Q.length);return`${$.slice(0,W)}${Q}`}function dB($,Z){let Q=Number.isFinite(Z)?Math.max(1,Z):1,W=Math.max(16,Q*IN);if(typeof $.content==="string"){let Y=uB($.content,W).trim();return{...$,content:Y||"..."}}let J=W,X=$.content.map((Y)=>{if(Y.type!=="text"||J<=0)return Y;let j=uB(Y.text,J).trim();return J-=j.length,{...Y,text:j||"..."}});return{...$,content:X}}function mN($,Z){let Q=bB($),W=c5($),J=yB($),X=[],Y=0;for(let j=0;j<$.length;j+=1){let V=xN($[j]);if(!V)continue;let H=Z(V);Y+=H,X.push({index:j,message:V,estimatedTokens:H,toolPairIds:pB(V),isFirstUser:j===Q,isLastUser:j===W,isLastAssistant:j===J})}return{candidates:X,totalTokens:Y}}function lB($,Z,Q,W){let J=$[Z],X=J.estimatedTokens;return J.message=Q,J.estimatedTokens=W(Q),J.toolPairIds=pB(Q),J.estimatedTokens-X}function pB($){if(!Array.isArray($.content))return[];let Z=[];for(let Q of $.content)if(Q.type==="tool_use")Z.push(Q.id);else if(Q.type==="tool_result")Z.push(Q.tool_use_id);return Z}function vN($){let Z=new Map;for(let Q of $)for(let W of Q.toolPairIds){let J=Z.get(W);if(J)J.add(Q);else Z.set(W,new Set([Q]))}return Z}function cN($,Z,Q){let W=new Set,J=[Q],X=0;while(X<J.length){let Y=J[X];if(X+=1,Y===void 0||!$.has(Y)||W.has(Y))continue;W.add(Y);for(let j of Y.toolPairIds)for(let V of Z.get(j)??[])if(!W.has(V))J.push(V)}return W}function uN($,Z){let Q=0;for(let W of $){if(Z.has(W))continue;$[Q]=W,Q+=1}$.length=Q}function u5($,Z,Q,W){let J=new Set($),X=vN($);for(let Y=0;Y<$.length&&W>Q;){if(!Z($[Y])){Y+=1;continue}let j=cN(J,X,$[Y]);if(j.size===0){Y+=1;continue}let V=0;for(let H of j)V+=H.estimatedTokens,J.delete(H);W-=V,uN($,j)}return W}function dN($,Z,Q,W,J){if(Q<=Z)return Q;for(let Y=$.length-1;Y>=0&&Q>Z;Y-=1){let j=$[Y];if(j.isFirstUser)continue;let V=Math.max(wB,j.estimatedTokens-(Q-Z));if(V>=j.estimatedTokens)continue;Q+=lB($,Y,dB(j.message,V),J)}if(Q<=Z)return Q;let X=$.findIndex((Y)=>Y.isFirstUser);if(X>=0){if($[X].estimatedTokens<=W)return Q;while(Q>Z){let j=$[X],V=Math.max(1,j.estimatedTokens-(Q-Z));if(V>=j.estimatedTokens)break;let H=j.estimatedTokens;if(Q+=lB($,X,dB(j.message,V),J),j.estimatedTokens>=H)break}}return Q}function lN($,Z){return JSON.stringify($)!==JSON.stringify(Z)}function pN($){let Z=c5($);if(Z<0||Z===0&&!D4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,Z),protectedTail:$.slice(Z)}}function rB($){let Z=Math.max(1,Math.min($.context.targetTokens??Math.floor($.context.triggerTokens*v5),$.context.maxInputTokens)),{compactable:Q,protectedTail:W}=pN($.context.messages);if(Q.length===0)return;let J=gN(W,$.estimateMessageTokens),X=Math.max(1,Z-J),Y=mN(Q,$.estimateMessageTokens),{candidates:j}=Y;if(j.length===0)return;let V=Y.totalTokens,H=V;H=u5(j,(F)=>F.message.role==="assistant"&&!F.isLastAssistant,X,H),H=u5(j,(F)=>F.message.role==="user"&&!F.isFirstUser&&!F.isLastUser,X,H),H=u5(j,(F)=>F.message.role==="assistant"&&F.isLastAssistant,X,H),H=u5(j,(F)=>F.message.role==="user"&&F.isLastUser&&!F.isFirstUser,X,H),H=dN(j,X,H,$.context.triggerTokens,$.estimateMessageTokens);let B=[...j.map((F)=>F.message),...W];if(!lN($.context.messages,B))return;let G=V+J,K=H+J;return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:B.length,messagesRemoved:$.context.messages.length-B.length,tokensBefore:G,tokensAfter:K,targetTokens:Z,maxInputTokens:$.context.maxInputTokens}),{messages:B}}var rN=0.5,iN=0.5;function iB($){try{return JSON.stringify($).length}catch{return String($).length}}function L4($){return typeof $==="number"&&Number.isFinite($)&&$>0}function nN($){let Z=[];if(L4($.configMaxInputTokens))Z.push($.configMaxInputTokens);if(L4($.modelMaxInputTokens))Z.push($.modelMaxInputTokens);if(L4($.contextWindow)){Z.push($.contextWindow);let Q=L4($.modelMaxTokens)?$.contextWindow-$.modelMaxTokens:void 0;if(L4(Q)&&Q>=$.contextWindow*rN)Z.push(Q)}return Z.length>0?Math.min(...Z):MB}function aN($){let Z=0,Q=0,W=0;for(let J of $){if(!Array.isArray(J.content))continue;for(let X of J.content){if(X.type!=="tool_result")continue;let Y=iB(X.content);Z+=1,Q+=Y,W=Math.max(W,Y)}}return{toolResultCount:Z,toolResultSerializedChars:Q,maxToolResultSerializedChars:W}}var sN={basic:({context:$,estimateMessageTokens:Z,logger:Q})=>rB({context:$,estimateMessageTokens:Z,logger:Q}),agentic:({context:$,providerConfig:Z,compaction:Q,mode:W,estimateMessageTokens:J,logger:X})=>cB({context:$,providerConfig:Z,summarizer:Q?.summarizer,preserveRecentTokens:W==="manual"?Math.min(Q?.preserveRecentTokens??qW,$.triggerTokens):Q?.preserveRecentTokens??qW,estimateMessageTokens:J,logger:X})};function oN($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio==="number"){let Q=$.config.thresholdRatio,W=$.maxInputTokens*Q;return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:Q}}let Z=Math.max(0,Math.min($.maxInputTokens-EB,$.maxInputTokens*RB));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function tN($){let Z=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,Z)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function eN($){let Z=$.messagePairCount>=5&&typeof $.modelMaxTokens==="number"&&Number.isFinite($.modelMaxTokens)&&$.modelMaxTokens<$.maxInputTokens?Math.floor($.maxInputTokens*iN):Math.floor($.triggerTokens*v5),Q=Math.max(1,$.triggerTokens-1);return Math.max(1,Math.min(Z,$.maxInputTokens,Q))}function $w($){let Z=0,Q=!1;for(let W of $)if(W.role==="user")Q=!0;else if(W.role==="assistant"&&Q)Z+=1,Q=!1;return Z}function EW($,Z={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},J=SB(),X=Q?.strategy??"basic",Y=sN[X],j=Z.mode??"auto",V=Q?.compact?"custom":X;return async(H)=>{let B=H.apiMessages.reduce((M,E)=>M+J(E),0),G=nN({configMaxInputTokens:Q?.maxInputTokens,modelMaxInputTokens:H.model.info?.maxInputTokens,contextWindow:H.model.info?.contextWindow,modelMaxTokens:H.model.info?.maxTokens}),K=oN({inputTokens:B,maxInputTokens:G,config:{maxInputTokens:Q?.maxInputTokens,reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:j,strategy:X,iteration:H.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:B,maxInputTokens:G,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,shouldCompact:K.shouldCompact,messageCount:H.messages.length,apiMessageCount:H.apiMessages.length,apiMessagesJsonChars:iB(H.apiMessages),...aN(H.apiMessages)}),j==="auto"&&!K.shouldCompact)return;let F=j==="manual"?tN({inputTokens:B,maxInputTokens:G,autoTriggerTokens:K.triggerTokens,manualTargetRatio:Z.manualTargetRatio}):K,A=j==="auto"?eN({maxInputTokens:G,modelMaxTokens:H.model.info?.maxTokens,triggerTokens:F.triggerTokens,messagePairCount:$w(H.messages)}):void 0,L={agentId:H.agentId,conversationId:H.conversationId,parentAgentId:H.parentAgentId,iteration:H.iteration,messages:H.messages,model:H.model,maxInputTokens:G,triggerTokens:F.triggerTokens,targetTokens:A,thresholdRatio:F.thresholdRatio,utilizationRatio:G>0?B/G:0},f=j==="manual"?"manual_compaction":"auto_compaction";H.emitStatusNotice?.(j==="manual"?"compacting":"auto-compacting",{kind:f,reason:f,iteration:H.iteration,triggerTokens:F.triggerTokens,maxInputTokens:G});let D=H.messages.length,U=Date.now(),T=Q?.compact?await Q.compact(L):await Y({context:L,providerConfig:{...W,abortSignal:H.abortSignal},compaction:Q,mode:j,estimateMessageTokens:J,logger:$.logger}),q=Date.now()-U,z=$.sessionId??H.conversationId,_={agentId:H.agentId,conversationId:H.conversationId,parentAgentId:H.parentAgentId??void 0};if(T?.messages){let M=T.messages.reduce((E,P)=>E+J(P),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:X,maxInputTokens:G,inputTokens:B,afterTokens:M,tokensSaved:B-M,utilizationBefore:`${(B/G*100).toFixed(1)}%`,utilizationAfter:`${(M/G*100).toFixed(1)}%`,thresholdTrigger:`${(F.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:T.messages.length,messagesRemoved:D-T.messages.length}),BZ($.telemetry,{ulid:z,strategy:V,mode:j,messagesBefore:D,messagesAfter:T.messages.length,messagesRemoved:D-T.messages.length,tokensBefore:B,tokensAfter:M,tokensSaved:B-M,triggerTokens:F.triggerTokens,maxInputTokens:G,thresholdRatio:F.thresholdRatio,durationMs:q,provider:$.providerId,modelId:$.modelId,..._})}else GZ($.telemetry,{ulid:z,strategy:V,mode:j,reason:"no_result",tokensBefore:B,triggerTokens:F.triggerTokens,maxInputTokens:G,thresholdRatio:F.thresholdRatio,durationMs:q,provider:$.providerId,modelId:$.modelId,..._});return T}}G0();function _0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function f0($,Z){return{inputTokens:$.inputTokens+Math.max(0,Z.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,Z.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,Z.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,Z.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,Z.totalCost??0)}}function d5($){let Z=_0();for(let Q of $)Z=f0(Z,Q);return Z}function v2($){return typeof $==="number"&&Number.isFinite($)?$:0}function l5($){let Z=_0();for(let Q of $){let W=Q.metrics;if(!W)continue;Z=f0(Z,{inputTokens:v2(W.inputTokens),outputTokens:v2(W.outputTokens),cacheReadTokens:v2(W.cacheReadTokens),cacheWriteTokens:v2(W.cacheWriteTokens),totalCost:v2(W.cost)})}return Z}function Zw($){for(let Z=$.length-1;Z>=0;Z-=1){let Q=$[Z];if(Q?.role!=="assistant")continue;let W=v2(Q.metrics?.inputTokens);return W>0?W:void 0}return}function Qw($){if(!$||typeof $!=="object")return;let Z=$,Q=Z.skill??Z.skill_name??Z.skillName;if(typeof Q!=="string")return;let W=Q.trim();return W.length>0?W:void 0}function NW($){if(!$||typeof $!=="object")return{};let Z=$;return{agentId:typeof Z.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z.parentAgentId==="string"?Z.parentAgentId:void 0}}function q1($){let Z=$.agentId?.trim();if(!Z)return;let Q=$.parentAgentId?.trim()||void 0,W=$.teamRole,J="root";if(W==="teammate")J="team_teammate";else if(W==="lead")J="team_lead";else if(Q)J="subagent";return{agentId:Z,agentKind:J,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function Ww($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function Jw($){let Z=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of Z){let W=Q?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function wW($,Z,Q){let{sessionId:W,config:J,liveSession:X,emit:Y}=$,j=J.telemetry,V=X?.runtime.teamRuntime,H=Q?.isPrimaryAgentEvent??!0,B=NW(Z),G=q1({agentId:Q?.agentId??B.agentId,conversationId:Q?.conversationId??B.conversationId,parentAgentId:Q?.parentAgentId??B.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??V?.getTeamId(),teamName:Q?.teamName??V?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(Z.type==="content_start"&&Z.contentType==="tool"&&Z.toolName==="skills"){let K=Qw(Z.input);if(K)WZ(j,{ulid:W,skillName:K,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:J.providerId,modelId:J.modelId,...G})}if(Z.type==="content_end"&&Z.contentType==="tool"){let K=Z.toolName??"unknown",F=!Z.error;if(Q8(j,{ulid:W,tool:K,autoApproved:void 0,success:F,modelId:J.modelId,provider:J.providerId,...G}),!F&&(K==="editor"||K==="apply_patch"))JZ(j,{ulid:W,modelId:J.modelId,provider:J.providerId,errorType:Z.error,...G})}if(Z.type==="notice"&&Z.reason==="api_error")u4(j,{ulid:W,model:J.modelId,provider:J.providerId,errorMessage:Z.message,...G});if(Z.type==="error")u4(j,{ulid:W,model:J.modelId,provider:J.providerId,errorMessage:Z.error?.message??"unknown error",...G});if(Z.type==="usage"&&X?.turnUsageBaseline){let K=Ww(Z);if(H){X.turnPrimaryUsage=f0(X.turnPrimaryUsage??_0(),K);let A=f0(X.turnUsageBaseline,X.turnPrimaryUsage);$.usageBySession.set(W,A),Z8(j,{ulid:W,provider:J.providerId,model:J.modelId,source:"assistant",mode:J.mode,...G}),ZZ(j,{ulid:W,tokensIn:Z.inputTokens,tokensOut:Z.outputTokens,cacheWriteTokens:Z.cacheWriteTokens,cacheReadTokens:Z.cacheReadTokens,totalCost:Z.cost,model:J.modelId,...G})}else{let A=Jw({isPrimaryAgentEvent:H,overrides:Q,eventMetadata:B}),L=X.turnUsageByAgent??new Map;X.turnUsageByAgent=L,L.set(A,f0(L.get(A)??_0(),K))}let F=f0(X.turnPrimaryUsage??_0(),d5(X.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,f0(X.turnAggregateUsageBaseline??X.turnUsageBaseline,F))}if(Z.type==="iteration_end"&&H)$.persistMessages(W,X?.agent.getMessages()??[],X?.config.systemPrompt);Y({type:"agent_event",payload:{sessionId:W,event:Z,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(H?"lead":void 0):void 0}}),Y({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:WH(Z),ts:Date.now()}})}function W$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as bw}from"@cline/shared";import{spawn as Fw}from"node:child_process";import{appendFileSync as Aw,readFileSync as fw}from"node:fs";import{join as Uw}from"node:path";import{augmentNodeCommandForDebug as oB,withResolvedClineBuildEnv as hW}from"@cline/shared";import{ensureHookLogDir as aB}from"@cline/shared/storage";function p5($,Z){if(!Z)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:Z}}import{existsSync as Xw,readdirSync as Yw}from"node:fs";import{basename as jw,extname as Vw,join as Hw}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as nB,resolveHooksConfigSearchPaths as Bw}from"@cline/shared/storage";function CW($){return Bw($)}var r5;((B)=>{B.TaskStart="TaskStart";B.TaskResume="TaskResume";B.TaskCancel="TaskCancel";B.TaskComplete="TaskComplete";B.TaskError="TaskError";B.PreToolUse="PreToolUse";B.PostToolUse="PostToolUse";B.UserPromptSubmit="UserPromptSubmit";B.PreCompact="PreCompact";B.SessionShutdown="SessionShutdown"})(r5||={});var PW={["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"},Gw=new Map(Object.values(r5).map(($)=>[$.toLowerCase(),$])),Kw=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function SW($){let Z=Vw($).toLowerCase();if(!Kw.has(Z))return;let Q=jw($,Z).trim().toLowerCase();return Gw.get(Q)}function c2($){let Z=[],Q=new Set,W=CW($).filter((J)=>Xw(J));for(let J of W)try{for(let X of Yw(J,{withFileTypes:!0})){if(!X.isFile())continue;let Y=SW(X.name);if(!Y)continue;let j=Hw(J,X.name);if(Q.has(j))continue;Q.add(j),Z.push({fileName:Y,hookEventName:PW[Y],path:j})}}catch{}return Z.sort((J,X)=>J.path.localeCompare(X.path))}function n5($){if(!$||typeof $!=="object")return{};let Z={};for(let[Q,W]of Object.entries($))Z[Q]=typeof W==="string"?W:JSON.stringify(W);return Z}function i5($,Z,Q){let W=Q instanceof Error?`: ${Q.message}`:"",J=`${Z}${W}`;if($){try{$.log(J,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(J)}function Dw($,Z){if(!Z)return $;if(!$)return{...Z};let Q=[$.context,Z.context].filter((J)=>typeof J==="string"&&J.length>0).join(`
575
+ `),W=[...$.appendMessages??[],...Z.appendMessages??[]];return{cancel:$.cancel===!0||Z.cancel===!0?!0:void 0,review:$.review===!0||Z.review===!0?!0:void 0,context:Q||void 0,overrideInput:Z.overrideInput!==void 0?Z.overrideInput:$.overrideInput,systemPrompt:Z.systemPrompt!==void 0?Z.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function Lw($){if(!$||typeof $!=="object")return;let Z=$,Q=typeof Z.context==="string"?Z.context:typeof Z.contextModification==="string"?Z.contextModification:typeof Z.errorMessage==="string"?Z.errorMessage:void 0;return{cancel:typeof Z.cancel==="boolean"?Z.cancel:void 0,review:typeof Z.review==="boolean"?Z.review:void 0,context:Q,overrideInput:Object.hasOwn(Z,"overrideInput")?Z.overrideInput:void 0}}function bW($){let Z=String($??"").toLowerCase();return Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt")}function U0($,Z){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:Z.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:Z.workspacePath?[Z.workspacePath]:[],workspaceInfo:Z.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function _w($){let Z=$.trim();if(!Z)return{};let W=Z.split(`
576
+ `).map((X)=>X.trim()).filter(Boolean).filter((X)=>X.startsWith("HOOK_CONTROL\t")).map((X)=>X.slice(13)),J=W.length>0?W[W.length-1]:Z;try{return{parsedJson:JSON.parse(J)}}catch(X){return{parseError:X instanceof Error?X.message:"Failed to parse hook stdout JSON"}}}async function zw($,Z){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((W,J)=>{let X=!1,Y=()=>{Q.off("error",V),Q.off("finish",H),$.off("close",B)},j=(G)=>{if(X)return;if(X=!0,Y(),G){let K=G.code;if(K==="EPIPE"||K==="ERR_STREAM_DESTROYED"){W();return}J(G);return}W()},V=(G)=>j(G),H=()=>j(),B=()=>j();Q.on("error",V),Q.once("finish",H),$.once("close",B);try{Q.end(Z)}catch(G){j(G)}})}async function tB($,Z){if(Z.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await sB($,Z)}catch(Q){let W=qw(Z.command,process.platform,Q);if(!W)throw Q;return await sB($,{...Z,command:W})}}async function sB($,Z){let Q=oB(Z.command,{env:Z.env,debugRole:"hook"}),W=Fw(Q[0],Q.slice(1),{cwd:Z.cwd,env:hW(Z.env),stdio:Z.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z.detached,windowsHide:!0}),J=new Promise((K)=>{W.once("spawn",()=>K())}),X=new Promise((K,F)=>{W.once("error",(A)=>F(A))}),Y=JSON.stringify($);if(await Promise.race([J,X]),await zw(W,Y),Z.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let j="",V="",H=!1,B;W.stdout.on("data",(K)=>{j+=K.toString()}),W.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((Z.timeoutMs??0)>0)B=setTimeout(()=>{H=!0,W.kill("SIGKILL")},Z.timeoutMs);W.once("close",(F)=>{if(B)clearTimeout(B);let{parsedJson:A,parseError:L}=_w(j);K({exitCode:F,stdout:j,stderr:V,parsedJson:A,parseError:L,timedOut:H})})});return await Promise.race([G,X])}function Tw($){try{let Q=fw($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let W=Q.slice(2).trim();if(!W)return;let J=W.split(/\s+/).filter(Boolean);return J.length>0?J:void 0}catch{return}}function Ow($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function qw($,Z=process.platform,Q){if(Z!=="win32"||!Ow(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function eB($){if($.length===0)return;let[Z,...Q]=$,W=Z.replace(/\\/g,"/").toLowerCase(),J=W.split("/").at(-1)??W;if(J==="env")return eB(Q);if(J==="bash"||J==="sh"||J==="zsh")return[J,...Q];if(J==="python3"||J==="python")return process.platform==="win32"?["py","-3",...Q]:[J,...Q];return $}function Mw($){let Z=Tw($);if(Z&&Z.length>0)return[...eB(Z)??Z,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return oB(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function Rw($){let Z={};for(let Q of c2($)){if(!Q.hookEventName)continue;let W=Q.hookEventName,J=Z[W]??[];J.push(Mw(Q.path)),Z[W]=J}return Z}async function Ew($){let Z;for(let Q of $.commands){let W=Q.join(" ");try{let J=await tB($.payload,{command:Q,cwd:$.cwd,env:hW(process.env),detached:!1,timeoutMs:$.timeoutMs});if(J?.timedOut){i5($.logger,`hook command timed out: ${W}`);continue}if(J?.parseError){i5($.logger,`hook command returned invalid JSON control output: ${W} (${J.parseError})`);continue}Z=Dw(Z,Lw(J?.parsedJson))}catch(J){i5($.logger,`hook command failed: ${W}`,J)}}return Z}function l$($){for(let Z of $.commands){let Q=Z.join(" ");tB($.payload,{command:Z,cwd:$.cwd,env:hW(process.env),detached:!0}).catch((W)=>{i5($.logger,`hook command failed: ${Q}`,W)})}}function J$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function yW($,Z){return{...J$($.snapshot),userMessage:Z}}function $G($){return{...J$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function ZG($){return{...J$($.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 QG($){return $.filter((Z)=>Z.type==="text"&&typeof Z.text==="string").map((Z)=>Z.text).join("")}function Nw($){if(!$)return;let Z={};if($.cancel===!0)Z.stop=!0;if($.overrideInput!==void 0)Z.input=$.overrideInput;return Object.keys(Z).length>0?Z:void 0}function a5($){let Z={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(W)=>{let J=`${JSON.stringify({ts:new Date().toISOString(),...W})}
577
+ `,Y=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??Uw(aB(),"hooks.jsonl");aB(Y),Aw(Y,J,"utf8")};return{beforeRun:async(W)=>{let J=yW(W,"");Q({...U0(J,Z),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let J=$G(W);Q({...U0(J,Z),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:n5(J.call.input)}});return},afterTool:async(W)=>{let J=ZG(W);Q({...U0(J,Z),hookName:"tool_result",iteration:J.iteration,tool_result:J.record,postToolUse:{toolName:J.record.name,parameters:n5(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:W,result:J})=>{let X=J$(W);if(J.status==="completed"){Q({...U0(X,Z),hookName:"agent_end",iteration:J.iterations,turn:{outputText:J.outputText,status:J.status},taskComplete:{taskMetadata:{}}});return}if(J.status==="aborted"||bW(J.error?.message)){Q({...U0(X,Z),hookName:"agent_abort",reason:J.error?.message,taskCancel:{taskMetadata:{}}});return}if(J.error)Q({...U0(X,Z),hookName:"agent_error",iteration:J.iterations,error:{name:J.error.name,message:J.error.message,stack:J.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let J=yW({snapshot:W.snapshot},QG(W.message.content));Q({...U0(J,Z),hookName:"prompt_submit",userPromptSubmit:{prompt:J.userMessage,attachments:[]}})}}}function kW($){let Z=Rw($.workspacePath);if(!Object.values(Z).some((G)=>G.length>0))return;let W=async(G,K)=>{let F=Z[K]??[];if(F.length===0)return;l$({commands:F,cwd:$.cwd,logger:$.logger,payload:K==="agent_resume"?{...U0(G,$),hookName:K,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(G,$),hookName:K,taskStart:{taskMetadata:{}}}})},J=async(G)=>{let K=Z.prompt_submit??[];if(K.length>0)l$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"prompt_submit",userPromptSubmit:{prompt:G.userMessage,attachments:[]}}})},X=async(G)=>{let K=Z.tool_call??[];if(K.length===0)return;return Ew({commands:K,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(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:n5(G.call.input)}}})},Y=async(G)=>{let K=Z.tool_result??[];if(K.length===0)return;l$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"tool_result",iteration:G.iteration,tool_result:G.record,postToolUse:{toolName:G.record.name,parameters:n5(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}}})},j=async(G)=>{let K=Z.agent_end??[];if(K.length===0)return;l$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_end",iteration:G.iteration,turn:G.turn,taskComplete:{taskMetadata:{}}}})},V=async(G)=>{let K=Z.agent_error??[];if(K.length===0)return;l$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_error",iteration:G.iteration,error:{name:G.error.name,message:G.error.message,stack:G.error.stack}}})},H=async(G)=>{if(bW(G.reason)){let F=Z.agent_abort??[];if(F.length>0)l$({commands:F,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"agent_abort",reason:G.reason,taskCancel:{taskMetadata:{}}}})}let K=Z.session_shutdown??[];if(K.length===0)return;l$({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(G,$),hookName:"session_shutdown",reason:G.reason}})},B={};if((Z.agent_start?.length??0)>0||(Z.agent_resume?.length??0)>0||(Z.prompt_submit?.length??0)>0){if((Z.agent_start?.length??0)>0||(Z.agent_resume?.length??0)>0)B.beforeRun=async(G)=>{let K=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(J$(G.snapshot),K);return};if((Z.prompt_submit?.length??0)>0)B.onEvent=async(G)=>{if(G.type!=="message-added"||G.message.role!=="user")return;await J(yW({snapshot:G.snapshot},QG(G.message.content)))}}if((Z.tool_call?.length??0)>0)B.beforeTool=async(G)=>{let K=await X($G(G));return Nw(K)};if((Z.tool_result?.length??0)>0)B.afterTool=async(G)=>{await Y(ZG(G));return};if((Z.agent_end?.length??0)>0)B.afterRun=async({snapshot:G,result:K})=>{if(K.status!=="completed")return;await j({...J$(G),iteration:K.iterations,turn:{outputText:K.outputText,status:K.status}})};if((Z.agent_error?.length??0)>0||(Z.agent_abort?.length??0)>0||(Z.session_shutdown?.length??0)>0){let G=B.afterRun;B.afterRun=async(K)=>{await G?.(K);let{snapshot:F,result:A}=K;if(A.status==="aborted"||bW(A.error?.message)){await H({...J$(F),reason:A.error?.message});return}if(A.error)await V({...J$(F),iteration:A.iterations,error:A.error})}}return B}function s5($){return p5("core.hook_config_files",kW($))}function p$($,Z){let Q=$.map((W)=>W[Z]).filter((W)=>typeof W==="function");if(Q.length===0)return;return async(W)=>{let J;for(let X of Q){let Y=await X(W);if(!Y||typeof Y!=="object")continue;let j=Y;J={...J??{},...j,stop:J?.stop===!0||j.stop===!0?!0:j.stop,options:J?.options||j.options?{...J?.options??{},...j.options??{}}:void 0}}return J}}function _4($){let Z=$.filter((Q)=>Q!==void 0);if(Z.length===0)return;return{beforeRun:p$(Z,"beforeRun"),afterRun:p$(Z,"afterRun"),beforeModel:p$(Z,"beforeModel"),afterModel:p$(Z,"afterModel"),beforeTool:p$(Z,"beforeTool"),afterTool:p$(Z,"afterTool"),onEvent:p$(Z,"onEvent")}}import{z as X$}from"zod";var z4=H2;var WG=X$.object({settings:H2,updatedAt:X$.string().datetime(),tokenSource:X$.enum(["manual","oauth","migration"]).default("manual")}),o5=X$.object({version:X$.literal(1),lastUsedProvider:X$.string().min(1).optional(),providers:X$.record(X$.string(),WG)});function u2(){return{version:1,providers:{}}}r0();import{upsertWorkspaceInfo as ww,WorkspaceManifestSchema as IW}from"@cline/shared";class t5{manifest;listeners=new Set;constructor($){this.manifest=IW.parse($??{workspaces:{}})}async addWorkspacePath($){let Z=await U5($);return this.manifest=ww(this.manifest,Z),this.emit({type:"workspace_added",workspace:Z}),Z}async switchWorkspace($){let Z=b$($),Q=this.manifest.workspaces[Z];if(Q)return this.manifest=IW.parse({...this.manifest,currentWorkspacePath:Z}),this.emit({type:"workspace_switched",workspace:Q}),Q;let W=await this.addWorkspacePath(Z);return this.manifest=IW.parse({...this.manifest,currentWorkspacePath:W.rootPath}),this.emit({type:"workspace_switched",workspace:W}),W}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let Z=b$($);return this.manifest.workspaces[Z]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let Z of this.listeners)Z($)}}G0();import{createHash as Cw}from"node:crypto";var JG=new Set,XG=new Set;function Pw($){return Cw("sha256").update($).digest("hex")}function Sw($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function YG($){if(!$.telemetry)return;let Z=Pw($.rootPath),Q=$.rootCount??1;if(!JG.has(Z))JG.add(Z),o9($.telemetry,{root_count:Q,vcs_types:Sw($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!XG.has(Z)){XG.add(Z);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",t9($.telemetry,W,{fallback_to_single_root:!0,workspace_count:Q})}}function yw($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function hw($,Z,Q){if(Z.length>0)for(let X of Z)Q?.log(X.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(yw).join("; "),J=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${W}${J}. Use --verbose for more details.`,{severity:"warn"});for(let X of $)Q?.log(`Plugin initialization failed (${X.phase}) for ${X.pluginPath}`,{severity:"warn",stack:X.stack,pluginPath:X.pluginPath,pluginName:X.pluginName})}function kw($,Z){let Q=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!Q&&!W)return Z;return{...Z??{},...Q?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function jG($,Z){return bw($,Z)}function Iw($){let Z=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;Z+=1}return Z}function xw($){let Z={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||gw($.accessToken);if(Z.originator="cline",Z.session_id=$.sessionId,Z["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)Z["ChatGPT-Account-Id"]=Q;return Z}function gw($){let Z=$?.trim();if(!Z)return;let Q=z0(Z),W=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let J=Q?.organizations?.[0]?.id;if(typeof J==="string"&&J.length>0)return J;let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return}function mw($,Z,Q,W,J){let X=Q.getProviderSettings($.providerId),Y=W||X?.modelCatalog?{...W??{},...X?.modelCatalog??{}}:void 0,j=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,V={...X??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??X?.apiKey,baseUrl:$.baseUrl??X?.baseUrl,headers:$.providerId==="openai-codex"?xw({sessionId:Z,configHeaders:$.headers,storedHeaders:X?.headers,accountId:X?.auth?.accountId,accessToken:$.apiKey??X?.auth?.accessToken??X?.apiKey}):$.headers??X?.headers,reasoning:kw($,X?.reasoning),modelCatalog:Y},H={...B1(V),...j??{}};if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let G=$.fetch??H.fetch??J;if(G)H.fetch=G;return H}async function VG($){let{input:Z,sessionId:Q,providerSettingsManager:W,defaultTelemetry:J,defaultCapabilities:X,defaultToolPolicies:Y,defaultFetch:j,onPluginEvent:V,onTeamEvent:H,createSubAgentLifecycleCallbacks:B,createSpawnTool:G,localRuntime:K,readSessionMetadata:F,writeSessionMetadata:A}=$,L=W$(Z.config),{modelCatalogDefaults:f,userInstructionService:D,configExtensions:U,onTeamRestored:T,...q}=K??{},z=Object.keys(q).length>0?q:void 0,{workspaceInfo:_,workspaceMetadata:M,durationMs:E,vcsType:P,initError:c}=await mV(L),n=z?.extensionContext,a={...n??{},workspace:{..._,...n?.workspace??{}},session:{...n?.session??{},sessionId:Q},logger:n?.logger??z?.logger,telemetry:n?.telemetry??z?.telemetry??J};YG({telemetry:a.telemetry,rootPath:_.rootPath,workspaceInfo:_,rootCount:1,vcsType:P,durationMs:E,initError:c,featureFlagEnabled:!0});let t=s5({cwd:Z.config.cwd,workspacePath:L,rootSessionId:Q,logger:z?.logger,workspaceInfo:_}),p0=QH(z?.hooks)?void 0:a5({rootSessionId:Q,workspacePath:L,workspaceInfo:_}),K$=_4([z?.hooks,p0]),d;if(jG(U,"plugins"))try{d=await L6({pluginPaths:z?.pluginPaths,workspacePath:L,cwd:Z.config.cwd,onEvent:V,providerId:Z.config.providerId,modelId:Z.config.modelId,workspaceInfo:_,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),hw(d.failures,d.warnings,z?.logger)}catch(W2){let r9=W2 instanceof Error?W2.message:String(W2);z?.logger?.log?.(`plugin loading failed; continuing without plugins (${r9})`)}let N=b7(t?[t]:void 0,b7(z?.extensions,dZ(d?.extensions))),X0=jG(U,"plugins")?T$(d?.pluginPaths??[]):void 0,Y0={...Z.config,...z??{},sessionId:Q,hooks:K$,extensions:N,extensionContext:a,telemetry:a.telemetry},R0=mw(Y0,Q,W,f,j),Z2=_4([Y0.hooks,Y0.checkpoint?.enabled===!0?ZB({cwd:Y0.cwd,sessionId:Q,logger:Y0.logger,createCheckpoint:Y0.checkpoint?.createCheckpoint,initialRunCount:Iw(Z.initialMessages),readSessionMetadata:F,writeSessionMetadata:A}):void 0]),Y1={...Y0,providerConfig:R0,workspaceMetadata:M,hooks:Z2},t0=Z.toolPolicies??Y0.toolPolicies??Y,$8=O0(X,Z.capabilities),Q2=$8?.requestToolApproval,I4=$8?.toolExecutors,j1=B?.(Y1),x4=new t5({currentWorkspacePath:_.rootPath,workspaces:{[_.rootPath]:_}});return{effectiveInput:Z,config:Y1,providerConfig:R0,workspaceMetadata:M,workspaceInfo:_,extensions:N,hooks:Z2,toolPolicies:t0,requestToolApproval:Q2,pluginSandboxShutdown:d?.shutdown,runtimeBuilderInput:{config:Y1,hooks:Z2,extensions:N,onTeamEvent:H,createSpawnTool:G,onTeamRestored:T,onSubAgentEvent:j1?.onSubAgentEvent,onSubAgentStart:j1?.onSubAgentStart,onSubAgentEnd:j1?.onSubAgentEnd,userInstructionService:D,pluginSkillDirectories:X0,configExtensions:U,toolExecutors:I4,toolPolicies:t0,workspaceManager:x4,logger:Y1.logger,telemetry:Y1.telemetry,requestToolApproval:Q2}}}import{resolveDocumentsExtensionPath as vw}from"@cline/shared/storage";G0();function HG($,Z,Q,W,J){if(Q)$Z($.telemetry,{ulid:Z,apiProvider:$.providerId,...J});else e9($.telemetry,{ulid:Z,apiProvider:$.providerId,...J});cw($.telemetry,{workspacePath:W})}function cw($,Z){let Q=vw("Hooks"),W=c2(Z.workspacePath),J=new Map;for(let X of W){let Y=X.hookEventName??"unknown",j=J.get(Y)??{global:0,workspace:0};if(X.path===Q||X.path.startsWith(`${Q}/`))j.global+=1;else j.workspace+=1;J.set(Y,j)}for(let[X,Y]of J.entries())HZ($,X,Y.global,Y.workspace)}function BG($,Z){for(let Q of Z.mentions)jZ($,Q,Z.matchedFiles.includes(Q)?1:0,"file",!Z.matchedFiles.includes(Q));for(let Q of Z.matchedFiles)XZ($,"file",Q.length);for(let Q of Z.ignoredMentions)YZ($,"file","not_found",Q)}import{chmodSync as wG,existsSync as uW,mkdirSync as TC,readFileSync as OC,writeFileSync as qC}from"node:fs";import{basename as CG,dirname as dW}from"node:path";import{resolveProviderSettingsPath as MC}from"@cline/shared/storage";import{existsSync as uw,mkdirSync as dw,readFileSync as lw,writeFileSync as pw}from"node:fs";import{mkdir as rw,readFile as iw,writeFile as nw}from"node:fs/promises";import{dirname as xW,join as aw}from"node:path";import*as w0 from"@cline/llms";import{ModelCapabilitySchema as sw,ProviderCapabilitySchema as ow,ProviderClientSchema as tw,ProviderProtocolSchema as ew}from"@cline/shared";import{z as p}from"zod";var $C=p.object({id:p.string().optional(),name:p.string().optional(),maxTokens:p.number().optional(),contextWindow:p.number().optional(),maxInputTokens:p.number().optional(),capabilities:p.array(sw).optional(),supportsVision:p.boolean().optional(),supportsAttachments:p.boolean().optional(),supportsReasoning:p.boolean().optional()}).passthrough(),ZC=p.object({name:p.string(),baseUrl:p.string(),defaultModelId:p.string().optional(),protocol:ew.optional(),client:tw.optional(),capabilities:p.array(ow).optional(),modelsSourceUrl:p.string().optional()}).passthrough(),GG=p.object({provider:ZC.optional(),models:p.record(p.string(),$C).optional()}).passthrough(),KG=p.object({version:p.literal(1),providers:p.record(p.string(),GG)}),QC=p.object({version:p.literal(1),providers:p.record(p.string(),p.unknown())}),e5=new Set;function FG($){return $.split(/[-_]/).filter(Boolean).map((Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)).join(" ")}function r$($){return aw(xW($.getFilePath()),"models.json")}function $9(){return{version:1,providers:{}}}function AG($){let Z=QC.safeParse($);if(!Z.success)return $9();let Q={};for(let[W,J]of Object.entries(Z.data.providers)){let X=GG.safeParse(J);if(X.success)Q[W]=X.data}return{version:1,providers:Q}}function gW($){if(!uw($))return $9();try{let Z=lw($,"utf8");return AG(JSON.parse(Z))}catch{}return $9()}async function d2($){try{let Z=await iw($,"utf8");return AG(JSON.parse(Z))}catch{}return $9()}function fG($,Z){dw(xW($),{recursive:!0});let Q=KG.parse(Z);pw($,`${JSON.stringify(Q,null,2)}
578
+ `,"utf8")}async function Z9($,Z){await rw(xW($),{recursive:!0});let Q=KG.parse(Z);await nw($,`${JSON.stringify(Q,null,2)}
579
+ `,"utf8")}function UG($,Z){return{id:$,name:Z.name??$,supportsAttachments:Z.capabilities?.includes("files"),supportsVision:Z.capabilities?.includes("images"),supportsReasoning:Z.capabilities?.includes("reasoning")||Z.thinkingConfig!=null}}function DG($){if(!$||$.length===0)return;let Z=new Set;if($.includes("reasoning"))Z.add("reasoning");if($.includes("prompt-cache"))Z.add("prompt-cache");if($.includes("tools"))Z.add("tools");return Z.size>0?[...Z]:void 0}function LG($){let Z=new Set;if(!$||$.length===0)return[...Z];if($.includes("streaming"))Z.add("streaming");if($.includes("tools"))Z.add("tools");if($.includes("reasoning"))Z.add("reasoning");if($.includes("prompt-cache"))Z.add("prompt-cache");if($.includes("vision"))Z.add("images"),Z.add("files");return[...Z]}function WC($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function _G($,Z){return $??Z??"openai-chat"}function zG($,Z,Q){return $??Q??(Z==="openai-responses"?"openai":"openai-compatible")}function TG($,Z,Q){let W=new Set(Z?.capabilities??Q??[]);if(Z?.supportsVision)W.add("images");if(Z?.supportsAttachments)W.add("files");if(Z?.supportsReasoning)W.add("reasoning");return{id:$,name:Z?.name??$,maxTokens:Z?.maxTokens,contextWindow:Z?.contextWindow,maxInputTokens:Z?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function JC($,Z){for(let[Q,W]of Object.entries(Z??{})){let J=W.id?.trim()||Q.trim();if(!J)continue;w0.registerModel($,J,TG(J,W))}}function XC($,Z,Q){return{...Z??{},id:$,name:Z?.name??$,capabilities:Z?.capabilities??Q}}function YC($){return Object.assign({},...w0.resolveProviderModelCatalogKeys($).map((Q)=>w0.getGeneratedModelsForProvider(Q)))}function jC($){let Z=$.provider.trim();if(!Z||w0.isBuiltInProviderId(Z))return;let Q=$.baseUrl?.trim();if(!Q)return;let W=w0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z],J=YC(Z),X=LG($.capabilities),Y=X.length>0?X:void 0,j=$.model?.trim(),V={...J,...W?.models??{}};if(j)V[j]=XC(j,V[j],Y);let H=Object.keys(V).filter(Boolean),B=j||H[0];if(!B)return;let G=_G($.protocol,W?.provider.protocol),K=zG($.client,G,W?.provider.client);w0.registerProvider({provider:{id:Z,name:W?.provider.name??FG(Z),description:W?.provider.description,protocol:G,client:K,baseUrl:Q,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:B,capabilities:DG($.capabilities)??W?.provider.capabilities,source:"file"},models:V})}function Q9($){for(let Z of Object.values($.providers))jC(Z.settings)}function T4($,Z){let Q=Z.models??{};if(!WC(Z.provider)){JC($,Q);return}let W=LG(Z.provider.capabilities),J=Object.entries(Q).map(([H,B])=>({id:B.id?.trim()||H.trim(),model:B})).filter(({id:H})=>H.length>0),X=Z.provider.defaultModelId?.trim()||J[0]?.id||"default",Y=_G(Z.provider.protocol,void 0),j=zG(Z.provider.client,Y,void 0),V=Object.fromEntries(J.map(({id:H,model:B})=>[H,{...TG(H,B,W.length>0?W:void 0),status:"active"}]));w0.registerProvider({provider:{id:$,name:Z.provider.name.trim()||FG($),protocol:Y,client:j,baseUrl:Z.provider.baseUrl,modelsSourceUrl:Z.provider.modelsSourceUrl,defaultModelId:X,capabilities:DG(Z.provider.capabilities),source:"file"},models:V})}function OG($){let Z=r$($);if(e5.has(Z))return;let Q=gW(Z);for(let[W,J]of Object.entries(Q.providers))T4(W,J);e5.add(Z)}async function qG($){let Z=r$($);if(e5.has(Z))return;let Q=await d2(Z);for(let[W,J]of Object.entries(Q.providers))T4(W,J);e5.add(Z)}import{existsSync as VC,readFileSync as HC}from"node:fs";import{dirname as BC,join as mW}from"node:path";import*as l2 from"@cline/llms";import{resolveClineDataDir as GC}from"@cline/shared/storage";var W9="openai",EG=l2.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,MG=128000;function NG($){let Z=$?.trim();if(!Z)return;try{let Q=JSON.parse(Z);if(!Q)return;let W=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:W,accountId:Q.userInfo?.id}}catch{return}}function C($){let Z=$?.trim();return Z?Z:void 0}function KC($){return $==="credentials"?"iam":$}function RG($){if(!VC($))return;try{let Z=HC($,"utf8"),Q=JSON.parse(Z);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function FC($){let Z=$.dataDir??GC(),Q=$.globalStatePath??mW(Z,"globalState.json"),W=$.secretsPath??mW(Z,"secrets.json"),J=RG(Q),X=RG(W);if(!J&&!X)return;return{globalState:J??{},secrets:X??{}}}function vW($){if($===W9)return EG;return $}function AC($,Z,Q,W){let J=Q==="plan"?"planMode":"actMode",X=Z===W?C(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,j={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`}[Z];return(j?C(typeof $[j]==="string"?$[j]:void 0):void 0)??X}function fC($,Z,Q){let W=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,J=[...Z==="oca"?[$.actModeOcaReasoningEffort,$.planModeOcaReasoningEffort]:[],...Z==="gemini"?[$.geminiActModeThinkingLevel,$.geminiPlanModeThinkingLevel]:[],$.actModeReasoningEffort,$.planModeReasoningEffort].map(C).find(Boolean),X=J==="none"||J==="low"||J==="medium"||J==="high"||J==="xhigh"?J:void 0,Y=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function UC($){let Z=$["openai-codex-oauth-credentials"];if(!Z)return;try{let Q=JSON.parse(Z),W=C(Q.access_token),J=C(Q.refresh_token),X=C(Q.accountId);if(!W&&!J&&!X)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...J?{refreshToken:J}:{},...X?{accountId:X}:{}}}}catch{return}}function DC($){let Z=l2.getGeneratedModelsForProvider($),W=l2.getProviderCollectionSync($)?.provider.defaultModelId;if(W&&Z[W])return W;return Object.keys(Z)[0]??void 0}function LC($,Z,Q,W){let J=vW($),X=C(W==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),Y=AC(Z,$,W,X)??DC(J),j=fC(Z,J,W),V=typeof Z.requestTimeoutMs==="number"&&Number.isInteger(Z.requestTimeoutMs)&&Z.requestTimeoutMs>0?Z.requestTimeoutMs:void 0,H={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},B={};if($==="openai-codex")Object.assign(B,UC(Q));if($==="cline")try{let D=C(Q["cline:clineAccountId"]);if(D)B.auth={...B.auth??{},...NG(D)}}catch{}if($===W9&&Z.openAiHeaders)B.headers=Z.openAiHeaders;if($==="bedrock"){let D=KC(Z.awsAuthentication),U=D==="profile"||Z.awsUseProfile===!0;B.aws={accessKey:C(Q.awsAccessKey),secretKey:C(Q.awsSecretKey),sessionToken:C(Q.awsSessionToken),region:C(Z.awsRegion),authentication:D,profile:U?C(Z.awsProfile):void 0,usePromptCache:Z.awsBedrockUsePromptCache,useCrossRegionInference:Z.awsUseCrossRegionInference,useGlobalInference:Z.awsUseGlobalInference,endpoint:C(Z.awsBedrockEndpoint),customModelBaseId:C(W==="plan"?Z.planModeAwsBedrockCustomModelBaseId:Z.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")B.gcp={projectId:C(Z.vertexProjectId),region:C(Z.vertexRegion)};if($===W9&&(Z.azureApiVersion||Z.azureIdentity!==void 0))B.azure={apiVersion:C(Z.azureApiVersion),useIdentity:Z.azureIdentity};if($==="sapaicore"){let D=Z.sapAiCoreUseOrchestrationMode??!0;B.sap={clientId:C(Q.sapAiCoreClientId),clientSecret:C(Q.sapAiCoreClientSecret),tokenUrl:C(Z.sapAiCoreTokenUrl),resourceGroup:C(Z.sapAiResourceGroup),deploymentId:D?void 0:C(W==="plan"?Z.planModeSapAiCoreDeploymentId:Z.actModeSapAiCoreDeploymentId),useOrchestrationMode:D}}if($==="oca"){B.oca={mode:Z.ocaMode};let D=C(Q.ocaRefreshToken);if(D)B.auth={...B.auth??{},refreshToken:D}}if($==="qwen")B.apiLine=Z.qwenApiLine;if($==="moonshot")B.apiLine=Z.moonshotApiLine;if($==="zai")B.apiLine=Z.zaiApiLine;if($==="minimax")B.apiLine=Z.minimaxApiLine;let G={anthropic:Z.anthropicBaseUrl,openai:Z.openAiBaseUrl,ollama:Z.ollamaBaseUrl,lmstudio:Z.lmStudioBaseUrl,litellm:Z.liteLlmBaseUrl,gemini:Z.geminiBaseUrl,requesty:Z.requestyBaseUrl,asksage:Z.asksageApiUrl,dify:Z.difyBaseUrl,oca:Z.ocaBaseUrl,aihubmix:Z.aihubmixBaseUrl,sapaicore:Z.sapAiCoreBaseUrl},K=C(H[$]),F=C(G[$]),A={provider:J,...K?{apiKey:K}:{},...Y?{model:Y}:{},...F?{baseUrl:F}:{},...j?{reasoning:j}:{},...V?{timeout:V}:{},...B},L=z4.safeParse(A);if(!L.success)return;return Object.keys(A).filter((D)=>D!=="provider").length>0?L.data:void 0}function _C($,Z){if($!==EG)return;if(!Z.baseUrl||!Z.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:Z.baseUrl,defaultModelId:Z.model},models:{[Z.model]:{id:Z.model,name:Z.model,contextWindow:MG,maxInputTokens:MG,capabilities:["streaming","tools","images"]}}}}function zC($,Z){let Q=new Set;for(let J of[$.actModeApiProvider,$.planModeApiProvider]){let X=C(J);if(X)Q.add(X)}if(C(Z.apiKey))Q.add("anthropic");if(C(Z.openRouterApiKey))Q.add("openrouter");if(C(Z.openAiApiKey))Q.add(W9);if(C(Z.openAiNativeApiKey))Q.add("openai-native");if(C(Z["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(C(Z.geminiApiKey))Q.add("gemini");if(C(Z.ollamaApiKey))Q.add("ollama");if(C(Z.awsAccessKey)||C(Z.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||C($.awsProfile))Q.add("bedrock");if(C($.vertexProjectId)||C($.vertexRegion))Q.add("vertex");if(C(Z.clineApiKey))Q.add("cline");let W=NG(C(Z["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)Q.add("cline");if(C(Z.ocaApiKey))Q.add("oca");if(C(Z.sapAiCoreClientId)||C(Z.sapAiCoreClientSecret)||C($.sapAiCoreTokenUrl)||C($.sapAiCoreBaseUrl)||C($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function cW($){let Z=$.providerSettingsManager.read(),Q=FC($);if(!Q)return{migrated:!1,providerCount:Object.keys(Z.providers).length,lastUsedProvider:Z.lastUsedProvider};let{globalState:W,secrets:J}=Q,X=W.mode==="plan"?"plan":"act",Y=zC(W,J),j=u2();j.providers={...Z.providers},j.lastUsedProvider=Z.lastUsedProvider;let V=new Date().toISOString(),H=0,B=mW(BC($.providerSettingsManager.getFilePath()),"models.json"),G=gW(B),K=0;for(let L of Y){let f=vW(L);if(j.providers[f])continue;let D=LC(L,W,J,X);if(!D)continue;j.providers[f]={settings:D,updatedAt:V,tokenSource:"migration"},H+=1;let U=_C(f,D);if(U&&!G.providers[f])G.providers[f]=U,K+=1}if(H===0&&K===0)return{migrated:!1,providerCount:Object.keys(Z.providers).length,lastUsedProvider:Z.lastUsedProvider};let F=C(X==="plan"?W.planModeApiProvider:W.actModeApiProvider),A=F?vW(F):void 0;if(j.lastUsedProvider=Z.lastUsedProvider??(A&&j.providers[A]?A:Object.keys(j.providers)[0]),$.providerSettingsManager.write(j),K>0)fG(B,G);return{migrated:H>0||K>0,providerCount:Object.keys(j.providers).length,lastUsedProvider:j.lastUsedProvider}}function RC(){return new Date().toISOString()}var EC="cline",NC="cline-pass";function wC($){if(CG($)!=="providers.json")return;let Z=dW($);if(CG(Z)!=="settings")return;return dW(Z)}class Y${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??MC(),this.dataDir=$.dataDir??wC(this.filePath),this.dataDir||!$.filePath)cW({providerSettingsManager:this,dataDir:this.dataDir});if(OG(this),Q9(this.read()),uW(this.filePath))try{wG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!uW(this.filePath))return u2();try{let $=OC(this.filePath,"utf8"),Z=JSON.parse($),Q=o5.safeParse(Z);if(Q.success)return Q9(Q.data),Q.data}catch{}return u2()}write($){let Z=o5.parse($),Q=dW(this.filePath);if(!uW(Q))TC(Q,{recursive:!0,mode:448});qC(this.filePath,`${JSON.stringify(Z,null,2)}
580
+ `,"utf8");try{wG(this.filePath,384)}catch{}Q9(Z)}saveProviderSettings($,Z={}){let Q=z4.parse($),W=this.read(),J=Q.provider,X=Z.setLastUsed!==!1,Y=W.providers[J],j=Z.tokenSource??Y?.tokenSource??"manual",V={...W,providers:{...W.providers,[J]:{settings:Q,updatedAt:RC(),tokenSource:j}},lastUsedProvider:X?J:W.lastUsedProvider};return this.write(V),V}resolveProviderSettings($,Z){let Q=$.providers[Z]?.settings,J=B0(Z)?.storageProviderId;if(!J||J===Z)return Q;let X=$.providers[J]?.settings;if(!X)return Q;return z4.parse({...X.auth?{auth:X.auth}:{},...X.apiKey?{apiKey:X.apiKey}:{},...X.baseUrl?{baseUrl:X.baseUrl}:{},...Q??{},provider:Z})}getProviderSettings($){let Z=this.read();return this.resolveProviderSettings(Z,$)}resolveLastUsedProviderId($,Z){let Q=$.lastUsedProvider;if(Q===NC&&Z.isClinePassEnabled===!1)return EC;return Q}getLastUsedProviderSettings($={}){let Z=this.read(),Q=this.resolveLastUsedProviderId(Z,$);if(!Q)return;return this.resolveProviderSettings(Z,Q)}getProviderConfig($,Z){let Q=this.getProviderSettings($);if(!Q)return;return B1(Q,Z)}getLastUsedProviderConfig($={}){let Z=this.getLastUsedProviderSettings($);if(!Z)return;return B1(Z,$)}async refreshCatalog(){try{await J6({})}catch{}}}G0();g2();import{execFile as CC}from"node:child_process";import{promisify as PC}from"node:util";var p2=PC(CC);function O4($){let Z=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(Z?.history)?Z.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let J=String(W.ref??"").trim(),X=Number(W.createdAt??0),Y=Number(W.runCount??0);if(J.length===0||!Number.isFinite(X)||!Number.isInteger(Y)||Y<1)return[];let j=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:J,createdAt:X,runCount:Y,...j?{kind:j}:{}}]})}function PG($,Z){let Q=O4($).filter((J)=>J.runCount<=Z),W=Q.at(-1);return W?{latest:W,history:Q}:void 0}function J9($,Z){return $.reduce((Q,W)=>{if(W.runCount>Z)return Q;if(!Q||W.runCount>Q.runCount)return W;return Q},void 0)}function SG($,Z){let Q=0;for(let W=0;W<$.length;W+=1){let J=$[W];if(J?.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"?J.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===Z)return W}throw Error(`Could not find user message for checkpoint run ${Z}`)}function SC($,Z){let Q=SG($,Z);return $.slice(0,Q+1)}function bG($,Z){let Q=SG($,Z);return $.slice(0,Q)}function yG($){let Z=$.checkpointRunCount;if(!Number.isInteger(Z)||Z<1)throw Error("checkpointRunCount must be a positive integer");let Q=J9(O4($.session),Z);if(!Q)throw Error(`No checkpoint found at or before run ${Z} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:W,...$.restoreMessages!==!1?{messages:SC($.messages??[],Z)}:{}}}async function hG($,Z){if((await p2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await p2("git",["-C",$,"cat-file","-e",`${Z.ref}^{commit}`],{windowsHide:!0}),await p2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await p2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),Z.kind==="commit"){await p2("git",["-C",$,"reset","--hard",Z.ref],{windowsHide:!0});return}await p2("git",["-C",$,"stash","apply",Z.ref],{windowsHide:!0})}class s0 extends Error{code;constructor($,Z){super(Z);this.code=$;this.name="SessionVersioningError"}}function bC($){let Z=$.sessionId.trim();if(!Z)throw new s0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new s0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new s0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new s0("invalid_restore","checkpointRunCount must be a positive integer");return Z}class r2{async restoreCheckpoint($){let Z=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,W=bC({sessionId:$.sessionId,restoreMessages:Z,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),J=await $.getSession(W);if(!J)throw new s0("session_not_found",`Session ${W} not found`);let X=Z?await $.readMessages(W):void 0;if(Z&&X?.length===0)throw new s0("session_messages_not_found",`No messages found for session ${W}`);let Y=yG({session:J,messages:X,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:Z});if(Q)await($.applyWorkspaceCheckpoint??hG)(Y.cwd,Y.checkpoint);let j=t1({session:J,messages:X});if(!Z)return{checkpoint:Y.checkpoint,sourceSnapshot:j};let V=PG(J,$.checkpointRunCount),H=$.restore?.omitCheckpointMessageFromSession?bG(X??[],$.checkpointRunCount):Y.messages??[],B={sourceSession:J,sourceMessages:X,sourceSnapshot:j,plan:Y,restoredCheckpointMetadata:V,initialMessages:H,restoreMessages:Z,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new s0("invalid_restore","start is required when restore.messages is true");let G=$.buildStartInput?await $.buildStartInput(B,$.start):$.start,K=await $.startSession(G),F=$.getStartedSessionId?.(K);if(F)await($.retainCheckpointRefs??$B)(Y.cwd,F,V?.history??[]);let A=F&&$.readRestoredSession?await $.readRestoredSession(F):void 0;return{sessionId:F,startResult:K,messages:Y.messages,checkpoint:Y.checkpoint,sourceSnapshot:j,...A?{restoredSnapshot:t1({session:A,messages:H})}:{}}}}import{hasRuntimeConfigExtension as rC}from"@cline/shared";import{nanoid as iC}from"nanoid";r0();import{appendFileSync as yC,existsSync as i2,mkdirSync as kG,readdirSync as hC,readFileSync as IG,renameSync as kC,writeFileSync as IC}from"node:fs";import{join as lW}from"node:path";import{resolveTeamDataDir as xC}from"@cline/shared/storage";function xG(){return new Date().toISOString()}function pW($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function gG($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class X9{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??xC()}init(){this.ensureTeamDir()}listTeamNames(){if(!i2(this.teamDirPath))return[];return hC(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>i2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let Z=this.readEnvelope($);return Z?.teamState?gG(Z.teamState):void 0}readHistory($,Z=200){let Q=this.historyPath($);if(!i2(Q))return[];return IG(Q,"utf8").split(`
581
+ `).map((W)=>W.trim()).filter(Boolean).map((W)=>{try{return JSON.parse(W)}catch{return}}).filter((W)=>W!==void 0).reverse().slice(0,Z)}loadRuntime($){let Z=this.readEnvelope($);return{state:Z?.teamState?gG(Z.teamState):void 0,teammates:Z?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,Z){this.ensureTeamSubdir($),yC(this.historyPath($),`${JSON.stringify({ts:xG(),eventType:Z.type,payload:Z})}
582
+ `,"utf8")}persistRuntime($,Z,Q){this.ensureTeamSubdir($);let W={version:1,updatedAt:xG(),teamState:Z,teammates:Q},J=this.statePath($),X=`${J}.tmp`;IC(X,`${JSON.stringify(W,null,2)}
583
+ `,"utf8"),kC(X,J)}markInProgressRunsInterrupted($,Z){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let W=Q.teamState.runs.filter((X)=>X.status==="queued"||X.status==="running").map((X)=>X.id);if(W.length===0)return[];let J=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((X)=>X.status==="queued"||X.status==="running"?{...X,status:"interrupted",error:Z,endedAt:J}:X)},this.persistRuntime($,Q.teamState,Q.teammates),W}ensureTeamDir(){if(!i2(this.teamDirPath))kG(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let Z=lW(this.ensureTeamDir(),pW($));if(!i2(Z))kG(Z,{recursive:!0});return Z}statePath($){return lW(this.ensureTeamDir(),pW($),"state.json")}historyPath($){return lW(this.ensureTeamDir(),pW($),"task-history.jsonl")}readEnvelope($){let Z=this.statePath($);if(!i2(Z))return;try{let Q=JSON.parse(IG(Z,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as gC,mkdirSync as mC}from"node:fs";import{join as vC}from"node:path";import{safeJsonParse as mG}from"@cline/shared";import{loadSqliteDb as cC,nowIso as rW}from"@cline/shared/db";import{resolveDbDataDir as uC}from"@cline/shared/storage";function dC(){return uC()}function n2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function lC($){let Z=mG($);if(!Array.isArray(Z))return[];let Q=[];for(let W of Z){if(!W||typeof W!=="object")continue;let J=W,X=J.agentId,Y=J.rolePrompt;if(typeof X!=="string"||!X.trim())continue;if(typeof Y!=="string"||!Y.trim())continue;let j={agentId:X.trim(),rolePrompt:Y};if(typeof J.modelId==="string"&&J.modelId.trim())j.modelId=J.modelId.trim();if(typeof J.maxIterations==="number"&&Number.isFinite(J.maxIterations))j.maxIterations=Math.max(1,Math.floor(J.maxIterations));Q.push(j)}return Q}function pC($){return{...$,tasks:$.tasks.map((Z)=>({...Z,createdAt:new Date(Z.createdAt),updatedAt:new Date(Z.updatedAt)})),mailbox:$.mailbox.map((Z)=>({...Z,sentAt:new Date(Z.sentAt),readAt:Z.readAt?new Date(Z.readAt):void 0})),missionLog:$.missionLog.map((Z)=>({...Z,ts:new Date(Z.ts)})),runs:($.runs??[]).map((Z)=>({...Z,startedAt:new Date(Z.startedAt),endedAt:Z.endedAt?new Date(Z.endedAt):void 0,nextAttemptAt:Z.nextAttemptAt?new Date(Z.nextAttemptAt):void 0,heartbeatAt:Z.heartbeatAt?new Date(Z.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),finalizedAt:Z.finalizedAt?new Date(Z.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((Z)=>({...Z,createdAt:new Date(Z.createdAt),reviewedAt:Z.reviewedAt?new Date(Z.reviewedAt):void 0}))}}class q4{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??dC()}init(){this.getRawDb()}ensureTeamDir(){if(!gC(this.teamDirPath))mC(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return vC(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=cC(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
584
584
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
585
585
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
586
586
  version INTEGER NOT NULL
@@ -664,7 +664,7 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
664
664
  version INTEGER NOT NULL DEFAULT 1,
665
665
  PRIMARY KEY(team_name, fragment_id)
666
666
  );
667
- `)}run($,Z=[]){return this.getRawDb().prepare($).run(...Z)}queryOne($,Z=[]){return this.getRawDb().prepare($).get(...Z)??void 0}queryAll($,Z=[]){return this.getRawDb().prepare($).all(...Z)}withTransaction($){let Z=this.getRawDb();Z.exec("BEGIN IMMEDIATE;");try{$(),Z.exec("COMMIT;")}catch(Q){try{Z.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[n2($)]);if(!Z)return;let Q=mG(Z.state_json);if(!Q)return;try{return cC(Q)}catch{return}}readHistory($,Z=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[n2($),Z]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let Z=n2($),Q=this.readState(Z),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Z]),J=W?vC(W.teammates_json):[];return{state:Q,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,Z,Q,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
667
+ `)}run($,Z=[]){return this.getRawDb().prepare($).run(...Z)}queryOne($,Z=[]){return this.getRawDb().prepare($).get(...Z)??void 0}queryAll($,Z=[]){return this.getRawDb().prepare($).all(...Z)}withTransaction($){let Z=this.getRawDb();Z.exec("BEGIN IMMEDIATE;");try{$(),Z.exec("COMMIT;")}catch(Q){try{Z.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[n2($)]);if(!Z)return;let Q=mG(Z.state_json);if(!Q)return;try{return pC(Q)}catch{return}}readHistory($,Z=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[n2($),Z]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let Z=n2($),Q=this.readState(Z),W=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Z]),J=W?lC(W.teammates_json):[];return{state:Q,teammates:J,interruptedRunIds:[]}}appendTeamEvent($,Z,Q,W){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
668
668
  VALUES (?, ?, ?, ?, NULL, ?)`,[n2($),rW(),Z,JSON.stringify(Q),W??null])}persistRuntime($,Z,Q){let W=n2($),J=rW();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
669
669
  VALUES (?, ?, ?, ?)
670
670
  ON CONFLICT(team_name) DO UPDATE SET
@@ -711,42 +711,42 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
711
711
  reviewed_by = excluded.reviewed_by,
712
712
  reviewed_at = excluded.reviewed_at,
713
713
  version = team_outcome_fragments.version + 1`,[W,X.outcomeId,X.id,X.section,X.sourceAgentId,X.sourceRunId??null,X.content,X.status,X.reviewedBy??null,X.reviewedAt?X.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,Z){let Q=n2($),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Q]);if(W.length===0)return[];let J=rW();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
714
- WHERE team_name = ? AND status IN ('queued', 'running')`,[Z,J,Q]),W.map((X)=>X.run_id)}handleTeamEvent($,Z){this.appendTeamEvent($,Z.type,Z)}}function vG($={}){try{let Z=new q4($);return Z.init(),Z}catch{let Z=new J9({teamDir:$.teamDir});return Z.init(),Z}}function X9($,Z){return uC($,Z)}function lC($,Z){let Q=Z?.["*"]??{},W=Z?.[$]??{};return{...Q,...W}.enabled!==!1}function pC($,Z){return $.filter((Q)=>lC(Q.name,Z))}function iW($,Z){return k1(pC($,Z))}var rC={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 iC($){let Z=$.trim().toLowerCase();return rC[Z]??Z}function nC($,Z){if(Z.tools===void 0)return $;let Q=new Set(Z.tools.map(iC));if(Z.skills!==void 0)Q.add("skills");return $.filter((W)=>Q.has(W.name))}function cG(){return`team-${dC(5)}`}function Y9($,Z,Q,W,J,X,Y,j){let V=e0[u1({mode:Q})],H=_8(Z,W,Q,J??L8);return iW(w8({cwd:$,...V,enableSkills:!!Y,...H,executors:{...Y?{skills:Y}:{},...j??{}}}),X)}function aC($){return Y9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,sC,$.toolExecutors).some((Z)=>Z.name==="skills")}var sC=async()=>"";async function oC($){let Z=Z0();if(!w$({filePath:Z}))return{tools:[]};let Q=new I8({clientFactory:B5({settingsPath:Z})}),W;try{W=await k8(Q,{filePath:Z})}catch(j){await Q.dispose().catch(()=>{});let V=j instanceof Error?j.message:String(j);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=W.filter((j)=>j.disabled!==!0),X=await Promise.allSettled(J.map((j)=>K5({serverName:j.name,provider:Q}))),Y=[];for(let[j,V]of X.entries())if(V.status==="fulfilled")Y.push(...V.value);else{let H=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[j].name}", skipping: ${H}`)}return{tools:Y,shutdown:async()=>{await Q.dispose()}}}function tC($,Z){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,Z)}catch{}}function eC($){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 $P($){let Z=e0[u1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??Z.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??Z.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 j9{teamRuntimeEntries=new Map;async build($){let{config:Z,hooks:Q,extensions:W,logger:J,telemetry:X,createSpawnTool:Y,onTeamRestored:j,userInstructionService:V,configExtensions:H,toolExecutors:B}=$,G=$.onTeamEvent??(()=>{}),K=$P(Z),F=Z.workspaceRoot??Z.cwd,A=$.toolPolicies??Z.toolPolicies,L=G1(),f=[],D=Z.teamName?.trim()||cG(),U=Z.sessionId?.trim()||D,T=K.enableSpawnAgent?y5({workspaceRoot:F}):{configs:[],errors:[]},O=T.configs.some((x)=>x.skills!==void 0),z=X9(H,"rules"),_=X9(H,"skills"),M=_||O,E=X9(H,"workflows"),P=X9(H,"plugins"),c=z||_||E,n=!1,a=Boolean(V),t=V,p0;for(let x of T.errors)(J??Z.logger)?.log?.(`[agents] Failed to load agent config at ${x.path}: ${x.error.message}`);if(!t&&(c||O))t=w2({skills:M?{workspacePath:F,includePluginSkills:P,pluginSkillDirectories:P?$.pluginSkillDirectories:void 0,pluginPaths:Z.pluginPaths,cwd:Z.cwd}:{workspacePath:F},rules:{workspacePath:Z.cwd},workflows:{workspacePath:Z.cwd}});if(t)await t.start().catch(()=>{});let K$=K.enableTools&&_&&Boolean(t)&&t?.hasConfiguredSkills(Z.skills)===!0&&aC({cwd:Z.cwd,providerId:Z.providerId,mode:K.mode,modelId:Z.modelId,toolRoutingRules:Z.toolRoutingRules,toolPolicies:A,toolExecutors:B}),d=t&&c?t.createExtension({includeRules:z,includeSkills:_,includeWorkflows:E,registerSkillsTool:K$,allowedSkillNames:Z.skills}):void 0,X1=d?[...W??Z.extensions??[],d]:W??Z.extensions;if(K.enableTools){if(f.push(...Y9(Z.cwd,Z.providerId,K.mode,Z.modelId,Z.toolRoutingRules,A,void 0,B)),!K.disableMcpSettingsTools){let x=await oC(Z.logger);f.push(...x.tools),p0=x.shutdown}}let N,X0=K.enableAgentTeams?vG():void 0,Y0=X0?.loadRuntime(U),M0=Y0?.state,$2=Y0?.teammates??[],Y1=new Map($2.map((x)=>[x.agentId,x])),t0=Z.sessionId||D,$8,Z2=[],I4=!1,j1=R2({providerId:Z.providerId,modelId:Z.modelId,cwd:Z.cwd,apiKey:Z.apiKey??"",baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxTokensPerTurn:Z.maxTokensPerTurn,maxIterations:Z.maxIterations,hooks:Q,extensions:X1,logger:J??Z.logger,telemetry:$.telemetry??Z.telemetry,workspaceMetadata:Z.workspaceMetadata});if(K.enableSpawnAgent){if(T.configs.length>0)f.push(...iW(k5({configProvider:j1,agents:T.configs,createSubAgentTools:(x)=>K.enableTools?nC(Y9(Z.cwd,x.providerId??Z.providerId,K.mode,x.modelId??Z.modelId,Z.toolRoutingRules,A,x.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(x.skills):void 0,B),x):[],hookErrorMode:Z.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(t0))this.teamRuntimeEntries.set(t0,{delegatedAgentConfigProvider:j1});let x4=()=>{if(!K.enableAgentTeams)return;let x=this.teamRuntimeEntries.get(t0)??{delegatedAgentConfigProvider:j1};if(this.teamRuntimeEntries.set(t0,x),N=x.runtime,!N){if(N=new B4({teamName:D,leadAgentId:Z.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(Q0)=>{if(G(Q0),N&&X0){if(Q0.type==="teammate_spawned"&&Q0.teammate?.rolePrompt){let V1={agentId:Q0.agentId,rolePrompt:Q0.teammate.rolePrompt,modelId:Q0.teammate.modelId,maxIterations:Q0.teammate.maxIterations};Y1.set(V1.agentId,V1)}if(Q0.type==="teammate_shutdown"&&!eC(Q0.reason))Y1.delete(Q0.agentId);X0.handleTeamEvent(U,Q0),X0.persistRuntime(U,N.exportState(),Array.from(Y1.values()))}}}),M0)N.hydrateState(M0),I4=!0;x.runtime=N}if(!n){if(!N)return;n=!0;let Q0=Z5({runtime:N,leadAgentId:Z.sessionId||"lead",restoredFromPersistence:Boolean(M0),restoredTeammates:$2,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(V1)=>{Z2=V1,$8?.addTools(V1)},createBaseTools:K.enableTools?()=>Y9(Z.cwd,Z.providerId,K.mode,Z.modelId,Z.toolRoutingRules,A,void 0,B):void 0,teammateConfigProvider:j1});if(I4)N.recoverActiveRuns("runtime_recovered");if(Q0.restoredFromPersistence)j?.();f.push(...Q0.tools)}return N};if(K.enableSpawnAgent&&Y){let x=Y();f.push({...x,execute:async(Q0,V1)=>{return x4(),x.execute(Q0,V1)}})}if(K.enableAgentTeams)x4();let Q2=iW(f,A),p9=Q2.some((x)=>x.name==="submit_and_exit"&&x.lifecycle?.completesRun===!0),g4=K.enableAgentTeams?()=>{let x=this.teamRuntimeEntries.get(t0)?.runtime;if(!x)return;let Q0=x.listTasks(),V1=Q0.some((N1)=>N1.status==="in_progress"||N1.status==="pending"),FJ=x.listRuns({}),qA=FJ.some((N1)=>N1.status==="running"||N1.status==="queued");if(V1||qA){let N1=Q0.filter((P0)=>P0.status==="in_progress"||P0.status==="pending").map((P0)=>`${P0.id} (${P0.status}): ${P0.title}`).join(", "),AJ=FJ.filter((P0)=>P0.status==="running"||P0.status==="queued").map((P0)=>`${P0.id} (${P0.status})`).join(", "),r9=[];if(N1)r9.push(`Unfinished tasks: ${N1}`);if(AJ)r9.push(`Active runs: ${AJ}`);return`[SYSTEM] You still have team obligations. ${r9.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,OA=p9?{requireCompletionTool:!0,...g4?{completionGuard:g4}:{}}:g4?{completionGuard:g4}:void 0;return{tools:Q2,logger:J??Z.logger,telemetry:X??Z.telemetry,teamRuntime:N,teamRestoredFromPersistence:Boolean(M0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(t0)?.delegatedAgentConfigProvider??j1,extensions:X1,completionPolicy:OA,registerLeadAgent:(x)=>{if($8=x,Z2.length>0)x.addTools(k1(Z2,[...L]))},shutdown:async(x)=>{if(tC(N,x),this.teamRuntimeEntries.delete(t0),await p0?.(),!a)t?.stop()}}}}function ZP($,Z){let Q=$?.expiresAt,W=Z?.expiresAt;return $?.accessToken===Z?.accessToken&&$?.refreshToken===Z?.refreshToken&&$?.accountId===Z?.accountId&&Q===W}class V9 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 nW{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new Y$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let Z=B0($.providerId);if(!Z)return null;return this.resolveWithSingleFlight(Z.providerId,Z.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,Z,Q=!1){let W=this.refreshInFlight.get(Z);if(W)return W;let J=this.resolveProviderApiKeyInternal($,Z,Q).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete(Z)});return this.refreshInFlight.set(Z,J),J}async resolveProviderApiKeyInternal($,Z,Q){let W=B0($);if(!W)return null;let J=this.providerSettingsManager.getProviderSettings(Z);if(!J)return null;let X=wZ($,J);if(!X)return null;let Y=await W.refresh({settings:J,credentials:X,forceRefresh:Q,telemetry:this.telemetry});if(!Y)throw new V9($);let j=X8({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:Y,setLastUsed:!1,save:!1}),V=!ZP(J.auth,j.auth);if(V)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:W.getApiKey(j)??Y.access,accountId:Y.accountId,refreshed:V}}}import{normalizeUserInput as QP}from"@cline/shared";import{nanoid as WP}from"nanoid";class uG{list($){return $?v0($):[]}update($,Z){if(!$)return{sessionId:Z.sessionId,prompts:[],updated:!1};let Q=Z.promptId.trim(),W=$.pendingPrompts.findIndex((V)=>V.id===Q);if(W<0)return{sessionId:Z.sessionId,prompts:v0($),updated:!1};let J=$.pendingPrompts[W];if(!J)return{sessionId:Z.sessionId,prompts:v0($),updated:!1};let X=Z.prompt===void 0?J.prompt:QP(Z.prompt).trim();if(!X)throw Error("prompt cannot be empty");let Y=Z.delivery??J.delivery,j={...J,prompt:X,mode:Z.mode??J.mode,delivery:Y};return $.pendingPrompts.splice(W,1),JP($,j,W,J.delivery),{sessionId:Z.sessionId,prompts:v0($),prompt:H9(j),updated:!0}}delete($,Z){if(!$)return{sessionId:Z.sessionId,prompts:[],removed:!1};let Q=Z.promptId.trim(),W=$.pendingPrompts.findIndex((X)=>X.id===Q);if(W<0)return{sessionId:Z.sessionId,prompts:v0($),removed:!1};let[J]=$.pendingPrompts.splice(W,1);return{sessionId:Z.sessionId,prompts:v0($),prompt:J?H9(J):void 0,removed:!0}}enqueue($,Z){let{prompt:Q,mode:W,delivery:J,userImages:X,userFiles:Y}=Z,j=$.pendingPrompts.findIndex((V)=>V.prompt===Q);if(j>=0){let[V]=$.pendingPrompts.splice(j,1),H={...V,prompt:Q,mode:W??V.mode,userImages:X??V.userImages,userFiles:Y??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...H,delivery:"steer"});else $.pendingPrompts.push(H)}else{let V={id:`pending_${Date.now()}_${WP(5)}`,prompt:Q,mode:W,delivery:J,userImages:X,userFiles:Y};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return v0($)}consumeSteer($){let Z=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(Z<0)return{prompts:v0($)};let[Q]=$.pendingPrompts.splice(Z,1);return{entry:Q,prompts:v0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:v0($)}}requeueFront($,Z){return $.pendingPrompts.unshift(Z),v0($)}clear($){return $.pendingPrompts.length=0,[]}}class aW{deps;service=new uG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let Z=this.deps.getSession($.sessionId);if(!Z||Z.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(Z,$);return this.emitPrompts(Z),this.scheduleDrain($.sessionId,Z),Q}delete($){let Z=this.deps.getSession($.sessionId);if(!Z||Z.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(Z,$);return this.emitPrompts(Z),this.scheduleDrain($.sessionId,Z),Q}enqueue($,Z){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,Z),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let Z=this.deps.getSession($);if(!Z)return;let{entry:Q}=this.service.consumeSteer(Z);if(!Q)return;return this.emitPrompts(Z),this.emitSubmitted(Z,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:v0($)}})}scheduleDrain($,Z){if(Z.pendingPrompts.length===0||Z.aborting||Z.drainingPendingPrompts||!Z.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let Z=this.deps.getSession($);if(!Z)return;if(Z.aborting||Z.drainingPendingPrompts)return;if(!Z.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(Z);if(!Q)return;this.emitPrompts(Z),this.emitSubmitted(Z,Q),Z.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{W=!1,this.service.requeueFront(Z,Q),this.emitPrompts(Z)}finally{if(Z.drainingPendingPrompts=!1,W&&Z.pendingPrompts.length>0&&Z.status!=="failed"&&Z.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,Z){let Q=H9(Z);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount,userImages:Q.userImages,userFiles:Q.userFiles}})}}function H9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function v0($){return $.pendingPrompts.map(H9)}function JP($,Z,Q,W){if(Z.delivery==="steer")$.pendingPrompts.unshift(Z);else if(W==="steer")$.pendingPrompts.push(Z);else $.pendingPrompts.splice(Q,0,Z)}G0();class oW{deps;constructor($){this.deps=$}dispatchAgentEvent($,Z,Q){let W=this.deps.getSession($),J={sessionId:$,config:Z,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},X=NW(Q),Y=!!W&&(!X.agentId||X.agentId===sW(W.agent));wW(J,Q,Y?{isPrimaryAgentEvent:!0,agentId:sW(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,Z){let Q=this.deps.getSession($);if(Q){if(HW(Q,Z),Z.type==="agent_event"){let W={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};wW(W,Z.event,{agentId:Z.agentId,teamRole:"teammate",teamAgentId:Z.agentId,isPrimaryAgentEvent:!1})}if(Z.type==="teammate_spawned"){let W=O1({agentId:Z.teammate.runtimeAgentId??Z.agentId,conversationId:Z.teammate.conversationId,parentAgentId:Z.teammate.parentAgentId,createdByAgentId:sW(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:Z.agentId});if(W)f$(Q.config.telemetry,{ulid:$,modelId:Z.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...W})}}if(await BW($,Z,this.deps.invokeBackendOptional),Q)GW(Q,$,Z,this.deps.emit)}async handlePluginEvent($,Z,Q){if(Z.name==="plugin_log"){this.handlePluginLog($,Z.payload);return}if(Z.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!V)return;let H=Z.payload&&typeof Z.payload==="object"?Z.payload:void 0;if(!H)return;await V.ingestEvent(H);return}if(Z.name!=="steer_message"&&Z.name!=="queue_message"&&Z.name!=="pending_prompt")return;let W=Z.payload&&typeof Z.payload==="object"?Z.payload:void 0,J=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,X=typeof W?.prompt==="string"?W.prompt.trim():"";if(!X)return;let Y=Z.name==="steer_message"?"steer":Z.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:X,delivery:Y})}handlePluginLog($,Z,Q){let W=this.deps.getSession($),J=Q??W?.config.extensionContext?.logger??W?.config.logger;if(!J||!Z||typeof Z!=="object")return;let X=Z,Y=typeof X.message==="string"?X.message:"";if(!Y)return;let j=X.metadata&&typeof X.metadata==="object"?{...X.metadata}:{};if(j.sessionId??=$,typeof X.pluginName==="string"&&X.pluginName)j.pluginName=X.pluginName;if(X.level==="debug"){J.debug(Y,j);return}if(X.level==="error"){if(J.error)J.error(Y,j);else J.log(Y,{...j,severity:"error"});return}J.log(Y,j)}}function sW($){return $.getAgentId()}function tW($){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:W$($.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 eW($,Z){let Q=$[Z];return typeof Q==="function"?Q:null}async function dG($,Z,...Q){let W=eW($,Z);if(!W)throw Error(`session service method not available: ${Z}`);return Promise.resolve(W.apply($,Q))}async function lG($,Z,...Q){let W=eW($,Z);if(!W)return;await Promise.resolve(W.apply($,Q))}async function pG($,Z,...Q){let W=eW($,Z);if(!W)return;return await Promise.resolve(W.apply($,Q))}r0();G0();function $3($,Z,Q){return{onSubAgentEvent:(W)=>$.onAgentEvent(Q,Z,W),onSubAgentStart:(W)=>{let J=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(W.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let X=O1({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:W.parentAgentId});if(X)f$(Z.telemetry,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,...X});d4(Z.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:W.parentAgentId,agentId:W.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",Q,W)},onSubAgentEnd:(W)=>{let J=$.getSession(Q)?.runtime.teamRuntime,X=$.subAgentStarts.get(W.subAgentId),Y=X?Date.now()-X.startedAt:0,j=W.result?.text?W.result.text.split(`
715
- `).length:0;d4(Z.telemetry,{event:"ended",ulid:Q,durationMs:Y,outputLines:j,errorMessage:W.error?String(W.error):void 0,agentId:W.subAgentId,parentId:W.parentAgentId,...O1({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:W.parentAgentId})}),$.subAgentStarts.delete(W.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,W)}}}function Z3($,Z,Q,W){let J=$3($,Z,Q);return N2({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:Z.providerId,modelId:Z.modelId,cwd:Z.cwd,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxIterations:Z.maxIterations,hooks:Z.hooks,extensions:Z.extensions,logger:Z.logger,telemetry:Z.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:Z.providerId,modelId:Z.modelId,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Y=Z.enableTools?w8({cwd:Z.cwd,...e0[u1({mode:Z.mode})],executors:W}):[];if(Z.enableSpawnAgent)Y.push(Z3($,Z,Q,W));return k1(Y)},...J})}import{readFile as XP,stat as YP}from"node:fs/promises";var jP=20480000;async function rG($){let Z=await YP($);if(!Z.isFile())throw Error("Path is not a file");if(Z.size>jP)throw Error("File is too large to read into context.");let Q=await XP($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var iG=5000;function M4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function fP($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$,Q=M4(Z.inputTokens),W=M4(Z.outputTokens),J=M4(Z.cacheReadTokens),X=M4(Z.cacheWriteTokens),Y=M4(Z.totalCost);if(Q===void 0||W===void 0||J===void 0||X===void 0||Y===void 0)return;return{inputTokens:Q,outputTokens:W,cacheReadTokens:J,cacheWriteTokens:X,totalCost:Y}}function UP($,Z){return{inputTokens:Math.max($.inputTokens,Z.inputTokens),outputTokens:Math.max($.outputTokens,Z.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,Z.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,Z.cacheWriteTokens),totalCost:Math.max($.totalCost,Z.totalCost)}}class j${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new $4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new r2;constructor($){let Z=HP();if(Z)AP(Z);let Q=m0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new j9,this.createAgentInstance=$.createAgent??((W)=>new l1(W)),this.defaultCapabilities=T0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new Y$,this.oauthTokenManager=$.oauthTokenManager??new nW({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new aW({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new oW({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,J,X)=>{this.invoke("persistSessionMessages",W,J,X)},enqueuePendingPrompt:(W,J)=>this.pendingPromptsController.enqueue(W,J),invokeBackendOptional:(W,...J)=>this.invokeOptional(W,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!Z?.apiKey)return $;return{...$,config:{...$.config,apiKey:Z.apiKey}}}async startSession($){let Z=$.source??z0.CLI,Q=$0(),W=$.config.sessionId?.trim()??"",J=W||GP(),X=await this.applyInitialOAuthCredentials($),Y=X.initialMessages??[],j=Y.length>0?d5(Y):L0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let H=Q3(V,J),B=Q3(H,`${J}.messages.json`),G=Q3(H,`${J}.json`),K=W$($.config),F=N0.parse({version:1,session_id:J,source:Z,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:X.config.providerId,model:X.config.modelId,cwd:X.config.cwd,workspace_root:K,team_name:X.config.teamName,enable_tools:X.config.enableTools,enable_spawn:X.config.enableSpawnAgent,enable_teams:X.config.enableAgentTeams,prompt:X.prompt?.trim()||void 0,messages_path:B}),A;if(W.length>0&&Y.length>0&&!X.prompt?.trim()){let N=await this.invokeOptionalValue("readSessionManifest",J);if(N)F=N,A={manifestPath:G,messagesPath:N.messages_path||B,manifest:N}}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:j,sessionDir:H,rootMessagesPath:A?.messagesPath??B,manifest:F});this.usageBySession.set(J,j),this.aggregateUsageBySession.set(J,f);let D=T0(this.defaultCapabilities,$.capabilities),U=D?.toolExecutors??this.toolExecutors,T=$.localRuntime,O=T?.extensionContext?.logger??T?.logger,z=T?.extensionContext?.automation,_,M={getSession:(N)=>this.sessions.get(N),subAgentStarts:this.subAgentStarts,onAgentEvent:(N,X0,Y0)=>this.eventBridge.dispatchAgentEvent(N,X0,Y0),invokeBackendOptional:(N,...X0)=>this.invokeOptional(N,...X0)};_=await VG({input:X,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:D,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(N)=>{if(N.name==="plugin_log"){this.eventBridge.handlePluginLog(J,N.payload,O);return}this.eventBridge.handlePluginEvent(J,N,z)},onTeamEvent:(N)=>{this.eventBridge.handleTeamEvent(J,N),_.config.onTeamEvent?.(N)},createSpawnTool:()=>Z3(M,_.config,J,U),createSubAgentLifecycleCallbacks:(N)=>$3(M,N,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(N)=>{await this.persistSessionMetadata(J,()=>N)}});let E=await this.runtimeBuilder.build(_.runtimeBuilderInput),P=_.config,c=_.providerConfig;if(E.teamRuntime&&!P.teamName?.trim())P.teamName=E.teamRuntime.getTeamName();let n=[...E.tools,...P.extraTools??[]],a=E.extensions??_.extensions,t={sessionId:J,providerId:c.providerId,modelId:c.modelId,apiKey:c.apiKey,baseUrl:c.baseUrl,headers:c.headers,knownModels:c.knownModels,providerConfig:c,thinking:P.thinking,reasoningEffort:P.reasoningEffort??c.reasoningEffort,maxTokensPerTurn:P.maxTokensPerTurn,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:EW(P),tools:n,hooks:_.hooks,extensions:a,hookErrorMode:P.hookErrorMode,initialMessages:_.effectiveInput.initialMessages,userFileContentLoader:rG,toolPolicies:_.toolPolicies,requestToolApproval:_.requestToolApproval?async(N)=>{let X0=_.requestToolApproval,Y0=this.sessions.get(J);if(Y0)await this.markTurnPending(Y0);try{if(!X0)return{approved:!1,reason:"Tool approval callback is not configured."};return await X0(N)}finally{let M0=this.sessions.get(J);if(M0?.status==="pending")await this.markTurnRunning(M0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:E.completionPolicy,consumePendingUserMessage:()=>{let N=this.pendingPromptsController.consumeSteer(J);return N?K4(N.prompt,N.mode??P.mode):void 0},logger:E.logger??P.logger,extensionContext:P.extensionContext,onEvent:(N)=>this.eventBridge.dispatchAgentEvent(J,P,N)};t.hooks={...t.hooks,onEvent:async(N)=>{if(await _.hooks?.onEvent?.(N),N.type!=="assistant-message")return;let X0=this.sessions.get(J);if(!X0)return;let Y0=X0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,Y0,P.systemPrompt)}catch(M0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:M0}),r$(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 p0=this.createAgentInstance(t);if(t.onEvent)p0.subscribeEvents(t.onEvent);E.registerLeadAgent?.(p0);let K$=O1({agentId:p0.getAgentId(),conversationId:p0.getConversationId(),teamId:E.teamRuntime?.getTeamId(),teamName:E.teamRuntime?.getTeamName(),teamRole:E.teamRuntime?"lead":void 0});if(HG(P,J,W.length>0,K,K$),K$)f$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...K$});if(E.teamRuntime)jZ(P.telemetry,{ulid:J,teamId:E.teamRuntime.getTeamId(),teamName:E.teamRuntime.getTeamName(),leadAgentId:p0.getAgentId(),restoredFromPersistence:E.teamRestoredFromPersistence===!0});let d={sessionId:J,config:P,sessionMetadata:X.sessionMetadata,...A?{artifacts:A}:{},source:Z,startedAt:A?.manifest.started_at??Q,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Q,pendingPrompt:F.prompt,runtime:E,agent:p0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:Y,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:_.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(J,d),this.emitStatus(J,"running"),Y.length>0&&!A){if(await this.ensureSessionPersisted(d),await this.invoke("persistSessionMessages",d.sessionId,Y,d.config.systemPrompt),!X.prompt?.trim())await this.updateStatus(d,"completed",0)}let X1;try{if(X.prompt?.trim())if(X1=await this.executeTurn(d,{prompt:X.prompt,userImages:X.userImages,userFiles:X.userFiles}),!d.interactive)await this.finalizeSingleRun(d,X1.finishReason);else await this.completeInteractiveTurn(d,X1.finishReason)}catch(N){if(d.interactive&&d.aborting)X1=await this.completeAbortedInteractiveTurn(d);else{r$(d.config.telemetry,{component:"core",operation:"session.start",error:N,severity:"error",handled:!1,context:{sessionId:d.sessionId,providerId:d.config.providerId,modelId:d.config.modelId}});try{await this.failSession(d)}catch(X0){d.config.logger?.error?.("Session failure cleanup threw",{sessionId:d.sessionId,error:X0})}throw N}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:B,result:X1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(Z)=>this.getSession(Z),readMessages:(Z)=>this.readSessionMessages(Z),buildStartInput:(Z,Q)=>{let W=Z.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:Z.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...W?{sessionMetadata:W}:{},initialMessages:Z.initialMessages}},startSession:(Z)=>this.startSession(Z),getStartedSessionId:(Z)=>Z.sessionId,readRestoredSession:(Z)=>this.getSession(Z)})}async runTurn($){let Z=this.getSessionOrThrow($.sessionId),Q=Z.agent.canStartRun(),W=$.delivery??(Z.interactive&&!Q?"queue":void 0);if(Z.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:W,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(Z,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!Z.interactive)await this.finalizeSingleRun(Z,J.finishReason);else await this.completeInteractiveTurn(Z,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(Z.interactive&&Z.aborting)return await this.completeAbortedInteractiveTurn(Z);throw r$(Z.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:Z.sessionId,providerId:Z.config.providerId,modelId:Z.config.modelId}}),await this.failSession(Z),J}}async getAccumulatedUsage($){let Z=I7(this.usageBySession.get($)),Q=I7(this.aggregateUsageBySession.get($));return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,Z){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(Z)}async stopSession($){let Z=this.sessions.get($);if(!Z)return;if(Z.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),Z.interactive&&!j0(Z.status)){await this.releaseSessionRuntime(Z,"session_stop");return}if(Z.interactive&&Z.agent.canStartRun()){await this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:"session_stop",endReason:"stopped"});return}Z.aborting=!0,Z.agent.abort(Error("session_stop")),await this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let Z=[...this.sessions.values()];if(Z.length===0)return;await Promise.allSettled(Z.map((Q)=>Q.interactive&&!j0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let Z=this.sessions.get($);if(Z)return tW(Z);let Q=$.trim();if(!Q)return;let W=await this.getRow(Q);if(W)return t8(W);let J=await this.readManifest(Q);return J?m7(J):void 0}async listSessions($=200){let Q=(await this.listRows($)).map(t8),W=new Set(Q.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(W.has(J.sessionId))continue;Q.unshift(tW(J))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let Z=await this.invoke("deleteSession",$);if(Z.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return Z.deleted}async updateSession($,Z){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:Z.prompt,metadata:Z.metadata,title:Z.title}))?.updated===!0}}async readSessionMessages($){let Z=$.trim();if(!Z)return[];let Q=await this.getRow(Z);if(Q?.messagesPath)return n1(Q.messagesPath);let W=await this.readManifest(Z);return n1(W?.messages_path)}async dispatchHookEvent($){await HH($,{queueSpawnRequest:(Z)=>this.invokeOptional("queueSpawnRequest",Z),upsertSubagentSessionFromHook:(Z)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",Z),appendSubagentHookAudit:(Z,Q)=>this.invokeOptional("appendSubagentHookAudit",Z,Q),applySubagentStatus:(Z,Q)=>this.invokeOptional("applySubagentStatus",Z,Q)})}subscribe($,Z){return this.events.subscribe($,Z)}async updateSessionModel($,Z){let Q=this.getSessionOrThrow($);Q.config.modelId=Z,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:Z}),Q.agent.updateConnection({modelId:Z})}handlePluginEvent($,Z,Q){return this.eventBridge.handlePluginEvent($,Z,Q)}async executeTurn($,Z){let Q=await this.prepareTurnInput($,Z),W=Q.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=W;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let J=await this.executeAgentTurn($,W,Q.userImages,Q.userFiles);while(KW($,J.finishReason)){let X=await FW($);if(X.length===0)break;let Y=AW($,X);J=await this.executeAgentTurn($,Y)}return J}async completeInteractiveTurn($,Z){if(G4($))return;$.lastInteractiveTurnFinishReason=Z,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let Z=$.lastInteractiveTurnFinishReason;if(!Z)return"cancelled";switch(Z){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return Z}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let Z=new Date,Q=$.agent.getMessages(),W=L0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:Z,endedAt:Z,durationMs:0}}async executeAgentTurn($,Z,Q,W){let J=$.started||$.agent.getMessages().length>0,X=$.persistedMessages??$.agent.getMessages(),Y=this.usageBySession.get($.sessionId)??L0(),j=this.aggregateUsageBySession.get($.sessionId)??Y;$.turnUsageBaseline=Y,$.turnAggregateUsageBaseline=j,$.turnPrimaryUsage=L0(),$.turnUsageByAgent=new Map,ZZ($.config.telemetry,$.sessionId,$.config.mode),Z8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(Z,Q,W):()=>$.agent.run(Z,Q,W),H=await this.runWithAuthRetry($,V,X);$.started=!0;let B=z5(H.messages,H,X);$.persistedMessages=B;let G=u5($.turnUsageByAgent?.values()??[]),K=f0(Y,H.usage),F=f0(f0(L0(),H.usage),G),A=f0(j,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(L)=>({...L??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,B,$.config.systemPrompt),this.observeTaskCompletionTool($,H),H}catch(V){throw r$($.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($,Z){if($.submitAndExitObserved)return;if(!Z.toolCalls.some((W)=>W.name===D0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,c4($.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($,Z){let Q=W$($.config),W=FP(Z.prompt).trim();if(!W)return{prompt:"",userImages:Z.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,Z.userFiles)};let J=await d6(W,Q);BG($.config.telemetry,J);let X=K4(J.prompt,Z.mode??$.config.mode),Y=this.resolveAbsoluteFilePaths($.config.cwd,Z.userFiles),j=this.resolveAbsoluteFilePaths(Q,J.matchedFiles),V=Array.from(new Set([...Y,...j]));return{prompt:X,userImages:Z.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let Z=W$($.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:Z,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 markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,Z){let Q=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,J=Z(W?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Q.sessionMetadata=J,Q.artifacts.manifest.metadata=J}async finalizeSingleRun($,Z){if(G4($))return;let Q=Z==="aborted"||$.aborting,W=Z==="error";await this.shutdownSession($,{status:Q?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:Z})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,Z){if(Z.status==="completed"&&!$.submitAndExitObserved)c4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});g5($);let Q=[],W=(J,X)=>{Q.push(X),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:X,severity:"warn"}),r$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:X,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:Z.status,shutdownReason:Z.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,Z.status,Z.exitCode)}catch(J){W("update_status",J)}try{await $.agent.shutdown(Z.shutdownReason)}catch(J){W("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(Z.shutdownReason))}catch(J){W("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){W("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:Z.endReason,ts:Date.now()}}),Q.length>0&&Z.status==="failed")throw Q[0]}async releaseSessionRuntime($,Z){let Q=[],W=(J,X)=>{Q.push(X),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:X,severity:"warn"}),r$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:X,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:Z,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(Z)}catch(J){W("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(Z))}catch(J){W("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){W("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,Z,Q){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,Z,Q);if(!W.updated)return;let J=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(J.status=Z,j0(Z))delete J.ended_at,J.exit_code=null;else J.ended_at=W.endedAt??$0(),J.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=J,$.status=Z,$.updatedAt=W.endedAt??$0(),$.endedAt=j0(Z)?null:J.ended_at,$.exitCode=J.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,J),this.emitStatus($.sessionId,Z)}async runWithAuthRetry($,Z,Q){try{return await Z()}catch(W){if(!J8($.config.providerId)||!KP(W))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),Z()}}async syncOAuthCredentials($,Z){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Z?.forceRefresh})}catch(W){if(W instanceof V9)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let Z=this.sessions.get($);if(!Z){let Q=new C$($);throw r$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return Z}resolveAbsoluteFilePaths($,Z){if(!Z||Z.length===0)return[];let Q=Z.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>BP(W)?W:W3($,W));return Array.from(new Set(Q))}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 Z=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=f0($.initialUsage,Z);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,Z,Q){let W=W3(Z),J=`${Q}.messages.json`,X;try{X=VP($)}catch{return L0()}let Y=L0();for(let j of X){if(!j.endsWith(".messages.json"))continue;if(j===J)continue;let V=W3($,j);if(V===W)continue;let H=await n1(V);if(H.length===0)continue;Y=f0(Y,d5(H))}return Y}withPersistedAggregateUsageFloor($,Z){let Q=fP(Z.metadata?.aggregateUsage);if(Q)return UP($,Q);let W=Z.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,Z){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:Z}})}async emitSessionSnapshot($){let Z=await this.getSession($);if(!Z)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:t1({session:Z,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($)),iG))}async getRow($){let Z=$.trim();if(!Z)return;return(await this.listRows(iG)).find((W)=>W.sessionId===Z)}async readManifest($){let Z=$.trim();if(!Z)return;return await this.invokeOptionalValue("readSessionManifest",Z)}invoke($,...Z){return dG(this.sessionService,$,...Z)}invokeOptional($,...Z){return lG(this.sessionService,$,...Z)}invokeOptionalValue($,...Z){return pG(this.sessionService,$,...Z)}}function DP($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let Z=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(Z==="local"||Z==="hub"||Z==="remote")return Z;return"auto"}var R4,E4;function LP($,Z){if($!=="auto"&&$!=="hub")return;if(Z.hub?.endpoint?.trim())return;bH(Z.hub?.workspaceRoot?.trim()||Z.hub?.cwd?.trim()||process.cwd())}async function _P($){await $.reconcileDeadSessions?.().catch(()=>{})}function sG($){try{let Z=new Z$;return Z.init(),new Q$(Z,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(Z){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),aG($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:Z,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new LW(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function nG($,Z,Q){return new j$({sessionService:Q??$.sessionService??sG($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:Z,fetch:$.fetch})}async function zP($){if(R4)return R4;if(E4)return await E4;return E4=(async()=>{return R4=sG($),await _P(R4),R4})().finally(()=>{E4=void 0}),await E4}async function B9($){let Z=m0($.distinctId);$.telemetry?.setDistinctId(Z);let Q=DP($);if(LP(Q,$),Q==="remote"){let W=$.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:W}),new w5({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let W=$.hub?.endpoint?.trim(),J=W||await X4({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:W||void 0}),new c$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let W=await a7({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(W){$.logger?.log("Using discovered local hub runtime host",{url:W});let J=new c$({url:W,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(X){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:X}),aG($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:X,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),nG($,Z)}return nG($,Z)}import{execFile as TP}from"node:child_process";import*as tG from"node:fs/promises";import*as a2 from"node:path";import{promisify as OP}from"node:util";var qP=OP(TP),MP=52428800;async function G9($,Z){let{stdout:Q}=await qP("git",["-C",$,...Z],{windowsHide:!0,maxBuffer:MP,encoding:"utf8"});return Q}function oG($){return $.split("\x00").filter(Boolean)}function eG($,Z){let Q=a2.resolve($,Z),W=a2.relative($,Q);if(W.startsWith("..")||a2.isAbsolute(W))throw Error(`Checkpoint diff path escapes workspace: ${Z}`);return Q}async function RP($,Z,Q){try{return await G9($,["show",`${Z}:${Q}`])}catch{return""}}async function EP($,Z){try{return await tG.readFile(eG($,Z),"utf8")}catch{return""}}async function NP($,Z){await G9($,["cat-file","-e",`${Z.ref}^{tree}`]);let[Q,W]=await Promise.all([G9($,["diff","--name-only","-z",Z.ref,"--"]),G9($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...oG(Q),...oG(W)])].sort((X,Y)=>X.localeCompare(Y))}function $K($){let Z=$.checkpointRunCount;if(!Number.isInteger(Z)||Z<1)throw Error("checkpointRunCount must be a positive integer");let Q=W9(O4($.session),Z);if(!Q)throw Error(`No checkpoint found at or before run ${Z} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Q,cwd:W}}async function ZK($,Z){let Q=await NP($,Z);return(await Promise.all(Q.map(async(J)=>{let[X,Y]=await Promise.all([RP($,Z.ref,J),EP($,J)]);return{filePath:eG($,J),leftContent:X,rightContent:Y}}))).filter((J)=>J.leftContent!==J.rightContent)}async function J3($){let Z=$K($),Q=await ZK(Z.cwd,Z.checkpoint);return{...Z,diffs:Q}}import{existsSync as wP,mkdirSync as CP,readFileSync as PP,writeFileSync as SP}from"node:fs";import{dirname as bP}from"node:path";import{FEATURE_FLAGS as QK,FeatureFlagDefaultValue as X3}from"@cline/shared";var yP=3600000,hP=604800000,WK=1;class N4{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??yP,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??hP,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 Z=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===Z)return}let W=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:Z||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:QK.length>0?QK:void 0,context:{...this.context,userId:Z}});if(this.cacheInfo.userId!==Z)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==Z)return;throw this.cacheInfo=W.updateTime?W:{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((Z)=>this.isFeatureFlagPayload(Z));if(typeof $==="object")return Object.values($).every((Z)=>this.isFeatureFlagPayload(Z));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=Object.entries($).filter(([,W])=>this.isFeatureFlagPayload(W));if(Z.length===0)return;let Q={};for(let[W,J]of Z)Q[W]=J;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!wP(this.cacheFilePath))return;let $=JSON.parse(PP(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let Z=$;if(Z.version!==WK||typeof Z.updatedAt!=="number"||!Number.isFinite(Z.updatedAt)||Date.now()-Z.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:Z.updatedAt,userId:Z.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(Z.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(Z.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;CP(bP(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),Z={version:WK,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};SP(this.cacheFilePath,`${JSON.stringify(Z,null,2)}
716
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let Z=new Map;for(let Q of this.getReturnedFlagKeys($)){let W=this.getFeatureFlag(Q);Z.set(Q,W??!1)}this.cache=Z}getFeatureFlag($){try{let Z=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],W=Z??Q??X3[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==W)this.telemetry?.capture({event:I.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return W}catch(Z){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:Z}),X3[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??X3[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,Z){if(process.env.IS_TEST==="true")this.cache.set($,Z)}async dispose(){await this.provider.dispose()}}class w4{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}g2();class Y3{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,Z,Q,W,J,X,Y,j,V,H){this.clientName=Z,this.runtimeAddress=Q,this.host=$,this.prepare=W,this.capabilities=J,this.logger=X,this.telemetry=Y,this.distinctId=j,this.featureFlags=V,this.settings=SV($),this.pendingPrompts=bV($),this.automation=new gZ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=H?new a8({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:GX(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:KX({host:$,getExtensionContext:()=>Y6({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:H.dbPath,logger:H.logger,pollIntervalMs:H.pollIntervalMs,claimLeaseSeconds:H.claimLeaseSeconds,globalMaxConcurrency:H.globalMaxConcurrency,watcherDebounceMs:H.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((B)=>{if(B.type!=="ended")return;this.disposeSessionBootstrap(B.payload.sessionId)})}static async create($={}){let Z=m0($.distinctId),Q=T0($.capabilities),W={...$,capabilities:Q,distinctId:Z},J=await B9(W),X=BX($.automation),Y=$.featureFlags||new N4({provider:new w4,telemetry:$.telemetry,logger:$.logger,context:{distinctId:Z,clientName:$.clientName}}),j=new Y3(J,$.clientName,J.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,Z,Y,X?{...X,logger:$.logger}:void 0);if(X&&X.autoStart!==!1)await j.automation.start();return j}async disposeSessionBootstrap($){let Z=this.activeSessionBootstraps.get($);if(!Z)return;this.activeSessionBootstraps.delete($),await Promise.resolve(Z.dispose?.())}async start($){let Z=yV($),Q=await this.prepare?.(Z);try{let W=Q?await Q.applyToStartSessionInput(Z):Z,J=await this.host.startSession(V7(W,{defaultCapabilities:this.capabilities,withExtensionContext:(X)=>Y6({automationService:this.automationService,automation:this.automation,context:X,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Q);else await Promise.resolve(Q.dispose?.());return hV({input:W,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(W){throw await Promise.resolve(Q?.dispose?.()),W}}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 Z=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(Z.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await v7(this.host,$);list=async($=200,Z={})=>await this.listHistory({...Z,limit:$});delete=async($)=>{let Z=await this.host.deleteSession($);if(Z)await this.disposeSessionBootstrap($);return Z};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let Z=$.start?V7($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>Y6({automationService:this.automationService,automation:this.automation,context:Q,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:Z})}async compareCheckpoint($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=await this.host.getSession(Z);if(!Q)throw Error(`Session ${Z} not found`);return J3({session:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,Z){return this.host.subscribe($,Z)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as XK,HookEventPayloadSchema as YK,parseHookEventPayload as F9,resolveHookSessionContext as cP}from"@cline/shared";import{z as i$}from"zod";import{spawn as kP}from"node:child_process";import{augmentNodeCommandForDebug as IP,withResolvedClineBuildEnv as xP}from"@cline/shared";function gP($){let Z=$.trim();if(!Z)return{};let W=Z.split(`
717
- `).map((X)=>X.trim()).filter(Boolean).filter((X)=>X.startsWith("HOOK_CONTROL\t")).map((X)=>X.slice(13)),J=W.length>0?W[W.length-1]:Z;try{return{parsedJson:JSON.parse(J)}}catch(X){return{parseError:X instanceof Error?X.message:"Failed to parse subprocess stdout JSON"}}}function mP($,Z){let Q=$ instanceof Error?$:Error(String($)),W=Q,J=Z.join(" ");if(W.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}": ${Q.message}`)}async function vP($,Z){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,J)=>{let X=(Y)=>{Q.off("error",X);let j=Y.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}J(Y)};Q.once("error",X),Q.end(Z,(Y)=>{if(Q.off("error",X),Y){let j=Y.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}J(Y);return}W()})})}async function K9($,Z){let Q=IP(Z.command,{env:Z.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!Z.detached,J=kP(Q[0],Q.slice(1),{cwd:Z.cwd,env:xP(Z.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W,windowsHide:!0}),X=new Promise((K)=>{J.once("spawn",()=>{try{Z.onSpawn?.({command:Q,pid:J.pid??void 0,detached:W})}catch{}K()})}),Y=new Promise((K,F)=>{J.once("error",(A)=>{F(mP(A,Q))})});if(await vP(J,JSON.stringify($)),W){await Promise.race([X,Y]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",V="",H=!1,B;J.stdout.on("data",(K)=>{j+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((Z.timeoutMs??0)>0)B=setTimeout(()=>{H=!0,J.kill("SIGKILL")},Z.timeoutMs);J.once("close",(F)=>{if(B)clearTimeout(B);let{parsedJson:A,parseError:L}=gP(j);K({exitCode:F,stdout:j,stderr:V,parsedJson:A,parseError:L,timedOut:H})})});return await Promise.race([G,Y])}var uP=i$.object({contextModification:i$.string().optional(),cancel:i$.boolean().optional(),review:i$.boolean().optional(),errorMessage:i$.string().optional(),context:i$.string().optional(),overrideInput:i$.unknown().optional()}).passthrough();var dP=["agent","hook"];async function A9($,Z={}){let Q=Z.command??dP;return await K9($,{command:Q,cwd:Z.cwd,env:Z.env,detached:Z.detached,timeoutMs:Z.timeoutMs,onSpawn:Z.onSpawn})}function jK($){return $ instanceof Error?$:Error(String($))}function lP($){if(!$||typeof $!=="object")return;let Z=uP.safeParse($);if(!Z.success)return;let Q=Z.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let J=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:J,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function JK($){if(!$||typeof $!=="object")return{};let Z={};for(let[Q,W]of Object.entries($))if(typeof W==="string")Z[Q]=W;else Z[Q]=JSON.stringify(W);return Z}function q1($,Z,Q){let W=Q.env??process.env,J=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",X=Q.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:Z.conversationId,sessionContext:cP(Q.sessionContext,{hookName:$,conversationId:Z.conversationId,agentId:Z.agentId,parentAgentId:Z.parentAgentId}),workspaceRoots:X?[X]:[],workspaceInfo:Q.workspaceInfo,userId:J,agent_id:Z.agentId,parent_agent_id:Z.parentAgentId}}function pP($){return{name:$.name,message:$.message,stack:$.stack}}function rP($){let Z=String($??"").toLowerCase();return Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt")}function iP($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function nP($){return $.filter((Z)=>Z.type==="text"&&typeof Z.text==="string").map((Z)=>Z.text).join("")}function aP($){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 sP($){if(!$)return;let Z={};if($.cancel===!0)Z.stop=!0;if($.overrideInput!==void 0)Z.input=$.overrideInput;return Object.keys(Z).length>0?Z:void 0}async function n$($,Z){try{let Q=await A9($,{command:Z.command,cwd:Z.cwd,env:Z.env,detached:!0,onSpawn:Z.onSpawn});Z.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){Z.onDispatchError?.(jK(Q),$)}}function VK($={}){return{hooks:{beforeRun:async(j)=>{let V=iP(j);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let B={...q1("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await n$(B,$)}else{let B={...q1("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await n$(B,$)}return},beforeTool:async(j)=>{let V={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},H={...q1("tool_call",V,$),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:JK(j.input)}};try{let B=await A9(H,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:H,result:B,detached:!1}),B?.timedOut)throw Error("tool_call hook command timed out");if(B?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${B.parseError}`);return sP(lP(B?.parsedJson))}catch(B){$.onDispatchError?.(jK(B),H);return}},afterTool:async(j)=>{let V=aP(j),H={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},B={...q1("tool_result",H,$),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:JK(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await n$(B,$);return},afterRun:async({snapshot:j,result:V})=>{let H={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(V.status==="completed"){let K={...q1("agent_end",H,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await n$(K,$);return}let B=V.status==="aborted"||rP(V.error?.message)?"agent_abort":"agent_error",G=B==="agent_error"?{...q1(B,H,$),hookName:B,iteration:V.iterations,error:pP(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...q1(B,H,$),hookName:B,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await n$(G,$)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let V={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},H={...q1("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:nP(j.message.content),attachments:[]}};await n$(H,$)}},shutdown:async({agentId:j,conversationId:V,parentAgentId:H,reason:B})=>{let G={...q1("session_shutdown",{agentId:j,conversationId:V,parentAgentId:H},$),hookName:"session_shutdown",reason:B};await n$(G,$)}}}import{createSessionId as oP}from"@cline/shared";function c0($,Z){return{version:$.version,requestId:$.requestId,ok:!0,payload:Z}}function HK($,Z,Q){return{version:$.version,requestId:$.requestId??oP("hubreq_"),ok:!1,error:{code:Z,message:Q}}}class f9{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return c0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return c0($,{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 c0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return c0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return c0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return c0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return c0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return c0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return c0($,{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 c0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return c0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return c0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return HK($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(Z){return HK($,"schedule_command_failed",Z instanceof Error?Z.message:String(Z))}}toCreateInput($){let Z=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:Z}}toUpdateInput($){let Z=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:Z}}}function D9($){return $?new Date($).getTime():void 0}function tP($){let Z=$.metadata?{...$.metadata}:void 0;if(Z)delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions;return Z}function U9($){let Z=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof Z?.__hubScheduleCwd==="string"?Z.__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:D9($.nextRunAt),lastRunAt:D9($.lastRunAt),createdBy:typeof Z?.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:Z?.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0,metadata:tP($)}}function eP($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function j3($,Z){return{executionId:$.runId,scheduleId:Z,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:D9($.startedAt),endedAt:D9($.completedAt),status:eP($.status),errorMessage:$.error}}class L9{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new n8({dbPath:$.dbPath}),this.materializer=new d8({store:this.store}),this.runner=new l8({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(_7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return U9(this.store.createHubSchedule($))}getSchedule($){let Z=this.store.getHubSchedule($);return Z?U9(Z):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((Z)=>U9(Z))}updateSchedule($,Z){if(Z.cronPattern!==void 0)_7(Z.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let W=Z.workspaceRoot!==void 0?Z.workspaceRoot.trim():Q.workspaceRoot;if((Z.enabled??Q.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let X=this.store.updateHubSchedule($,{...Z,scheduleId:$});return X?U9(X):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let Z=this.store.enqueueHubScheduleRun($,"manual");if(!Z)return;await this.runner.tick();let Q=this.store.getRun(Z.runId)??Z;return j3(Q,$)}triggerScheduleNowDetached($){let Z=this.store.enqueueHubScheduleRun($,"manual");if(!Z)return;return this.runner.tick().catch(()=>{return}),j3(Z,$)}listScheduleExecutions($){let Z=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:Z?.specId,limit:$.limit};return this.store.listRuns(Q).map((J)=>{let X=Z??this.store.getSpec(J.specId);if(!X||X.source!=="hub-schedule")return;return j3(J,X.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let Z=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(Z.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,W=0,J=0,X;for(let Y of Z){if(Y.status==="success"||Y.status==="completed")Q+=1;if(!X&&Y.status!=="success"&&Y.status!=="completed")X=Y;if(Y.startedAt&&Y.endedAt)J+=Y.endedAt-Y.startedAt,W+=1}return{totalRuns:Z.length,successRate:Q/Z.length,avgDurationSeconds:W>0?J/W/1000:0,lastFailure:X}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let Z=this.store.getSpec($.specId);if(!Z||Z.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:Z.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:Z.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+Z.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let Z={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(Z).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,W)=>String(Q.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:W})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:W}))}}O9();import{resolveClineBuildEnv as OS}from"@cline/shared";function qS($,Z){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${Z} (${Q} event before socket open).`:`Failed to connect to hub at ${Z}.`)}var MS="cline-hub-auth.";function RS($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function ES($,Z){let Q=new URL($),W=new URL(Z);return Q.search="",Q.hash="",W.search="",W.hash="",Q.toString()===W.toString()}function KK(){return OS()==="production"?s1():L1()}async function NS($){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;let Q=KK(),W=await A0(Q.discoveryPath);if(W?.url&&ES($.toString(),W.url))return W.authToken;return}async function wS($={}){let Z=a1($);if(!RS($)){let Q=KK(),W=await A0(Q.discoveryPath);if(W?.url)return W.url}return D1(Z.host,Z.port,Z.pathname)}async function FK($){return await new Promise((Z,Q)=>{(async()=>{let W=new URL($),J=await NS(W);W.hash="";let X=new WebSocket(W.toString(),J?[`${MS}${J}`]:void 0),Y=new Map,j=0;X.addEventListener("open",()=>{Z({send(V){let H=V.requestId??`hub-client-${++j}`;return new Promise((B,G)=>{Y.set(H,{resolve:B,reject:G});let K={kind:"command",envelope:{...V,requestId:H}};X.send(JSON.stringify(K))})},close(){X.close()}})}),X.addEventListener("message",(V)=>{let H=JSON.parse(String(V.data));if(H.kind==="reply"&&H.envelope.requestId){let B=Y.get(H.envelope.requestId);if(B)Y.delete(H.envelope.requestId),B.resolve(H.envelope)}}),X.addEventListener("close",()=>{for(let V of Y.values())V.reject(Error("Hub connection closed"));Y.clear()}),X.addEventListener("error",(V)=>{Q(qS(V,$))})})().catch(Q)})}async function ms($){try{return(await FK($)).close(),!0}catch{return!1}}async function vs($,Z){let Q=await wS($),W=await FK(Q);try{return await W.send({version:Z.version??"v1",clientId:Z.clientId??"hub-client",...Z})}finally{W.close()}}function G3($){return $?JSON.parse(JSON.stringify($)):{}}function q9($){let Z=$?.session&&typeof $.session==="object"?$.session:void 0;if(!Z)return;let Q=Z.metadata&&typeof Z.metadata==="object"?G3(Z.metadata):void 0;return{sessionId:typeof Z.sessionId==="string"?Z.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function AK($,Z){return $.error?.message??`hub command failed: ${Z}`}function CS($){let Z=G3($);if(typeof Z.error==="string"&&Z.error.trim())return{...Z,error:Z.error.trim()};let Q=Z.result&&typeof Z.result==="object"?Z.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...Z,error:Q.text.trim()};let W=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...Z,error:W.message.trim()};return Z}function fK($){let Z=$?.sessionId;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}function PS($){let Z=$?.checkpoint;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("hub checkpoint restore returned no checkpoint");let Q=Z;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function SS($){let Z=G3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||fK(Z)||"",eventType:"schedule.execution.completed",payload:Z};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||fK(Z)||"",eventType:"schedule.execution.failed",payload:Z};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:Z};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:Z};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:Z};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:Z};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:Z};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:Z};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:Z};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:Z};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:CS($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:Z};default:return}}class bS{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new _1({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 Z=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=q9(Z.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,Z,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:Z.prompt,mode:Z.config.mode,attachments:Z.attachments,delivery:Z.delivery,timeoutSeconds:Z.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let Z;try{Z=await this.client.command("session.get",void 0,$)}catch(Q){if(P$(Q))return;throw Q}return q9(Z.payload)}async readMessages($){let Z=$.trim();if(!Z)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:Z},Z);if(!Q.ok)throw Error(AK(Q,"session.messages"));let W=Q.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,J=await this.client.command("session.restore",{sessionId:Z,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},Z);if(!J.ok)throw Error(AK(J,"session.restore"));let X=q9(J.payload);if(Q&&!X?.sessionId)throw Error("hub checkpoint restore returned no session id");let Y=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,j=PS(J.payload);return{sessionId:X?.sessionId,startResult:X?.sessionId?{sessionId:X.sessionId,manifestPath:"",messagesPath:X.messagesPath??""}:void 0,...Y?{messages:Y}:{},checkpoint:j}}async listSessions($){await this.ensureMetadataApplied();let Z=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(Z.payload?.sessions)?Z.payload?.sessions:[]).map((W)=>q9({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,Z=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:Z})).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($,Z){let Q=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),W=this.client.subscribe((J)=>{let X=SS(J);if(!X)return;if(Q.size>0&&!Q.has(X.sessionId))return;Z.onEvent?.(X)});return this.ensureMetadataApplied().catch((J)=>{Z.onError?.(J instanceof Error?J:Error(String(J)))}),W}streamTeamProgress($,Z){let Q=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;Z.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{Z.onError?.(W instanceof Error?W:Error(String(W)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list");return Array.isArray(Z.payload?.schedules)?Z.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,Z){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...Z})).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($,Z){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:Z});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(Z.payload?.upcoming)?Z.payload?.upcoming:[]}}class yS{client;constructor($){this.client=new _1({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 Z=await this.client.command("session.list",{limit:$});return Array.isArray(Z.payload?.sessions)?Z.payload.sessions:[]}subscribeUI($){return this.client.subscribe((Z)=>{switch(Z.event){case"ui.notify":$.onNotify?.(Z.payload);break;case"ui.show_window":$.onShowWindow?.(Z.payload);break;case"hub.client.registered":$.onClientRegistered?.(Z.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(Z.payload??{});break;case"session.created":$.onSessionCreated?.(Z.payload??{});break;case"session.updated":$.onSessionUpdated?.(Z.payload??{});break;case"session.detached":$.onSessionDetached?.(Z.payload??{});break}})}}import{normalizeProviderId as hS}from"@cline/llms";function kS($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((Z)=>({name:Z.name,input:Z.input,output:Z.output,error:Z.error,durationMs:Z.durationMs}))}}function IS($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function ts($={}){let Z=new j$({sessionService:new Q$(new Z$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let W=(Q.cwd?.trim()||Q.workspaceRoot).trim(),J=await Z.startSession({source:Q.source?.trim()||z0.CLI,interactive:!1,config:{providerId:hS(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:W,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:IS(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Q,W){let J=await Z.runTurn({sessionId:Q,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((X)=>X.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:kS(J)}},async abortSession(Q){return await Z.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}import{resolveClineBuildEnv as UF}from"@cline/shared";function xS($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
718
- `).trim()||void 0}var UK=120,K3="...";function F3($){let Z=$.trim();if(!Z)return"";if(Buffer.byteLength(Z,"utf8")<=UK)return Z;let Q=UK-Buffer.byteLength(K3,"utf8");if(Q<=0)return K3;let W="";for(let J of Z){if(Buffer.byteLength(W+J,"utf8")>Q)break;W+=J}return`${W}${K3}`}async function DK($){let Z=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await n1(Q)].reverse().find((V)=>V.role==="assistant"),X=J?xS(J.content):void 0,Y=$?.workspaceRoot?.trim()||"workspace",j=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():Y;return{title:`Task completed (${Z})`,body:F3(X&&X.length>0?X:j.length>0?j:Y),severity:"info"}}import{captureSdkError as w9,createSessionId as kb}from"@cline/shared";import{createSessionId as cS}from"@cline/shared";import{createSessionId as vS}from"@cline/shared";function gS($){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 mS($){let Z=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())Z.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())Z.parentAgentId=$.parentAgentId;if($.agentId?.trim())Z.agentId=$.agentId;if($.conversationId?.trim())Z.conversationId=$.conversationId;if($.messagesPath?.trim())Z.messagesPath=$.messagesPath;if($.prompt?.trim())Z.prompt=$.prompt;if($.provider?.trim())Z.provider=$.provider;if($.model?.trim())Z.model=$.model;if($.source?.trim())Z.source=$.source;if(typeof $.pid==="number")Z.pid=$.pid;return Object.keys(Z).length>0?Z:void 0}function M9($,Z,Q,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:Z?.createdByClientId??"hub",status:gS($.status),participants:Z?[...Z.participants.values()]:[],metadata:mS($),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,...Q?{usage:{...Q}}:{},...W?{aggregateUsage:{...W}}:{}}}function g($,Z){return{version:$.version,requestId:$.requestId,ok:!0,...Z!==void 0?{payload:Z}:{}}}function h($,Z,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:Z,message:Q}}}function R9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function C0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function s$($,Z,Q){return{version:"v1",event:$,eventId:vS("hevt_"),sessionId:Q,timestamp:Date.now(),payload:Z}}async function u0($,Z){let Q=await $.sessionHost.getSession(Z);if(!Q)return;let W=await $.sessionHost.getAccumulatedUsage?.(Z);return M9(Q,$.sessionState.get(Z),W?.usage,W?.aggregateUsage)}async function d0($,Z){let Q=await $.sessionHost.getSession(Z);if(!Q)return;let[W,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(Z):[],$.sessionHost.getAccumulatedUsage?.(Z)]);return t1({session:Q,messages:W,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function E9($,Z,Q,W,J={}){let X=$.sessionState.get(Z);if(X){if(J.interactive!==void 0)X.interactive=J.interactive;if(!X.participants.has(Q))X.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:W});return X}let Y={createdByClientId:Q,interactive:J.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(Z,Y),Y}async function A3($,Z){let Q=cS("approval_"),W=Z.sessionId;if($.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((X)=>{$.pendingApprovals.set(Q,{sessionId:W,resolve:X}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:Z.sessionId,agentId:Z.agentId,conversationId:Z.conversationId,iteration:Z.iteration,toolCallId:Z.toolCallId,toolName:Z.toolName,inputJson:JSON.stringify(Z.input??null),policy:Z.policy},W))})}function f3($,Z,Q){let W=$.pendingApprovals.get(Z);if(!W)return;return $.pendingApprovals.delete(Z),W.resolve(Q),{sessionId:W.sessionId}}function U3($,Z,Q){let W=0;for(let[J,X]of[...$.pendingApprovals.entries()]){if(!Z({approvalId:J,sessionId:X.sessionId}))continue;$.pendingApprovals.delete(J),X.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Q},X.sessionId)),W+=1}return W}async function LK($,Z){let Q=typeof Z.payload?.approvalId==="string"?Z.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return h(Z,"approval_not_found",`Unknown approval: ${Q}`);let J=typeof Z.payload?.reason==="string"?Z.payload.reason:Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)&&typeof Z.payload.payload.reason==="string"?Z.payload.payload.reason:void 0,X=Z.payload?.approved===!0,Y=f3($,Q,{approved:X,reason:J});if(!Y)return h(Z,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:X,reason:J},Y.sessionId)),g(Z,{approvalId:Q,approved:X})}import{createSessionId as lS}from"@cline/shared";function uS($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var _K={debug:10,info:20,warn:30,error:40,silent:50};function dS(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function m($,Z,Q={}){if(_K[$]<_K[dS()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:Z,...Object.fromEntries(Object.entries(Q).map(([J,X])=>[J,uS(X)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function D3($,Z){let Q=Z instanceof Error?Z.stack||Z.message:String(Z);m("error",$,{error:Q})}async function zK($,Z,Q,W,J,X){let Y=lS("capreq_"),j=performance.now();return m("info","capability.request.start",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J}),await new Promise((V,H)=>{$.pendingCapabilityRequests.set(Y,{sessionId:Z,targetClientId:J,capabilityName:Q,onProgress:X,resolve:(B)=>{if(m(B.ok?"info":"warn","capability.request.end",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J,ok:B.ok,error:B.error,durationMs:Math.round(performance.now()-j)}),!B.ok){H(Error(B.error||`Capability ${Q} was rejected by ${J}.`));return}V(B.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:Y,targetClientId:J,capabilityName:Q,payload:W},Z)),m("info","capability.request.published",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J})})}function TK($,Z){let Q=typeof Z.payload?.requestId==="string"?Z.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(Q);if(!W)return h(Z,"capability_not_found",`Unknown capability request: ${Q}`);if((Z.clientId?.trim()||"")!==W.targetClientId)return h(Z,"capability_wrong_client",`Capability request ${Q} is owned by ${W.targetClientId}`);if(Z.sessionId?.trim()&&Z.sessionId.trim()!==W.sessionId)return h(Z,"capability_wrong_session",`Capability request ${Q} belongs to session ${W.sessionId}`);let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:{};return W.onProgress?.(X),g(Z,{requestId:Q})}function V$($,Z,Q){let W=0;for(let[J,X]of[...$.pendingCapabilityRequests.entries()]){if(!Z({requestId:J,...X}))continue;$.pendingCapabilityRequests.delete(J),m("warn","capability.request.cancelled",{requestId:J,sessionId:X.sessionId,capabilityName:X.capabilityName,targetClientId:X.targetClientId,reason:Q}),X.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:X.capabilityName,targetClientId:X.targetClientId,ok:!1,cancelled:!0,error:Q},X.sessionId)),W+=1}return W}async function OK($,Z){let Q=typeof Z.payload?.sessionId==="string"?Z.payload.sessionId.trim():Z.sessionId?.trim()||"",W=typeof Z.payload?.capabilityName==="string"?Z.payload.capabilityName.trim():"",J=typeof Z.payload?.targetClientId==="string"?Z.payload.targetClientId.trim():"";if(!Q||!W||!J)return h(Z,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:{},Y=await $.requestCapability(Q,W,X,J);return g(Z,Y)}catch(X){return h(Z,"capability_request_failed",X instanceof Error?X.message:String(X))}}function qK($,Z){let Q=typeof Z.payload?.requestId==="string"?Z.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(Q);if(!W)return h(Z,"capability_not_found",`Unknown capability request: ${Q}`);let J=Z.clientId?.trim()||"";if(J!==W.targetClientId)return h(Z,"capability_wrong_client",`Capability request ${Q} is owned by ${W.targetClientId}`);if(Z.sessionId?.trim()&&Z.sessionId.trim()!==W.sessionId)return h(Z,"capability_wrong_session",`Capability request ${Q} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(Q);let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:void 0,Y=typeof Z.payload?.error==="string"?Z.payload.error:void 0,j=Z.payload?.ok===!0;return m(j?"info":"warn","capability.respond",{requestId:Q,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:J,ok:j,error:Y}),W.resolve({ok:j,payload:X,error:Y}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:J,ok:j,payload:X,error:Y},W.sessionId)),g(Z,{requestId:Q,ok:j})}import{createSessionId as pS}from"@cline/shared";function MK($,Z){let Q=Z.payload,W=Q?.clientId?.trim()||Z.clientId?.trim()||pS("client_");return $.clients.set(W,{clientId:W,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),g(Z,{clientId:W})}function RK($,Z){let Q=Z.clientId?.trim(),W=Q?$.clients.get(Q):void 0;if(!Q||!W)return h(Z,"client_not_found","Client is not registered with this hub.");let J=R9(Z.payload?.metadata);if(W.lastSeenAt=Date.now(),J)W.metadata=JSON.parse(JSON.stringify(J));return g(Z)}function EK($,Z,Q){let W=Z.clientId?.trim();if(W)$.clients.delete(W),Q(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return g(Z)}function NK($,Z){return g(Z,{clients:[...$.clients.values()]})}G0();import{existsSync as PK,mkdirSync as rS,readdirSync as iS,readFileSync as nS,rmSync as aS,writeFileSync as sS}from"node:fs";import{dirname as oS,join as wK}from"node:path";import{CONNECTOR_PLATFORMS as tS,connectorChannelsFromPlatforms as eS,listConnectorCatalog as SK,shouldIncludeConnectorField as $b}from"@cline/shared";import{resolveConnectorDataDir as Zb,resolveConnectorSettingsPath as _3}from"@cline/shared/storage";var Qb=1,CK={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},Wb={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 H$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function b4($){return typeof $==="string"?$.trim():void 0}function bK($){if(!PK($))return;try{let Z=JSON.parse(nS($,"utf8"));return H$(Z)?Z:void 0}catch{return}}function z3(){let $=bK(_3()),Z=H$($?.connectors)?$.connectors:{},Q={};for(let[W,J]of Object.entries(Z)){if(!H$(J))continue;let X=b4(J.type),Y=b4(J.configuredAt),j=b4(J.updatedAt);if(!X||!Y||!j)continue;let V=N9(J.values),H=H$(J.security)?{enabled:J.security.enabled===!0,values:N9(J.security.values)}:void 0;Q[W]={type:X,values:V,security:H,configuredAt:Y,updatedAt:j}}return{version:Qb,connectors:Q}}function yK($){let Z=_3();rS(oS(Z),{recursive:!0}),sS(Z,`${JSON.stringify($,null,2)}
719
- `,"utf8")}function N9($){if(!H$($))return{};let Z={};for(let[Q,W]of Object.entries($))if(typeof W==="string")Z[Q]=W.trim();return Z}function Jb($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Xb($){let Z=wK(Zb(),$);if(!PK(Z))return[];return iS(Z).filter((Q)=>Q.endsWith(".json")&&!Q.endsWith(".threads.json")).map((Q)=>wK(Z,Q))}function Yb($,Z,Q){let W=Z.botUsername??Z.userName??Z.applicationId??Z.phoneNumberId??String(Q);return`${$}:${W}`}function jb($,Z){let Q=bK(Z);if(!Q)return;let W=typeof Q.pid==="number"?Q.pid:void 0,J=typeof Q.hubUrl==="string"?Q.hubUrl:typeof Q.rpcAddress==="string"?Q.rpcAddress:void 0;if(!W||!J||!Jb(W))return;let X=Wb[$];if(!X)return;let Y={};for(let j of X.required){let V=CK[j](Q);if(!V||typeof V==="string"&&!V.trim())return;Y[j]=V}for(let j of X.optional){let V=CK[j](Q);if(V!==void 0)Y[j]=V}return{id:Yb($,Y,W),type:$,pid:W,hubUrl:J,...Y}}function Vb(){let $=[];for(let{name:Z}of SK())for(let Q of Xb(Z)){let W=jb(Z,Q);if(W)$.push(W)}return $.sort((Z,Q)=>{if(Z.type!==Q.type)return Z.type.localeCompare(Q.type);let W=Z.botUsername??Z.userName??"",J=Q.botUsername??Q.userName??"";return W.localeCompare(J)})}function Hb(){let $=z3();return Object.entries($.connectors).map(([Z,Q])=>({id:Z,type:Q.type,configuredAt:Q.configuredAt,updatedAt:Q.updatedAt})).sort((Z,Q)=>Z.type.localeCompare(Q.type))}function T3(){return{available:eS(),active:Vb(),configured:Hb()}}function Bb($,Z){if($.required&&!Z[$.flag]?.trim())throw Error(`${$.label} is required`)}function Gb($,Z){let Q={};for(let J of $.fields)Q[J.flag]=Z[J.flag]??J.initialValue??"";let W={};for(let J of $.fields){if(!$b(J,Q))continue;Bb(J,Q),W[J.flag]=Q[J.flag]}return W}function Kb($){if(!H$($))throw Error("connector.configure payload must be an object.");let Z=b4($.channel);if(!Z)throw Error("channel is required");let Q=tS.find((K)=>K.id===Z);if(!Q)throw Error(`unknown connector channel: ${Z}`);if(!new Set(SK().map((K)=>K.name)).has(Q.id))throw Error(`connector channel is not available: ${Z}`);let J=N9($.values),X=Gb(Q,J),Y=H$($.security)?$.security:{},j=Y.enabled===!0,V=N9(Y.values);if(j&&Q.security)for(let K of Q.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let H=z3(),B=new Date().toISOString(),G=H.connectors[Z];return H.connectors[Z]={type:Z,values:X,security:j?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??B,updatedAt:B},yK(H),T3()}function Fb($){if(!H$($))throw Error("connector.delete_config payload must be an object.");let Z=b4($.channel);if(!Z)throw Error("channel is required");let Q=z3();if(delete Q.connectors[Z],Object.keys(Q.connectors).length>0)yK(Q);else aS(_3(),{force:!0});return T3()}function Ab($){return $==="connector.configure"||$==="connector.delete_config"}function L3($,Z,Q){if(!Ab(Z.command))return;Q8($.telemetry,{ulid:Z.sessionId??Z.requestId??"hub",tool:Z.command,success:Q})}async function hK($,Z){try{if(Z.command==="connector.channels")return g(Z,T3());if(Z.command==="connector.configure"){let Q=Kb(Z.payload);return L3($,Z,!0),g(Z,Q)}if(Z.command==="connector.delete_config"){let Q=Fb(Z.payload);return L3($,Z,!0),g(Z,Q)}return h(Z,"unsupported_connector_command",`unsupported connector command: ${Z.command}`)}catch(Q){return L3($,Z,!1),h(Z,"connector_command_failed",Q instanceof Error?Q.message:String(Q))}}var fb=30000;function Ub($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function Db($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function Lb($,Z,Q){let W=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${Z}`;return h($,c8,W)}function _b($){return $?$:void 0}function zb($){let Z=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function Tb($,Z,Q,W){let J=performance.now(),X=!1,Y={command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Q.sessionId,timeoutMs:W},j=setInterval(()=>{if(X)return;let B=Math.round(performance.now()-J);m("warn","run.heartbeat",{...Y,elapsedMs:B}),$.publish($.buildEvent("run.heartbeat",{requestId:Z.requestId,elapsedMs:B,...W?{timeoutMs:W}:{}},Q.sessionId))},fb),V=$.sessionHost.runTurn(Q);V.then((B)=>{if(!X)return;m("warn","run.late_end",{...Y,elapsedMs:Math.round(performance.now()-J),finishReason:B?.finishReason})},(B)=>{if(!X)return;m("error","run.late_error",{...Y,elapsedMs:Math.round(performance.now()-J),error:B})});let H;try{if(!W)return await V;return await Promise.race([V,new Promise((B,G)=>{H=setTimeout(()=>{let K=`Hub run ${Z.command} timed out after ${W}ms.`;X=!0,clearInterval(j),G(Error(K)),m("error","run.timeout",{...Y,elapsedMs:Math.round(performance.now()-J)}),U3($,(F)=>F.sessionId===Q.sessionId,K),V$($,(F)=>F.sessionId===Q.sessionId,K),$.sessionHost.abort(Q.sessionId,K).catch((F)=>{m("error","run.timeout_abort_failed",{...Y,error:F})})},W)})])}finally{if(X=!0,clearInterval(j),H)clearTimeout(H)}}async function kK($,Z){let Q=C0(Z),W=Z.payload&&typeof Z.payload==="object"?Z.payload:{},J=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!J.trim())return h(Z,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let X=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,Y=Array.isArray(X?.userFiles)?X.userFiles.filter((B)=>typeof B==="string"):void 0,j=zb(W);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let V;try{V=await Tb($,Z,{sessionId:Q,prompt:J,mode:_b(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(X?.userImages)?X.userImages:void 0,userFiles:Y,timeoutMs:j},j)}catch(B){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(P$(B))return Lb(Z,Q,B);throw $.publish($.buildEvent("run.failed",{reason:"error",error:B instanceof Error?B.message:String(B)},Q)),B}if(V){let B=await d0($,Q),G=Db(V);if($.publish($.buildEvent(Ub(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...B?{snapshot:B}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let H=await d0($,Q);return g(Z,V||H?{...V?{result:V}:{},...H?{snapshot:H}:{}}:void 0)}async function IK($,Z){let Q=C0(Z),W=typeof Z.payload?.reason==="string"?Z.payload.reason:"Run was aborted before pending approval or capability request was resolved.";U3($,(J)=>J.sessionId===Q,W);try{await $.sessionHost.abort(Q,Z.payload?.reason)}catch(J){m("warn","run.abort_failed",{command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Q,error:J})}finally{V$($,(J)=>J.sessionId===Q,W)}return g(Z,{applied:!0})}async function xK($,Z){let Q=F9(Z.payload?.payload);if(!Q)return h(Z,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),g(Z,{applied:!0})}async function gK($,Z){switch(Z.type){case"chunk":return;case"agent_event":await Ob($,Z);return;case"hook":if(Z.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:Z.payload.toolName},Z.payload.sessionId));else if(Z.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:Z.payload.toolName},Z.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:Z.payload.sessionId,summary:Z.payload.summary,lastEvent:Z.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,Z.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:Z.payload.sessionId,prompts:Z.payload.prompts},Z.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:Z.payload.id,prompt:Z.payload.prompt,delivery:Z.payload.delivery,attachmentCount:Z.payload.attachmentCount,userImages:Z.payload.userImages,userFiles:Z.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:Z.payload.sessionId,prompt:Q},Z.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:Z.payload.sessionId,snapshot:Z.payload.snapshot},Z.payload.sessionId));return;case"status":{let[Q,W]=await Promise.all([u0($,Z.payload.sessionId),d0($,Z.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...W?{snapshot:W}:{}},Z.payload.sessionId));return}case"ended":await qb($,Z);return;default:return}}async function Ob($,Z){let{sessionId:Q,event:W}=Z.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},Q));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},Q));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){$.publish($.buildEvent("assistant.delta",{text:W.text},Q));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},Q));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},Q));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},Q));break}return}if(W.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:Z.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:Z.payload.teamAgentId,teamRole:Z.payload.teamRole}},Q));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},Q))}async function qb($,Z){let Q=$.suppressNextTerminalEventBySession.get(Z.payload.sessionId),W=Q===Z.payload.reason||Q==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(Z.payload.sessionId);let[J,X]=await Promise.all([u0($,Z.payload.sessionId),d0($,Z.payload.sessionId)]);if(Z.payload.reason==="completed"){let Y=await DK(J);$.publish($.buildEvent("ui.notify",Y,Z.payload.sessionId))}if(W)return;$.publish($.buildEvent(Z.payload.reason==="aborted"?"run.aborted":Z.payload.reason==="error"||Z.payload.reason==="failed"?"run.failed":"run.completed",{reason:Z.payload.reason,...X?{snapshot:X}:{}},Z.payload.sessionId))}import{createSessionId as cK,parseRuntimeConfigExtensions as uK}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Io,HUB_COMPACTION_CAPABILITY as xo,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as go,HUB_HOOK_CAPABILITY_PREFIX as mo,HUB_MISTAKE_LIMIT_CAPABILITY as vo,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as co,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as uo,isHubToolExecutorName as Mb}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as no,HUB_COMPACTION_CAPABILITY as ao,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as so,HUB_HOOK_CAPABILITY_PREFIX as oo,HUB_MISTAKE_LIMIT_CAPABILITY as to,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as eo,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as $t}from"@cline/shared";var Rb=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function o$($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function Eb($,Z){let Q=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",X=o$($.inputSchema);if(!Q||!W||!X||!J||Z.has(J))return;return Z.add(J),{kind:"tool",capabilityName:J,name:Q,description:W,inputSchema:X,...o$($.lifecycle)?{lifecycle:o$($.lifecycle)}:{}}}function q3($){if(!Array.isArray($))return[];let Z=[],Q=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let J=W,X=J.kind,Y=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!Y||Q.has(Y))continue;if(X==="tool"){let j=Eb(J,Q);if(j)Z.push(j);continue}if(X==="toolExecutor"){let j=J.executor;if(!Mb(j))continue;Q.add(Y),Z.push({kind:"toolExecutor",capabilityName:Y,executor:j});continue}if(X==="hook"){let j=typeof J.name==="string"?J.name.trim():"";if(!j)continue;Q.add(Y),Z.push({kind:"hook",capabilityName:Y,name:j});continue}if(X==="compaction"){Q.add(Y),Z.push({kind:"compaction",capabilityName:Y,...o$(J.config)?{config:o$(J.config)}:{}});continue}if(X==="checkpoint"){Q.add(Y),Z.push({kind:"checkpoint",capabilityName:Y,...o$(J.config)?{config:o$(J.config)}:{}});continue}if(X==="mistakeLimit"){Q.add(Y),Z.push({kind:"mistakeLimit",capabilityName:Y});continue}if(X==="userInstructionService")Q.add(Y),Z.push({kind:"userInstructionService",capabilityName:Y})}return Z}function vK($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function Nb($){return Object.hasOwn($,"update")?$.update:$}function y4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function wb($){let Z=($??[]).map(y4).filter(Boolean);return Z.length>0?new Set(Z):void 0}function Cb($,Z,Q){if(!Q)return!0;let W=y4($),J=y4(Z),X=W.includes(":")?W.split(":").at(-1)??W:W,Y=J.includes(":")?J.split(":").at(-1)??J:J;return Q.has(W)||Q.has(J)||Q.has(X)||Q.has(Y)}function O3($,Z){let Q=wb(Z);return $.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>Cb(W.id,W.name,Q))}function mK($,Z){let Q=async(W,J)=>{let X=y4(W),j=O3($,Z).filter((K)=>K.id===X||y4(K.name)===X||K.id.endsWith(`:${X}`)).filter((K)=>!K.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((K)=>K.id).join(", ")}`:`Skill "${W}" not found.`;let V=j[0].skill,H=J?.trim(),B=H?`
714
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[Z,J,Q]),W.map((X)=>X.run_id)}handleTeamEvent($,Z){this.appendTeamEvent($,Z.type,Z)}}function vG($={}){try{let Z=new q4($);return Z.init(),Z}catch{let Z=new X9({teamDir:$.teamDir});return Z.init(),Z}}function Y9($,Z){return rC($,Z)}function nC($,Z){let Q=Z?.["*"]??{},W=Z?.[$]??{};return{...Q,...W}.enabled!==!1}function aC($,Z){return $.filter((Q)=>nC(Q.name,Z))}function iW($,Z){return k1(aC($,Z))}var sC={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 oC($){let Z=$.trim().toLowerCase();return sC[Z]??Z}function tC($,Z){if(Z.tools===void 0)return $;let Q=new Set(Z.tools.map(oC));if(Z.skills!==void 0)Q.add("skills");return $.filter((W)=>Q.has(W.name))}function cG(){return`team-${iC(5)}`}function j9($,Z,Q,W,J,X,Y,j){let V=e0[u1({mode:Q})],H=_8(Z,W,Q,J??L8);return iW(w8({cwd:$,...V,enableSkills:!!Y,...H,executors:{...Y?{skills:Y}:{},...j??{}}}),X)}function eC($){return j9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,$P,$.toolExecutors).some((Z)=>Z.name==="skills")}var $P=async()=>"";async function ZP($){let Z=Z0();if(!C$({filePath:Z}))return{tools:[]};let Q=new I8({clientFactory:G5({settingsPath:Z})}),W;try{W=await k8(Q,{filePath:Z})}catch(j){await Q.dispose().catch(()=>{});let V=j instanceof Error?j.message:String(j);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${V}`),{tools:[]}}let J=W.filter((j)=>j.disabled!==!0),X=await Promise.allSettled(J.map((j)=>F5({serverName:j.name,provider:Q}))),Y=[];for(let[j,V]of X.entries())if(V.status==="fulfilled")Y.push(...V.value);else{let H=V.reason instanceof Error?V.reason.message:String(V.reason);$?.log(`[mcp] Failed to load tools from MCP server "${J[j].name}", skipping: ${H}`)}return{tools:Y,shutdown:async()=>{await Q.dispose()}}}function QP($,Z){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,Z)}catch{}}function WP($){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 JP($){let Z=e0[u1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??Z.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??Z.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 V9{teamRuntimeEntries=new Map;async build($){let{config:Z,hooks:Q,extensions:W,logger:J,telemetry:X,createSpawnTool:Y,onTeamRestored:j,userInstructionService:V,configExtensions:H,toolExecutors:B}=$,G=$.onTeamEvent??(()=>{}),K=JP(Z),F=Z.workspaceRoot??Z.cwd,A=$.toolPolicies??Z.toolPolicies,L=K1(),f=[],D=Z.teamName?.trim()||cG(),U=Z.sessionId?.trim()||D,T=K.enableSpawnAgent?h5({workspaceRoot:F}):{configs:[],errors:[]},q=T.configs.some((x)=>x.skills!==void 0),z=Y9(H,"rules"),_=Y9(H,"skills"),M=_||q,E=Y9(H,"workflows"),P=Y9(H,"plugins"),c=z||_||E,n=!1,a=Boolean(V),t=V,p0;for(let x of T.errors)(J??Z.logger)?.log?.(`[agents] Failed to load agent config at ${x.path}: ${x.error.message}`);if(!t&&(c||q))t=w2({skills:M?{workspacePath:F,includePluginSkills:P,pluginSkillDirectories:P?$.pluginSkillDirectories:void 0,pluginPaths:Z.pluginPaths,cwd:Z.cwd}:{workspacePath:F},rules:{workspacePath:Z.cwd},workflows:{workspacePath:Z.cwd}});if(t)await t.start().catch(()=>{});let K$=K.enableTools&&_&&Boolean(t)&&t?.hasConfiguredSkills(Z.skills)===!0&&eC({cwd:Z.cwd,providerId:Z.providerId,mode:K.mode,modelId:Z.modelId,toolRoutingRules:Z.toolRoutingRules,toolPolicies:A,toolExecutors:B}),d=t&&c?t.createExtension({includeRules:z,includeSkills:_,includeWorkflows:E,registerSkillsTool:K$,allowedSkillNames:Z.skills}):void 0,X1=d?[...W??Z.extensions??[],d]:W??Z.extensions;if(K.enableTools){if(f.push(...j9(Z.cwd,Z.providerId,K.mode,Z.modelId,Z.toolRoutingRules,A,void 0,B)),!K.disableMcpSettingsTools){let x=await ZP(Z.logger);f.push(...x.tools),p0=x.shutdown}}let N,X0=K.enableAgentTeams?vG():void 0,Y0=X0?.loadRuntime(U),R0=Y0?.state,Z2=Y0?.teammates??[],Y1=new Map(Z2.map((x)=>[x.agentId,x])),t0=Z.sessionId||D,$8,Q2=[],I4=!1,j1=R2({providerId:Z.providerId,modelId:Z.modelId,cwd:Z.cwd,apiKey:Z.apiKey??"",baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxTokensPerTurn:Z.maxTokensPerTurn,maxIterations:Z.maxIterations,hooks:Q,extensions:X1,logger:J??Z.logger,telemetry:$.telemetry??Z.telemetry,workspaceMetadata:Z.workspaceMetadata});if(K.enableSpawnAgent){if(T.configs.length>0)f.push(...iW(I5({configProvider:j1,agents:T.configs,createSubAgentTools:(x)=>K.enableTools?tC(j9(Z.cwd,x.providerId??Z.providerId,K.mode,x.modelId??Z.modelId,Z.toolRoutingRules,A,x.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(x.skills):void 0,B),x):[],hookErrorMode:Z.hookErrorMode,toolPolicies:A,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),A))}if(!this.teamRuntimeEntries.has(t0))this.teamRuntimeEntries.set(t0,{delegatedAgentConfigProvider:j1});let x4=()=>{if(!K.enableAgentTeams)return;let x=this.teamRuntimeEntries.get(t0)??{delegatedAgentConfigProvider:j1};if(this.teamRuntimeEntries.set(t0,x),N=x.runtime,!N){if(N=new B4({teamName:D,leadAgentId:Z.sessionId||"lead",missionLogIntervalSteps:K.missionLogIntervalSteps,missionLogIntervalMs:K.missionLogIntervalMs,onTeamEvent:(Q0)=>{if(G(Q0),N&&X0){if(Q0.type==="teammate_spawned"&&Q0.teammate?.rolePrompt){let V1={agentId:Q0.agentId,rolePrompt:Q0.teammate.rolePrompt,modelId:Q0.teammate.modelId,maxIterations:Q0.teammate.maxIterations};Y1.set(V1.agentId,V1)}if(Q0.type==="teammate_shutdown"&&!WP(Q0.reason))Y1.delete(Q0.agentId);X0.handleTeamEvent(U,Q0),X0.persistRuntime(U,N.exportState(),Array.from(Y1.values()))}}}),R0)N.hydrateState(R0),I4=!0;x.runtime=N}if(!n){if(!N)return;n=!0;let Q0=Q5({runtime:N,leadAgentId:Z.sessionId||"lead",restoredFromPersistence:Boolean(R0),restoredTeammates:Z2,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(V1)=>{Q2=V1,$8?.addTools(V1)},createBaseTools:K.enableTools?()=>j9(Z.cwd,Z.providerId,K.mode,Z.modelId,Z.toolRoutingRules,A,void 0,B):void 0,teammateConfigProvider:j1});if(I4)N.recoverActiveRuns("runtime_recovered");if(Q0.restoredFromPersistence)j?.();f.push(...Q0.tools)}return N};if(K.enableSpawnAgent&&Y){let x=Y();f.push({...x,execute:async(Q0,V1)=>{return x4(),x.execute(Q0,V1)}})}if(K.enableAgentTeams)x4();let W2=iW(f,A),r9=W2.some((x)=>x.name==="submit_and_exit"&&x.lifecycle?.completesRun===!0),g4=K.enableAgentTeams?()=>{let x=this.teamRuntimeEntries.get(t0)?.runtime;if(!x)return;let Q0=x.listTasks(),V1=Q0.some((w1)=>w1.status==="in_progress"||w1.status==="pending"),FJ=x.listRuns({}),qA=FJ.some((w1)=>w1.status==="running"||w1.status==="queued");if(V1||qA){let w1=Q0.filter((P0)=>P0.status==="in_progress"||P0.status==="pending").map((P0)=>`${P0.id} (${P0.status}): ${P0.title}`).join(", "),AJ=FJ.filter((P0)=>P0.status==="running"||P0.status==="queued").map((P0)=>`${P0.id} (${P0.status})`).join(", "),i9=[];if(w1)i9.push(`Unfinished tasks: ${w1}`);if(AJ)i9.push(`Active runs: ${AJ}`);return`[SYSTEM] You still have team obligations. ${i9.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,OA=r9?{requireCompletionTool:!0,...g4?{completionGuard:g4}:{}}:g4?{completionGuard:g4}:void 0;return{tools:W2,logger:J??Z.logger,telemetry:X??Z.telemetry,teamRuntime:N,teamRestoredFromPersistence:Boolean(R0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(t0)?.delegatedAgentConfigProvider??j1,extensions:X1,completionPolicy:OA,registerLeadAgent:(x)=>{if($8=x,Q2.length>0)x.addTools(k1(Q2,[...L]))},shutdown:async(x)=>{if(QP(N,x),this.teamRuntimeEntries.delete(t0),await p0?.(),!a)t?.stop()}}}}function XP($,Z){let Q=$?.expiresAt,W=Z?.expiresAt;return $?.accessToken===Z?.accessToken&&$?.refreshToken===Z?.refreshToken&&$?.accountId===Z?.accountId&&Q===W}class H9 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 nW{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new Y$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let Z=B0($.providerId);if(!Z)return null;return this.resolveWithSingleFlight(Z.providerId,Z.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,Z,Q=!1){let W=this.refreshInFlight.get(Z);if(W)return W;let J=this.resolveProviderApiKeyInternal($,Z,Q).catch((X)=>{throw X}).finally(()=>{this.refreshInFlight.delete(Z)});return this.refreshInFlight.set(Z,J),J}async resolveProviderApiKeyInternal($,Z,Q){let W=B0($);if(!W)return null;let J=this.providerSettingsManager.getProviderSettings(Z);if(!J)return null;let X=CZ($,J);if(!X)return null;let Y=await W.refresh({settings:J,credentials:X,forceRefresh:Q,telemetry:this.telemetry});if(!Y)throw new H9($);let j=X8({manager:this.providerSettingsManager,providerId:$,settings:J,credentials:Y,setLastUsed:!1,save:!1}),V=!XP(J.auth,j.auth);if(V)this.providerSettingsManager.saveProviderSettings(j,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:W.getApiKey(j)??Y.access,accountId:Y.accountId,refreshed:V}}}import{normalizeUserInput as YP}from"@cline/shared";import{nanoid as jP}from"nanoid";class uG{list($){return $?v0($):[]}update($,Z){if(!$)return{sessionId:Z.sessionId,prompts:[],updated:!1};let Q=Z.promptId.trim(),W=$.pendingPrompts.findIndex((V)=>V.id===Q);if(W<0)return{sessionId:Z.sessionId,prompts:v0($),updated:!1};let J=$.pendingPrompts[W];if(!J)return{sessionId:Z.sessionId,prompts:v0($),updated:!1};let X=Z.prompt===void 0?J.prompt:YP(Z.prompt).trim();if(!X)throw Error("prompt cannot be empty");let Y=Z.delivery??J.delivery,j={...J,prompt:X,mode:Z.mode??J.mode,delivery:Y};return $.pendingPrompts.splice(W,1),VP($,j,W,J.delivery),{sessionId:Z.sessionId,prompts:v0($),prompt:B9(j),updated:!0}}delete($,Z){if(!$)return{sessionId:Z.sessionId,prompts:[],removed:!1};let Q=Z.promptId.trim(),W=$.pendingPrompts.findIndex((X)=>X.id===Q);if(W<0)return{sessionId:Z.sessionId,prompts:v0($),removed:!1};let[J]=$.pendingPrompts.splice(W,1);return{sessionId:Z.sessionId,prompts:v0($),prompt:J?B9(J):void 0,removed:!0}}enqueue($,Z){let{prompt:Q,mode:W,delivery:J,userImages:X,userFiles:Y}=Z,j=$.pendingPrompts.findIndex((V)=>V.prompt===Q);if(j>=0){let[V]=$.pendingPrompts.splice(j,1),H={...V,prompt:Q,mode:W??V.mode,userImages:X??V.userImages,userFiles:Y??V.userFiles};if(J==="steer"||V.delivery==="steer")$.pendingPrompts.unshift({...H,delivery:"steer"});else $.pendingPrompts.push(H)}else{let V={id:`pending_${Date.now()}_${jP(5)}`,prompt:Q,mode:W,delivery:J,userImages:X,userFiles:Y};if(J==="steer")$.pendingPrompts.unshift(V);else $.pendingPrompts.push(V)}return v0($)}consumeSteer($){let Z=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(Z<0)return{prompts:v0($)};let[Q]=$.pendingPrompts.splice(Z,1);return{entry:Q,prompts:v0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:v0($)}}requeueFront($,Z){return $.pendingPrompts.unshift(Z),v0($)}clear($){return $.pendingPrompts.length=0,[]}}class aW{deps;service=new uG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let Z=this.deps.getSession($.sessionId);if(!Z||Z.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(Z,$);return this.emitPrompts(Z),this.scheduleDrain($.sessionId,Z),Q}delete($){let Z=this.deps.getSession($.sessionId);if(!Z||Z.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(Z,$);return this.emitPrompts(Z),this.scheduleDrain($.sessionId,Z),Q}enqueue($,Z){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,Z),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let Z=this.deps.getSession($);if(!Z)return;let{entry:Q}=this.service.consumeSteer(Z);if(!Q)return;return this.emitPrompts(Z),this.emitSubmitted(Z,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:v0($)}})}scheduleDrain($,Z){if(Z.pendingPrompts.length===0||Z.aborting||Z.drainingPendingPrompts||!Z.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let Z=this.deps.getSession($);if(!Z)return;if(Z.aborting||Z.drainingPendingPrompts)return;if(!Z.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(Z);if(!Q)return;this.emitPrompts(Z),this.emitSubmitted(Z,Q),Z.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{W=!1,this.service.requeueFront(Z,Q),this.emitPrompts(Z)}finally{if(Z.drainingPendingPrompts=!1,W&&Z.pendingPrompts.length>0&&Z.status!=="failed"&&Z.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,Z){let Q=B9(Z);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount,userImages:Q.userImages,userFiles:Q.userFiles}})}}function B9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0),userImages:$.userImages,userFiles:$.userFiles}}function v0($){return $.pendingPrompts.map(B9)}function VP($,Z,Q,W){if(Z.delivery==="steer")$.pendingPrompts.unshift(Z);else if(W==="steer")$.pendingPrompts.push(Z);else $.pendingPrompts.splice(Q,0,Z)}G0();class oW{deps;constructor($){this.deps=$}dispatchAgentEvent($,Z,Q){let W=this.deps.getSession($),J={sessionId:$,config:Z,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},X=NW(Q),Y=!!W&&(!X.agentId||X.agentId===sW(W.agent));wW(J,Q,Y?{isPrimaryAgentEvent:!0,agentId:sW(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,Z){let Q=this.deps.getSession($);if(Q){if(HW(Q,Z),Z.type==="agent_event"){let W={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};wW(W,Z.event,{agentId:Z.agentId,teamRole:"teammate",teamAgentId:Z.agentId,isPrimaryAgentEvent:!1})}if(Z.type==="teammate_spawned"){let W=q1({agentId:Z.teammate.runtimeAgentId??Z.agentId,conversationId:Z.teammate.conversationId,parentAgentId:Z.teammate.parentAgentId,createdByAgentId:sW(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:Z.agentId});if(W)f$(Q.config.telemetry,{ulid:$,modelId:Z.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...W})}}if(await BW($,Z,this.deps.invokeBackendOptional),Q)GW(Q,$,Z,this.deps.emit)}async handlePluginEvent($,Z,Q){if(Z.name==="plugin_log"){this.handlePluginLog($,Z.payload);return}if(Z.name==="automation_event"){let V=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!V)return;let H=Z.payload&&typeof Z.payload==="object"?Z.payload:void 0;if(!H)return;await V.ingestEvent(H);return}if(Z.name!=="steer_message"&&Z.name!=="queue_message"&&Z.name!=="pending_prompt")return;let W=Z.payload&&typeof Z.payload==="object"?Z.payload:void 0,J=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,X=typeof W?.prompt==="string"?W.prompt.trim():"";if(!X)return;let Y=Z.name==="steer_message"?"steer":Z.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(J,{prompt:X,delivery:Y})}handlePluginLog($,Z,Q){let W=this.deps.getSession($),J=Q??W?.config.extensionContext?.logger??W?.config.logger;if(!J||!Z||typeof Z!=="object")return;let X=Z,Y=typeof X.message==="string"?X.message:"";if(!Y)return;let j=X.metadata&&typeof X.metadata==="object"?{...X.metadata}:{};if(j.sessionId??=$,typeof X.pluginName==="string"&&X.pluginName)j.pluginName=X.pluginName;if(X.level==="debug"){J.debug(Y,j);return}if(X.level==="error"){if(J.error)J.error(Y,j);else J.log(Y,{...j,severity:"error"});return}J.log(Y,j)}}function sW($){return $.getAgentId()}function tW($){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:W$($.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 eW($,Z){let Q=$[Z];return typeof Q==="function"?Q:null}async function dG($,Z,...Q){let W=eW($,Z);if(!W)throw Error(`session service method not available: ${Z}`);return Promise.resolve(W.apply($,Q))}async function lG($,Z,...Q){let W=eW($,Z);if(!W)return;await Promise.resolve(W.apply($,Q))}async function pG($,Z,...Q){let W=eW($,Z);if(!W)return;return await Promise.resolve(W.apply($,Q))}r0();G0();function $3($,Z,Q){return{onSubAgentEvent:(W)=>$.onAgentEvent(Q,Z,W),onSubAgentStart:(W)=>{let J=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(W.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let X=q1({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:W.parentAgentId});if(X)f$(Z.telemetry,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,...X});d4(Z.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:W.parentAgentId,agentId:W.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",Q,W)},onSubAgentEnd:(W)=>{let J=$.getSession(Q)?.runtime.teamRuntime,X=$.subAgentStarts.get(W.subAgentId),Y=X?Date.now()-X.startedAt:0,j=W.result?.text?W.result.text.split(`
715
+ `).length:0;d4(Z.telemetry,{event:"ended",ulid:Q,durationMs:Y,outputLines:j,errorMessage:W.error?String(W.error):void 0,agentId:W.subAgentId,parentId:W.parentAgentId,...q1({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:J?.getTeamId(),teamName:J?.getTeamName(),createdByAgentId:W.parentAgentId})}),$.subAgentStarts.delete(W.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,W)}}}function Z3($,Z,Q,W){let J=$3($,Z,Q);return N2({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:Z.providerId,modelId:Z.modelId,cwd:Z.cwd,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking,maxIterations:Z.maxIterations,hooks:Z.hooks,extensions:Z.extensions,logger:Z.logger,telemetry:Z.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:Z.providerId,modelId:Z.modelId,apiKey:Z.apiKey,baseUrl:Z.baseUrl,headers:Z.headers,providerConfig:Z.providerConfig,knownModels:Z.knownModels,thinking:Z.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Y=Z.enableTools?w8({cwd:Z.cwd,...e0[u1({mode:Z.mode})],executors:W}):[];if(Z.enableSpawnAgent)Y.push(Z3($,Z,Q,W));return k1(Y)},...J})}import{readFile as HP,stat as BP}from"node:fs/promises";var GP=20480000;async function rG($){let Z=await BP($);if(!Z.isFile())throw Error("Path is not a file");if(Z.size>GP)throw Error("File is too large to read into context.");let Q=await HP($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var iG=5000;function M4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function _P($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$,Q=M4(Z.inputTokens),W=M4(Z.outputTokens),J=M4(Z.cacheReadTokens),X=M4(Z.cacheWriteTokens),Y=M4(Z.totalCost);if(Q===void 0||W===void 0||J===void 0||X===void 0||Y===void 0)return;return{inputTokens:Q,outputTokens:W,cacheReadTokens:J,cacheWriteTokens:X,totalCost:Y}}function zP($,Z){return{inputTokens:Math.max($.inputTokens,Z.inputTokens),outputTokens:Math.max($.outputTokens,Z.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,Z.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,Z.cacheWriteTokens),totalCost:Math.max($.totalCost,Z.totalCost)}}class j${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new $4;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new r2;constructor($){let Z=FP();if(Z)LP(Z);let Q=m0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new V9,this.createAgentInstance=$.createAgent??((W)=>new l1(W)),this.defaultCapabilities=O0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new Y$,this.oauthTokenManager=$.oauthTokenManager??new nW({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new aW({getSession:(W)=>this.sessions.get(W),emit:(W)=>this.emit(W),send:(W)=>this.runTurn(W)}),this.pendingPrompts={list:async(W)=>this.pendingPromptsController.list(W.sessionId),update:async(W)=>this.pendingPromptsController.update(W),delete:async(W)=>this.pendingPromptsController.delete(W)},this.eventBridge=new oW({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,J,X)=>{this.invoke("persistSessionMessages",W,J,X)},enqueuePendingPrompt:(W,J)=>this.pendingPromptsController.enqueue(W,J),invokeBackendOptional:(W,...J)=>this.invokeOptional(W,...J)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let Z=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!Z?.apiKey)return $;return{...$,config:{...$.config,apiKey:Z.apiKey}}}async startSession($){let Z=$.source??T0.CLI,Q=$0(),W=$.config.sessionId?.trim()??"",J=W||fP(),X=await this.applyInitialOAuthCredentials($),Y=X.initialMessages??[],j=Y.length>0?l5(Y):_0(),V=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!V)throw Error("session service method not available: ensureSessionsDir");let H=Q3(V,J),B=Q3(H,`${J}.messages.json`),G=Q3(H,`${J}.json`),K=W$($.config),F=N0.parse({version:1,session_id:J,source:Z,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:X.config.providerId,model:X.config.modelId,cwd:X.config.cwd,workspace_root:K,team_name:X.config.teamName,enable_tools:X.config.enableTools,enable_spawn:X.config.enableSpawnAgent,enable_teams:X.config.enableAgentTeams,prompt:X.prompt?.trim()||void 0,messages_path:B}),A;if(W.length>0&&Y.length>0&&!X.prompt?.trim()){let N=await this.invokeOptionalValue("readSessionManifest",J);if(N)F=N,A={manifestPath:G,messagesPath:N.messages_path||B,manifest:N}}let f=await this.seedAggregateUsageFromArtifacts({initialUsage:j,sessionDir:H,rootMessagesPath:A?.messagesPath??B,manifest:F});this.usageBySession.set(J,j),this.aggregateUsageBySession.set(J,f);let D=O0(this.defaultCapabilities,$.capabilities),U=D?.toolExecutors??this.toolExecutors,T=$.localRuntime,q=T?.extensionContext?.logger??T?.logger,z=T?.extensionContext?.automation,_,M={getSession:(N)=>this.sessions.get(N),subAgentStarts:this.subAgentStarts,onAgentEvent:(N,X0,Y0)=>this.eventBridge.dispatchAgentEvent(N,X0,Y0),invokeBackendOptional:(N,...X0)=>this.invokeOptional(N,...X0)};_=await VG({input:X,localRuntime:$.localRuntime,sessionId:J,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:D,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(N)=>{if(N.name==="plugin_log"){this.eventBridge.handlePluginLog(J,N.payload,q);return}this.eventBridge.handlePluginEvent(J,N,z)},onTeamEvent:(N)=>{this.eventBridge.handleTeamEvent(J,N),_.config.onTeamEvent?.(N)},createSpawnTool:()=>Z3(M,_.config,J,U),createSubAgentLifecycleCallbacks:(N)=>$3(M,N,J),readSessionMetadata:async()=>(await this.getSession(J))?.metadata,writeSessionMetadata:async(N)=>{await this.persistSessionMetadata(J,()=>N)}});let E=await this.runtimeBuilder.build(_.runtimeBuilderInput),P=_.config,c=_.providerConfig;if(E.teamRuntime&&!P.teamName?.trim())P.teamName=E.teamRuntime.getTeamName();let n=[...E.tools,...P.extraTools??[]],a=E.extensions??_.extensions,t={sessionId:J,providerId:c.providerId,modelId:c.modelId,apiKey:c.apiKey,baseUrl:c.baseUrl,headers:c.headers,knownModels:c.knownModels,providerConfig:c,thinking:P.thinking,reasoningEffort:P.reasoningEffort??c.reasoningEffort,maxTokensPerTurn:P.maxTokensPerTurn,systemPrompt:P.systemPrompt,maxIterations:P.maxIterations,execution:P.execution,prepareTurn:EW(P),tools:n,hooks:_.hooks,extensions:a,hookErrorMode:P.hookErrorMode,initialMessages:_.effectiveInput.initialMessages,userFileContentLoader:rG,toolPolicies:_.toolPolicies,requestToolApproval:_.requestToolApproval?async(N)=>{let X0=_.requestToolApproval,Y0=this.sessions.get(J);if(Y0)await this.markTurnPending(Y0);try{if(!X0)return{approved:!1,reason:"Tool approval callback is not configured."};return await X0(N)}finally{let R0=this.sessions.get(J);if(R0?.status==="pending")await this.markTurnRunning(R0)}}:void 0,telemetry:P.telemetry,onConsecutiveMistakeLimitReached:P.onConsecutiveMistakeLimitReached,completionPolicy:E.completionPolicy,consumePendingUserMessage:()=>{let N=this.pendingPromptsController.consumeSteer(J);return N?K4(N.prompt,N.mode??P.mode):void 0},logger:E.logger??P.logger,extensionContext:P.extensionContext,onEvent:(N)=>this.eventBridge.dispatchAgentEvent(J,P,N)};t.hooks={...t.hooks,onEvent:async(N)=>{if(await _.hooks?.onEvent?.(N),N.type!=="assistant-message")return;let X0=this.sessions.get(J);if(!X0)return;let Y0=X0.agent.getMessages();try{await this.invoke("persistSessionMessages",J,Y0,P.systemPrompt)}catch(R0){P.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:J,error:R0}),i$(P.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:R0,severity:"warn",handled:!0,context:{sessionId:J,providerId:P.providerId,modelId:P.modelId}})}}};let p0=this.createAgentInstance(t);if(t.onEvent)p0.subscribeEvents(t.onEvent);E.registerLeadAgent?.(p0);let K$=q1({agentId:p0.getAgentId(),conversationId:p0.getConversationId(),teamId:E.teamRuntime?.getTeamId(),teamName:E.teamRuntime?.getTeamName(),teamRole:E.teamRuntime?"lead":void 0});if(HG(P,J,W.length>0,K,K$),K$)f$(P.telemetry,{ulid:J,modelId:P.modelId,provider:P.providerId,...K$});if(E.teamRuntime)VZ(P.telemetry,{ulid:J,teamId:E.teamRuntime.getTeamId(),teamName:E.teamRuntime.getTeamName(),leadAgentId:p0.getAgentId(),restoredFromPersistence:E.teamRestoredFromPersistence===!0});let d={sessionId:J,config:P,sessionMetadata:X.sessionMetadata,...A?{artifacts:A}:{},source:Z,startedAt:A?.manifest.started_at??Q,updatedAt:A?.manifest.ended_at??A?.manifest.started_at??Q,pendingPrompt:F.prompt,runtime:E,agent:p0,started:!1,status:A?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:Y,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:_.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(J,d),this.emitStatus(J,"running"),Y.length>0&&!A){if(await this.ensureSessionPersisted(d),await this.invoke("persistSessionMessages",d.sessionId,Y,d.config.systemPrompt),!X.prompt?.trim())await this.updateStatus(d,"completed",0)}let X1;try{if(X.prompt?.trim())if(X1=await this.executeTurn(d,{prompt:X.prompt,userImages:X.userImages,userFiles:X.userFiles}),!d.interactive)await this.finalizeSingleRun(d,X1.finishReason);else await this.completeInteractiveTurn(d,X1.finishReason)}catch(N){if(d.interactive&&d.aborting)X1=await this.completeAbortedInteractiveTurn(d);else{i$(d.config.telemetry,{component:"core",operation:"session.start",error:N,severity:"error",handled:!1,context:{sessionId:d.sessionId,providerId:d.config.providerId,modelId:d.config.modelId}});try{await this.failSession(d)}catch(X0){d.config.logger?.error?.("Session failure cleanup threw",{sessionId:d.sessionId,error:X0})}throw N}}return{sessionId:J,manifest:F,manifestPath:G,messagesPath:B,result:X1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(Z)=>this.getSession(Z),readMessages:(Z)=>this.readSessionMessages(Z),buildStartInput:(Z,Q)=>{let W=Z.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:Z.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...W?{sessionMetadata:W}:{},initialMessages:Z.initialMessages}},startSession:(Z)=>this.startSession(Z),getStartedSessionId:(Z)=>Z.sessionId,readRestoredSession:(Z)=>this.getSession(Z)})}async runTurn($){let Z=this.getSessionOrThrow($.sessionId),Q=Z.agent.canStartRun(),W=$.delivery??(Z.interactive&&!Q?"queue":void 0);if(Z.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:W??"immediate"}}),W==="queue"||W==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:W,userImages:$.userImages,userFiles:$.userFiles});return}try{let J=await this.executeTurn(Z,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!Z.interactive)await this.finalizeSingleRun(Z,J.finishReason);else await this.completeInteractiveTurn(Z,J.finishReason);if(J.finishReason==="error"||J.finishReason==="aborted")return J;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),J}catch(J){if(Z.interactive&&Z.aborting)return await this.completeAbortedInteractiveTurn(Z);throw i$(Z.config.telemetry,{component:"core",operation:"session.submit",error:J,severity:"error",handled:!1,context:{sessionId:Z.sessionId,providerId:Z.config.providerId,modelId:Z.config.modelId}}),await this.failSession(Z),J}}async getAccumulatedUsage($){let Z=I7(this.usageBySession.get($)),Q=I7(this.aggregateUsageBySession.get($));return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,Z){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(Z)}async stopSession($){let Z=this.sessions.get($);if(!Z)return;if(Z.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),Z.interactive&&!j0(Z.status)){await this.releaseSessionRuntime(Z,"session_stop");return}if(Z.interactive&&Z.agent.canStartRun()){await this.shutdownSession(Z,{status:this.resolveInteractiveStopStatus(Z),exitCode:this.resolveInteractiveStopExitCode(Z),shutdownReason:"session_stop",endReason:"stopped"});return}Z.aborting=!0,Z.agent.abort(Error("session_stop")),await this.shutdownSession(Z,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let Z=[...this.sessions.values()];if(Z.length===0)return;await Promise.allSettled(Z.map((Q)=>Q.interactive&&!j0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let Z=this.sessions.get($);if(Z)return tW(Z);let Q=$.trim();if(!Q)return;let W=await this.getRow(Q);if(W)return t8(W);let J=await this.readManifest(Q);return J?m7(J):void 0}async listSessions($=200){let Q=(await this.listRows($)).map(t8),W=new Set(Q.map((J)=>J.sessionId));for(let J of this.sessions.values()){if(W.has(J.sessionId))continue;Q.unshift(tW(J))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let Z=await this.invoke("deleteSession",$);if(Z.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return Z.deleted}async updateSession($,Z){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:Z.prompt,metadata:Z.metadata,title:Z.title}))?.updated===!0}}async readSessionMessages($){let Z=$.trim();if(!Z)return[];let Q=await this.getRow(Z);if(Q?.messagesPath)return n1(Q.messagesPath);let W=await this.readManifest(Z);return n1(W?.messages_path)}async dispatchHookEvent($){await HH($,{queueSpawnRequest:(Z)=>this.invokeOptional("queueSpawnRequest",Z),upsertSubagentSessionFromHook:(Z)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",Z),appendSubagentHookAudit:(Z,Q)=>this.invokeOptional("appendSubagentHookAudit",Z,Q),applySubagentStatus:(Z,Q)=>this.invokeOptional("applySubagentStatus",Z,Q)})}subscribe($,Z){return this.events.subscribe($,Z)}async updateSessionModel($,Z){let Q=this.getSessionOrThrow($);Q.config.modelId=Z,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:Z}),Q.agent.updateConnection({modelId:Z})}handlePluginEvent($,Z,Q){return this.eventBridge.handlePluginEvent($,Z,Q)}async executeTurn($,Z){let Q=await this.prepareTurnInput($,Z),W=Q.prompt.trim();if(!W)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=W;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let J=await this.executeAgentTurn($,W,Q.userImages,Q.userFiles);while(KW($,J.finishReason)){let X=await FW($);if(X.length===0)break;let Y=AW($,X);J=await this.executeAgentTurn($,Y)}return J}async completeInteractiveTurn($,Z){if(G4($))return;$.lastInteractiveTurnFinishReason=Z,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let Z=$.lastInteractiveTurnFinishReason;if(!Z)return"cancelled";switch(Z){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return Z}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let Z=new Date,Q=$.agent.getMessages(),W=_0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:Z,endedAt:Z,durationMs:0}}async executeAgentTurn($,Z,Q,W){let J=$.started||$.agent.getMessages().length>0,X=$.persistedMessages??$.agent.getMessages(),Y=this.usageBySession.get($.sessionId)??_0(),j=this.aggregateUsageBySession.get($.sessionId)??Y;$.turnUsageBaseline=Y,$.turnAggregateUsageBaseline=j,$.turnPrimaryUsage=_0(),$.turnUsageByAgent=new Map,QZ($.config.telemetry,$.sessionId,$.config.mode),Z8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let V=J?()=>$.agent.continue(Z,Q,W):()=>$.agent.run(Z,Q,W),H=await this.runWithAuthRetry($,V,X);$.started=!0;let B=T5(H.messages,H,X);$.persistedMessages=B;let G=d5($.turnUsageByAgent?.values()??[]),K=f0(Y,H.usage),F=f0(f0(_0(),H.usage),G),A=f0(j,F);return this.usageBySession.set($.sessionId,K),this.aggregateUsageBySession.set($.sessionId,A),await this.persistSessionMetadata($.sessionId,(L)=>({...L??{},totalCost:K.totalCost,aggregatedAgentsCost:A.totalCost,usage:K,aggregateUsage:A})),await this.invoke("persistSessionMessages",$.sessionId,B,$.config.systemPrompt),this.observeTaskCompletionTool($,H),H}catch(V){throw i$($.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($,Z){if($.submitAndExitObserved)return;if(!Z.toolCalls.some((W)=>W.name===L0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,c4($.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($,Z){let Q=W$($.config),W=DP(Z.prompt).trim();if(!W)return{prompt:"",userImages:Z.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,Z.userFiles)};let J=await l6(W,Q);BG($.config.telemetry,J);let X=K4(J.prompt,Z.mode??$.config.mode),Y=this.resolveAbsoluteFilePaths($.config.cwd,Z.userFiles),j=this.resolveAbsoluteFilePaths(Q,J.matchedFiles),V=Array.from(new Set([...Y,...j]));return{prompt:X,userImages:Z.userImages,userFiles:V.length>0?V:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let Z=W$($.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:Z,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 markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,Z){let Q=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,J=Z(W?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:J}))?.updated===!1)return;Q.sessionMetadata=J,Q.artifacts.manifest.metadata=J}async finalizeSingleRun($,Z){if(G4($))return;let Q=Z==="aborted"||$.aborting,W=Z==="error";await this.shutdownSession($,{status:Q?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:Z})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,Z){if(Z.status==="completed"&&!$.submitAndExitObserved)c4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});m5($);let Q=[],W=(J,X)=>{Q.push(X),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:J,error:X,severity:"warn"}),i$($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:X,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,status:Z.status,shutdownReason:Z.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,Z.status,Z.exitCode)}catch(J){W("update_status",J)}try{await $.agent.shutdown(Z.shutdownReason)}catch(J){W("agent_shutdown",J)}}try{await Promise.resolve($.runtime.shutdown(Z.shutdownReason))}catch(J){W("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){W("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:Z.endReason,ts:Date.now()}}),Q.length>0&&Z.status==="failed")throw Q[0]}async releaseSessionRuntime($,Z){let Q=[],W=(J,X)=>{Q.push(X),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:J,error:X,severity:"warn"}),i$($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:X,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:J,reason:Z,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(Z)}catch(J){W("agent_shutdown",J)}try{await Promise.resolve($.runtime.shutdown(Z))}catch(J){W("runtime_shutdown",J)}try{await $.pluginSandboxShutdown?.()}catch(J){W("plugin_sandbox_shutdown",J)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,Z,Q){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,Z,Q);if(!W.updated)return;let J=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(J.status=Z,j0(Z))delete J.ended_at,J.exit_code=null;else J.ended_at=W.endedAt??$0(),J.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=J,$.status=Z,$.updatedAt=W.endedAt??$0(),$.endedAt=j0(Z)?null:J.ended_at,$.exitCode=J.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,J),this.emitStatus($.sessionId,Z)}async runWithAuthRetry($,Z,Q){try{return await Z()}catch(W){if(!J8($.config.providerId)||!UP(W))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),Z()}}async syncOAuthCredentials($,Z){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:Z?.forceRefresh})}catch(W){if(W instanceof H9)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let Z=this.sessions.get($);if(!Z){let Q=new P$($);throw i$(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return Z}resolveAbsoluteFilePaths($,Z){if(!Z||Z.length===0)return[];let Q=Z.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>AP(W)?W:W3($,W));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return q1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let Z=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=f0($.initialUsage,Z);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,Z,Q){let W=W3(Z),J=`${Q}.messages.json`,X;try{X=KP($)}catch{return _0()}let Y=_0();for(let j of X){if(!j.endsWith(".messages.json"))continue;if(j===J)continue;let V=W3($,j);if(V===W)continue;let H=await n1(V);if(H.length===0)continue;Y=f0(Y,l5(H))}return Y}withPersistedAggregateUsageFloor($,Z){let Q=_P(Z.metadata?.aggregateUsage);if(Q)return zP($,Q);let W=Z.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,Z){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:Z}})}async emitSessionSnapshot($){let Z=await this.getSession($);if(!Z)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:t1({session:Z,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($)),iG))}async getRow($){let Z=$.trim();if(!Z)return;return(await this.listRows(iG)).find((W)=>W.sessionId===Z)}async readManifest($){let Z=$.trim();if(!Z)return;return await this.invokeOptionalValue("readSessionManifest",Z)}invoke($,...Z){return dG(this.sessionService,$,...Z)}invokeOptional($,...Z){return lG(this.sessionService,$,...Z)}invokeOptionalValue($,...Z){return pG(this.sessionService,$,...Z)}}function TP($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let Z=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(Z==="local"||Z==="hub"||Z==="remote")return Z;return"auto"}var R4,E4;function OP($,Z){if($!=="auto"&&$!=="hub")return;if(Z.hub?.endpoint?.trim())return;bH(Z.hub?.workspaceRoot?.trim()||Z.hub?.cwd?.trim()||process.cwd())}async function qP($){await $.reconcileDeadSessions?.().catch(()=>{})}function sG($){try{let Z=new Z$;return Z.init(),new Q$(Z,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(Z){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),aG($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:Z,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new LW(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function nG($,Z,Q){return new j$({sessionService:Q??$.sessionService??sG($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:Z,fetch:$.fetch})}async function MP($){if(R4)return R4;if(E4)return await E4;return E4=(async()=>{return R4=sG($),await qP(R4),R4})().finally(()=>{E4=void 0}),await E4}async function G9($){let Z=m0($.distinctId);$.telemetry?.setDistinctId(Z);let Q=TP($);if(OP(Q,$),Q==="remote"){let W=$.remote?.endpoint?.trim();if(!W)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:W}),new C5({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let W=$.hub?.endpoint?.trim(),J=W||await X4({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:W||void 0}),new u$({url:J,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let W=await a7({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(W){$.logger?.log("Using discovered local hub runtime host",{url:W});let J=new u$({url:W,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(X){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:X}),aG($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:X,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),nG($,Z)}return nG($,Z)}import{execFile as RP}from"node:child_process";import*as tG from"node:fs/promises";import*as a2 from"node:path";import{promisify as EP}from"node:util";var NP=EP(RP),wP=52428800;async function K9($,Z){let{stdout:Q}=await NP("git",["-C",$,...Z],{windowsHide:!0,maxBuffer:wP,encoding:"utf8"});return Q}function oG($){return $.split("\x00").filter(Boolean)}function eG($,Z){let Q=a2.resolve($,Z),W=a2.relative($,Q);if(W.startsWith("..")||a2.isAbsolute(W))throw Error(`Checkpoint diff path escapes workspace: ${Z}`);return Q}async function CP($,Z,Q){try{return await K9($,["show",`${Z}:${Q}`])}catch{return""}}async function PP($,Z){try{return await tG.readFile(eG($,Z),"utf8")}catch{return""}}async function SP($,Z){await K9($,["cat-file","-e",`${Z.ref}^{tree}`]);let[Q,W]=await Promise.all([K9($,["diff","--name-only","-z",Z.ref,"--"]),K9($,["ls-files","--others","--exclude-standard","-z"])]);return[...new Set([...oG(Q),...oG(W)])].sort((X,Y)=>X.localeCompare(Y))}function $K($){let Z=$.checkpointRunCount;if(!Number.isInteger(Z)||Z<1)throw Error("checkpointRunCount must be a positive integer");let Q=J9(O4($.session),Z);if(!Q)throw Error(`No checkpoint found at or before run ${Z} in session ${$.session.sessionId}`);let W=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!W)throw Error("cwd or workspaceRoot is required to compare a checkpoint");return{checkpoint:Q,cwd:W}}async function ZK($,Z){let Q=await SP($,Z);return(await Promise.all(Q.map(async(J)=>{let[X,Y]=await Promise.all([CP($,Z.ref,J),PP($,J)]);return{filePath:eG($,J),leftContent:X,rightContent:Y}}))).filter((J)=>J.leftContent!==J.rightContent)}async function J3($){let Z=$K($),Q=await ZK(Z.cwd,Z.checkpoint);return{...Z,diffs:Q}}import{existsSync as bP,mkdirSync as yP,readFileSync as hP,writeFileSync as kP}from"node:fs";import{dirname as IP}from"node:path";import{FEATURE_FLAGS as QK,FeatureFlagDefaultValue as X3}from"@cline/shared";var xP=3600000,gP=604800000,WK=1;class N4{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??xP,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??gP,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 Z=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===Z)return}let W=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:Z||null};try{let J=await this.provider.getAllFlagsAndPayloads({flagKeys:QK.length>0?QK:void 0,context:{...this.context,userId:Z}});if(this.cacheInfo.userId!==Z)return;this.cacheInfo.flagsPayload=J,this.rebuildCacheFromSnapshot(J),this.writePersistentCache()}catch(J){if(this.cacheInfo.userId!==Z)return;throw this.cacheInfo=W.updateTime?W:{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((Z)=>this.isFeatureFlagPayload(Z));if(typeof $==="object")return Object.values($).every((Z)=>this.isFeatureFlagPayload(Z));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=Object.entries($).filter(([,W])=>this.isFeatureFlagPayload(W));if(Z.length===0)return;let Q={};for(let[W,J]of Z)Q[W]=J;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!bP(this.cacheFilePath))return;let $=JSON.parse(hP(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let Z=$;if(Z.version!==WK||typeof Z.updatedAt!=="number"||!Number.isFinite(Z.updatedAt)||Date.now()-Z.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:Z.updatedAt,userId:Z.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(Z.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(Z.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;yP(IP(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),Z={version:WK,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};kP(this.cacheFilePath,`${JSON.stringify(Z,null,2)}
716
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let Z=new Map;for(let Q of this.getReturnedFlagKeys($)){let W=this.getFeatureFlag(Q);Z.set(Q,W??!1)}this.cache=Z}getFeatureFlag($){try{let Z=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],W=Z??Q??X3[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==W)this.telemetry?.capture({event:I.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return W}catch(Z){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:Z}),X3[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??X3[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,Z){if(process.env.IS_TEST==="true")this.cache.set($,Z)}async dispose(){await this.provider.dispose()}}class w4{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}g2();class Y3{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,Z,Q,W,J,X,Y,j,V,H){this.clientName=Z,this.runtimeAddress=Q,this.host=$,this.prepare=W,this.capabilities=J,this.logger=X,this.telemetry=Y,this.distinctId=j,this.featureFlags=V,this.settings=SV($),this.pendingPrompts=bV($),this.automation=new mZ(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=H?new a8({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:GX(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:KX({host:$,getExtensionContext:()=>Y6({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:H.dbPath,logger:H.logger,pollIntervalMs:H.pollIntervalMs,claimLeaseSeconds:H.claimLeaseSeconds,globalMaxConcurrency:H.globalMaxConcurrency,watcherDebounceMs:H.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((B)=>{if(B.type!=="ended")return;this.disposeSessionBootstrap(B.payload.sessionId)})}static async create($={}){let Z=m0($.distinctId),Q=O0($.capabilities),W={...$,capabilities:Q,distinctId:Z},J=await G9(W),X=BX($.automation),Y=$.featureFlags||new N4({provider:new w4,telemetry:$.telemetry,logger:$.logger,context:{distinctId:Z,clientName:$.clientName}}),j=new Y3(J,$.clientName,J.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,Z,Y,X?{...X,logger:$.logger}:void 0);if(X&&X.autoStart!==!1)await j.automation.start();return j}async disposeSessionBootstrap($){let Z=this.activeSessionBootstraps.get($);if(!Z)return;this.activeSessionBootstraps.delete($),await Promise.resolve(Z.dispose?.())}async start($){let Z=yV($),Q=await this.prepare?.(Z);try{let W=Q?await Q.applyToStartSessionInput(Z):Z,J=await this.host.startSession(V7(W,{defaultCapabilities:this.capabilities,withExtensionContext:(X)=>Y6({automationService:this.automationService,automation:this.automation,context:X,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(J.sessionId))this.activeSessionBootstraps.set(J.sessionId,Q);else await Promise.resolve(Q.dispose?.());return hV({input:W,sessionId:J.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),J}catch(W){throw await Promise.resolve(Q?.dispose?.()),W}}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 Z=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(Z.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await v7(this.host,$);list=async($=200,Z={})=>await this.listHistory({...Z,limit:$});delete=async($)=>{let Z=await this.host.deleteSession($);if(Z)await this.disposeSessionBootstrap($);return Z};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let Z=$.start?V7($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>Y6({automationService:this.automationService,automation:this.automation,context:Q,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:Z})}async compareCheckpoint($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=await this.host.getSession(Z);if(!Q)throw Error(`Session ${Z} not found`);return J3({session:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,Z){return this.host.subscribe($,Z)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as XK,HookEventPayloadSchema as YK,parseHookEventPayload as A9,resolveHookSessionContext as pP}from"@cline/shared";import{z as n$}from"zod";import{spawn as mP}from"node:child_process";import{augmentNodeCommandForDebug as vP,withResolvedClineBuildEnv as cP}from"@cline/shared";function uP($){let Z=$.trim();if(!Z)return{};let W=Z.split(`
717
+ `).map((X)=>X.trim()).filter(Boolean).filter((X)=>X.startsWith("HOOK_CONTROL\t")).map((X)=>X.slice(13)),J=W.length>0?W[W.length-1]:Z;try{return{parsedJson:JSON.parse(J)}}catch(X){return{parseError:X instanceof Error?X.message:"Failed to parse subprocess stdout JSON"}}}function dP($,Z){let Q=$ instanceof Error?$:Error(String($)),W=Q,J=Z.join(" ");if(W.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}": ${Q.message}`)}async function lP($,Z){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,J)=>{let X=(Y)=>{Q.off("error",X);let j=Y.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}J(Y)};Q.once("error",X),Q.end(Z,(Y)=>{if(Q.off("error",X),Y){let j=Y.code;if(j==="EPIPE"||j==="ERR_STREAM_DESTROYED"){W();return}J(Y);return}W()})})}async function F9($,Z){let Q=vP(Z.command,{env:Z.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!Z.detached,J=mP(Q[0],Q.slice(1),{cwd:Z.cwd,env:cP(Z.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W,windowsHide:!0}),X=new Promise((K)=>{J.once("spawn",()=>{try{Z.onSpawn?.({command:Q,pid:J.pid??void 0,detached:W})}catch{}K()})}),Y=new Promise((K,F)=>{J.once("error",(A)=>{F(dP(A,Q))})});if(await lP(J,JSON.stringify($)),W){await Promise.race([X,Y]),J.unref();return}if(!J.stdout||!J.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let j="",V="",H=!1,B;J.stdout.on("data",(K)=>{j+=K.toString()}),J.stderr.on("data",(K)=>{V+=K.toString()});let G=new Promise((K)=>{if((Z.timeoutMs??0)>0)B=setTimeout(()=>{H=!0,J.kill("SIGKILL")},Z.timeoutMs);J.once("close",(F)=>{if(B)clearTimeout(B);let{parsedJson:A,parseError:L}=uP(j);K({exitCode:F,stdout:j,stderr:V,parsedJson:A,parseError:L,timedOut:H})})});return await Promise.race([G,Y])}var rP=n$.object({contextModification:n$.string().optional(),cancel:n$.boolean().optional(),review:n$.boolean().optional(),errorMessage:n$.string().optional(),context:n$.string().optional(),overrideInput:n$.unknown().optional()}).passthrough();var iP=["agent","hook"];async function f9($,Z={}){let Q=Z.command??iP;return await F9($,{command:Q,cwd:Z.cwd,env:Z.env,detached:Z.detached,timeoutMs:Z.timeoutMs,onSpawn:Z.onSpawn})}function jK($){return $ instanceof Error?$:Error(String($))}function nP($){if(!$||typeof $!=="object")return;let Z=rP.safeParse($);if(!Z.success)return;let Q=Z.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let J=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:J,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function JK($){if(!$||typeof $!=="object")return{};let Z={};for(let[Q,W]of Object.entries($))if(typeof W==="string")Z[Q]=W;else Z[Q]=JSON.stringify(W);return Z}function M1($,Z,Q){let W=Q.env??process.env,J=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",X=Q.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:Z.conversationId,sessionContext:pP(Q.sessionContext,{hookName:$,conversationId:Z.conversationId,agentId:Z.agentId,parentAgentId:Z.parentAgentId}),workspaceRoots:X?[X]:[],workspaceInfo:Q.workspaceInfo,userId:J,agent_id:Z.agentId,parent_agent_id:Z.parentAgentId}}function aP($){return{name:$.name,message:$.message,stack:$.stack}}function sP($){let Z=String($??"").toLowerCase();return Z.includes("cancel")||Z.includes("abort")||Z.includes("interrupt")}function oP($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function tP($){return $.filter((Z)=>Z.type==="text"&&typeof Z.text==="string").map((Z)=>Z.text).join("")}function eP($){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 $S($){if(!$)return;let Z={};if($.cancel===!0)Z.stop=!0;if($.overrideInput!==void 0)Z.input=$.overrideInput;return Object.keys(Z).length>0?Z:void 0}async function a$($,Z){try{let Q=await f9($,{command:Z.command,cwd:Z.cwd,env:Z.env,detached:!0,onSpawn:Z.onSpawn});Z.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){Z.onDispatchError?.(jK(Q),$)}}function VK($={}){return{hooks:{beforeRun:async(j)=>{let V=oP(j);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let B={...M1("agent_resume",V,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await a$(B,$)}else{let B={...M1("agent_start",V,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await a$(B,$)}return},beforeTool:async(j)=>{let V={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},H={...M1("tool_call",V,$),hookName:"tool_call",iteration:j.snapshot.iteration,tool_call:{id:j.toolCall.toolCallId,name:j.toolCall.toolName,input:j.input},preToolUse:{toolName:j.toolCall.toolName,parameters:JK(j.input)}};try{let B=await f9(H,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:H,result:B,detached:!1}),B?.timedOut)throw Error("tool_call hook command timed out");if(B?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${B.parseError}`);return $S(nP(B?.parsedJson))}catch(B){$.onDispatchError?.(jK(B),H);return}},afterTool:async(j)=>{let V=eP(j),H={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},B={...M1("tool_result",H,$),hookName:"tool_result",iteration:j.snapshot.iteration,tool_result:V,postToolUse:{toolName:V.name,parameters:JK(V.input),result:typeof V.output==="string"?V.output:JSON.stringify(V.output),success:!V.error,executionTimeMs:V.durationMs}};await a$(B,$);return},afterRun:async({snapshot:j,result:V})=>{let H={agentId:j.agentId,conversationId:j.conversationId??j.runId??j.agentId,parentAgentId:j.parentAgentId??null};if(V.status==="completed"){let K={...M1("agent_end",H,$),hookName:"agent_end",iteration:V.iterations,turn:{outputText:V.outputText,status:V.status},taskComplete:{taskMetadata:{}}};await a$(K,$);return}let B=V.status==="aborted"||sP(V.error?.message)?"agent_abort":"agent_error",G=B==="agent_error"?{...M1(B,H,$),hookName:B,iteration:V.iterations,error:aP(V.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...M1(B,H,$),hookName:B,reason:V.error?.message,taskCancel:{taskMetadata:{}}};await a$(G,$)},onEvent:async(j)=>{if(j.type!=="message-added"||j.message.role!=="user")return;let V={agentId:j.snapshot.agentId,conversationId:j.snapshot.conversationId??j.snapshot.runId??j.snapshot.agentId,parentAgentId:j.snapshot.parentAgentId??null},H={...M1("prompt_submit",V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:tP(j.message.content),attachments:[]}};await a$(H,$)}},shutdown:async({agentId:j,conversationId:V,parentAgentId:H,reason:B})=>{let G={...M1("session_shutdown",{agentId:j,conversationId:V,parentAgentId:H},$),hookName:"session_shutdown",reason:B};await a$(G,$)}}}import{createSessionId as ZS}from"@cline/shared";function c0($,Z){return{version:$.version,requestId:$.requestId,ok:!0,payload:Z}}function HK($,Z,Q){return{version:$.version,requestId:$.requestId??ZS("hubreq_"),ok:!1,error:{code:Z,message:Q}}}class U9{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return c0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return c0($,{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 c0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return c0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return c0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return c0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return c0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return c0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return c0($,{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 c0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return c0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return c0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return HK($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(Z){return HK($,"schedule_command_failed",Z instanceof Error?Z.message:String(Z))}}toCreateInput($){let Z=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:Z}}toUpdateInput($){let Z=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:Z}}}function L9($){return $?new Date($).getTime():void 0}function QS($){let Z=$.metadata?{...$.metadata}:void 0;if(Z)delete Z.__hubScheduleCreatedBy,delete Z.__hubScheduleCwd,delete Z.__hubRuntimeOptions;return Z}function D9($){let Z=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof Z?.__hubScheduleCwd==="string"?Z.__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:L9($.nextRunAt),lastRunAt:L9($.lastRunAt),createdBy:typeof Z?.__hubScheduleCreatedBy==="string"?Z.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:Z?.__hubRuntimeOptions&&typeof Z.__hubRuntimeOptions==="object"&&!Array.isArray(Z.__hubRuntimeOptions)?Z.__hubRuntimeOptions:void 0,metadata:QS($)}}function WS($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function j3($,Z){return{executionId:$.runId,scheduleId:Z,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:L9($.startedAt),endedAt:L9($.completedAt),status:WS($.status),errorMessage:$.error}}class _9{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new n8({dbPath:$.dbPath}),this.materializer=new d8({store:this.store}),this.runner=new l8({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(_7($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return D9(this.store.createHubSchedule($))}getSchedule($){let Z=this.store.getHubSchedule($);return Z?D9(Z):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((Z)=>D9(Z))}updateSchedule($,Z){if(Z.cronPattern!==void 0)_7(Z.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let W=Z.workspaceRoot!==void 0?Z.workspaceRoot.trim():Q.workspaceRoot;if((Z.enabled??Q.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let X=this.store.updateHubSchedule($,{...Z,scheduleId:$});return X?D9(X):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let Z=this.store.enqueueHubScheduleRun($,"manual");if(!Z)return;await this.runner.tick();let Q=this.store.getRun(Z.runId)??Z;return j3(Q,$)}triggerScheduleNowDetached($){let Z=this.store.enqueueHubScheduleRun($,"manual");if(!Z)return;return this.runner.tick().catch(()=>{return}),j3(Z,$)}listScheduleExecutions($){let Z=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:Z?.specId,limit:$.limit};return this.store.listRuns(Q).map((J)=>{let X=Z??this.store.getSpec(J.specId);if(!X||X.source!=="hub-schedule")return;return j3(J,X.externalId)}).filter((J)=>{if(!J)return!1;return!$.status||J.status===$.status})}getScheduleStats($){let Z=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(Z.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,W=0,J=0,X;for(let Y of Z){if(Y.status==="success"||Y.status==="completed")Q+=1;if(!X&&Y.status!=="success"&&Y.status!=="completed")X=Y;if(Y.startedAt&&Y.endedAt)J+=Y.endedAt-Y.startedAt,W+=1}return{totalRuns:Z.length,successRate:Q/Z.length,avgDurationSeconds:W>0?J/W/1000:0,lastFailure:X}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let Z=this.store.getSpec($.specId);if(!Z||Z.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:Z.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:Z.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+Z.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let Z={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(Z).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,W)=>String(Q.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:W})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:W}))}}q9();import{resolveClineBuildEnv as ES}from"@cline/shared";function NS($,Z){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${Z} (${Q} event before socket open).`:`Failed to connect to hub at ${Z}.`)}var wS="cline-hub-auth.";function CS($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function PS($,Z){let Q=new URL($),W=new URL(Z);return Q.search="",Q.hash="",W.search="",W.hash="",Q.toString()===W.toString()}function KK(){return ES()==="production"?s1():_1()}async function SS($){let Z=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),Z)return Z;let Q=KK(),W=await A0(Q.discoveryPath);if(W?.url&&PS($.toString(),W.url))return W.authToken;return}async function bS($={}){let Z=a1($);if(!CS($)){let Q=KK(),W=await A0(Q.discoveryPath);if(W?.url)return W.url}return L1(Z.host,Z.port,Z.pathname)}async function FK($){return await new Promise((Z,Q)=>{(async()=>{let W=new URL($),J=await SS(W);W.hash="";let X=new WebSocket(W.toString(),J?[`${wS}${J}`]:void 0),Y=new Map,j=0;X.addEventListener("open",()=>{Z({send(V){let H=V.requestId??`hub-client-${++j}`;return new Promise((B,G)=>{Y.set(H,{resolve:B,reject:G});let K={kind:"command",envelope:{...V,requestId:H}};X.send(JSON.stringify(K))})},close(){X.close()}})}),X.addEventListener("message",(V)=>{let H=JSON.parse(String(V.data));if(H.kind==="reply"&&H.envelope.requestId){let B=Y.get(H.envelope.requestId);if(B)Y.delete(H.envelope.requestId),B.resolve(H.envelope)}}),X.addEventListener("close",()=>{for(let V of Y.values())V.reject(Error("Hub connection closed"));Y.clear()}),X.addEventListener("error",(V)=>{Q(NS(V,$))})})().catch(Q)})}async function ds($){try{return(await FK($)).close(),!0}catch{return!1}}async function ls($,Z){let Q=await bS($),W=await FK(Q);try{return await W.send({version:Z.version??"v1",clientId:Z.clientId??"hub-client",...Z})}finally{W.close()}}function G3($){return $?JSON.parse(JSON.stringify($)):{}}function M9($){let Z=$?.session&&typeof $.session==="object"?$.session:void 0;if(!Z)return;let Q=Z.metadata&&typeof Z.metadata==="object"?G3(Z.metadata):void 0;return{sessionId:typeof Z.sessionId==="string"?Z.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function AK($,Z){return $.error?.message??`hub command failed: ${Z}`}function yS($){let Z=G3($);if(typeof Z.error==="string"&&Z.error.trim())return{...Z,error:Z.error.trim()};let Q=Z.result&&typeof Z.result==="object"?Z.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...Z,error:Q.text.trim()};let W=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...Z,error:W.message.trim()};return Z}function fK($){let Z=$?.sessionId;return typeof Z==="string"&&Z.trim()?Z.trim():void 0}function hS($){let Z=$?.checkpoint;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error("hub checkpoint restore returned no checkpoint");let Q=Z;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function kS($){let Z=G3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||fK(Z)||"",eventType:"schedule.execution.completed",payload:Z};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||fK(Z)||"",eventType:"schedule.execution.failed",payload:Z};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:Z};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:Z};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:Z};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:Z};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:Z};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:Z};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:Z};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:Z};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:yS($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:Z};default:return}}class IS{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new z1({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 Z=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=M9(Z.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,Z,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:Z.prompt,mode:Z.config.mode,attachments:Z.attachments,delivery:Z.delivery,timeoutSeconds:Z.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let Z;try{Z=await this.client.command("session.get",void 0,$)}catch(Q){if(S$(Q))return;throw Q}return M9(Z.payload)}async readMessages($){let Z=$.trim();if(!Z)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:Z},Z);if(!Q.ok)throw Error(AK(Q,"session.messages"));let W=Q.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let Z=$.sessionId.trim();if(!Z)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,J=await this.client.command("session.restore",{sessionId:Z,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.workspaceRoot,cwd:W.cwd,sessionConfig:{providerId:W.provider,modelId:W.model,apiKey:W.apiKey,cwd:W.cwd??W.workspaceRoot,workspaceRoot:W.workspaceRoot,systemPrompt:W.systemPrompt??"",mode:W.mode??"act",rules:W.rules,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawnAgent:W.enableSpawn!==!1,enableAgentTeams:W.enableTeams!==!1,disableMcpSettingsTools:W.disableMcpSettingsTools,missionLogIntervalSteps:W.missionStepInterval,missionLogIntervalMs:W.missionTimeIntervalMs},metadata:{source:W.source??"cli",provider:W.provider,model:W.model,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,prompt:void 0,interactive:W.interactive!==!1},runtimeOptions:{mode:W.mode,systemPrompt:W.systemPrompt,maxIterations:W.maxIterations,enableTools:W.enableTools,enableSpawn:W.enableSpawn,enableTeams:W.enableTeams,autoApproveTools:W.autoApproveTools,configExtensions:W.configExtensions},modelSelection:{provider:W.provider,model:W.model,apiKey:W.apiKey},toolPolicies:W.toolPolicies}:{}},Z);if(!J.ok)throw Error(AK(J,"session.restore"));let X=M9(J.payload);if(Q&&!X?.sessionId)throw Error("hub checkpoint restore returned no session id");let Y=Array.isArray(J.payload?.messages)?J.payload.messages:void 0,j=hS(J.payload);return{sessionId:X?.sessionId,startResult:X?.sessionId?{sessionId:X.sessionId,manifestPath:"",messagesPath:X.messagesPath??""}:void 0,...Y?{messages:Y}:{},checkpoint:j}}async listSessions($){await this.ensureMetadataApplied();let Z=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(Z.payload?.sessions)?Z.payload?.sessions:[]).map((W)=>M9({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,Z=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:Z})).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($,Z){let Q=new Set(($.sessionIds??[]).map((J)=>J.trim()).filter(Boolean)),W=this.client.subscribe((J)=>{let X=kS(J);if(!X)return;if(Q.size>0&&!Q.has(X.sessionId))return;Z.onEvent?.(X)});return this.ensureMetadataApplied().catch((J)=>{Z.onError?.(J instanceof Error?J:Error(String(J)))}),W}streamTeamProgress($,Z){let Q=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;Z.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{Z.onError?.(W instanceof Error?W:Error(String(W)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.list");return Array.isArray(Z.payload?.schedules)?Z.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,Z){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...Z})).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($,Z){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:Z});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let Z=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(Z.payload?.upcoming)?Z.payload?.upcoming:[]}}class xS{client;constructor($){this.client=new z1({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 Z=await this.client.command("session.list",{limit:$});return Array.isArray(Z.payload?.sessions)?Z.payload.sessions:[]}subscribeUI($){return this.client.subscribe((Z)=>{switch(Z.event){case"ui.notify":$.onNotify?.(Z.payload);break;case"ui.show_window":$.onShowWindow?.(Z.payload);break;case"hub.client.registered":$.onClientRegistered?.(Z.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(Z.payload??{});break;case"session.created":$.onSessionCreated?.(Z.payload??{});break;case"session.updated":$.onSessionUpdated?.(Z.payload??{});break;case"session.detached":$.onSessionDetached?.(Z.payload??{});break}})}}import{normalizeProviderId as gS}from"@cline/llms";function mS($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((Z)=>({name:Z.name,input:Z.input,output:Z.output,error:Z.error,durationMs:Z.durationMs}))}}function vS($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function Qo($={}){let Z=new j$({sessionService:new Q$(new Z$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let W=(Q.cwd?.trim()||Q.workspaceRoot).trim(),J=await Z.startSession({source:Q.source?.trim()||T0.CLI,interactive:!1,config:{providerId:gS(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:W,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:vS(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:J.manifestPath,messagesPath:J.messagesPath}}},async sendSession(Q,W){let J=await Z.runTurn({sessionId:Q,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((X)=>X.content)});if(!J)throw Error("local hub schedule runtime returned no turn result");return{result:mS(J)}},async abortSession(Q){return await Z.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await Z.stopSession(Q),{applied:!0}}}}import{resolveClineBuildEnv as UF}from"@cline/shared";function cS($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
718
+ `).trim()||void 0}var UK=120,K3="...";function F3($){let Z=$.trim();if(!Z)return"";if(Buffer.byteLength(Z,"utf8")<=UK)return Z;let Q=UK-Buffer.byteLength(K3,"utf8");if(Q<=0)return K3;let W="";for(let J of Z){if(Buffer.byteLength(W+J,"utf8")>Q)break;W+=J}return`${W}${K3}`}async function DK($){let Z=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,J=[...await n1(Q)].reverse().find((V)=>V.role==="assistant"),X=J?cS(J.content):void 0,Y=$?.workspaceRoot?.trim()||"workspace",j=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():Y;return{title:`Task completed (${Z})`,body:F3(X&&X.length>0?X:j.length>0?j:Y),severity:"info"}}import{captureSdkError as C9,createSessionId as mb}from"@cline/shared";import{createSessionId as pS}from"@cline/shared";import{createSessionId as lS}from"@cline/shared";function uS($){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 dS($){let Z=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())Z.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())Z.parentAgentId=$.parentAgentId;if($.agentId?.trim())Z.agentId=$.agentId;if($.conversationId?.trim())Z.conversationId=$.conversationId;if($.messagesPath?.trim())Z.messagesPath=$.messagesPath;if($.prompt?.trim())Z.prompt=$.prompt;if($.provider?.trim())Z.provider=$.provider;if($.model?.trim())Z.model=$.model;if($.source?.trim())Z.source=$.source;if(typeof $.pid==="number")Z.pid=$.pid;return Object.keys(Z).length>0?Z:void 0}function R9($,Z,Q,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:Z?.createdByClientId??"hub",status:uS($.status),participants:Z?[...Z.participants.values()]:[],metadata:dS($),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,...Q?{usage:{...Q}}:{},...W?{aggregateUsage:{...W}}:{}}}function g($,Z){return{version:$.version,requestId:$.requestId,ok:!0,...Z!==void 0?{payload:Z}:{}}}function h($,Z,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:Z,message:Q}}}function E9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function C0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function o$($,Z,Q){return{version:"v1",event:$,eventId:lS("hevt_"),sessionId:Q,timestamp:Date.now(),payload:Z}}async function u0($,Z){let Q=await $.sessionHost.getSession(Z);if(!Q)return;let W=await $.sessionHost.getAccumulatedUsage?.(Z);return R9(Q,$.sessionState.get(Z),W?.usage,W?.aggregateUsage)}async function d0($,Z){let Q=await $.sessionHost.getSession(Z);if(!Q)return;let[W,J]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(Z):[],$.sessionHost.getAccumulatedUsage?.(Z)]);return t1({session:Q,messages:W,usage:J?.usage,aggregateUsage:J?.aggregateUsage})}function N9($,Z,Q,W,J={}){let X=$.sessionState.get(Z);if(X){if(J.interactive!==void 0)X.interactive=J.interactive;if(!X.participants.has(Q))X.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:W});return X}let Y={createdByClientId:Q,interactive:J.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(Z,Y),Y}async function A3($,Z){let Q=pS("approval_"),W=Z.sessionId;if($.sessionState.get(W)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((X)=>{$.pendingApprovals.set(Q,{sessionId:W,resolve:X}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:Z.sessionId,agentId:Z.agentId,conversationId:Z.conversationId,iteration:Z.iteration,toolCallId:Z.toolCallId,toolName:Z.toolName,inputJson:JSON.stringify(Z.input??null),policy:Z.policy},W))})}function f3($,Z,Q){let W=$.pendingApprovals.get(Z);if(!W)return;return $.pendingApprovals.delete(Z),W.resolve(Q),{sessionId:W.sessionId}}function U3($,Z,Q){let W=0;for(let[J,X]of[...$.pendingApprovals.entries()]){if(!Z({approvalId:J,sessionId:X.sessionId}))continue;$.pendingApprovals.delete(J),X.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:J,approved:!1,cancelled:!0,reason:Q},X.sessionId)),W+=1}return W}async function LK($,Z){let Q=typeof Z.payload?.approvalId==="string"?Z.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return h(Z,"approval_not_found",`Unknown approval: ${Q}`);let J=typeof Z.payload?.reason==="string"?Z.payload.reason:Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)&&typeof Z.payload.payload.reason==="string"?Z.payload.payload.reason:void 0,X=Z.payload?.approved===!0,Y=f3($,Q,{approved:X,reason:J});if(!Y)return h(Z,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:X,reason:J},Y.sessionId)),g(Z,{approvalId:Q,approved:X})}import{createSessionId as nS}from"@cline/shared";function rS($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var _K={debug:10,info:20,warn:30,error:40,silent:50};function iS(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function m($,Z,Q={}){if(_K[$]<_K[iS()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:Z,...Object.fromEntries(Object.entries(Q).map(([J,X])=>[J,rS(X)]).filter(([,J])=>J!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function D3($,Z){let Q=Z instanceof Error?Z.stack||Z.message:String(Z);m("error",$,{error:Q})}async function zK($,Z,Q,W,J,X){let Y=nS("capreq_"),j=performance.now();return m("info","capability.request.start",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J}),await new Promise((V,H)=>{$.pendingCapabilityRequests.set(Y,{sessionId:Z,targetClientId:J,capabilityName:Q,onProgress:X,resolve:(B)=>{if(m(B.ok?"info":"warn","capability.request.end",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J,ok:B.ok,error:B.error,durationMs:Math.round(performance.now()-j)}),!B.ok){H(Error(B.error||`Capability ${Q} was rejected by ${J}.`));return}V(B.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:Y,targetClientId:J,capabilityName:Q,payload:W},Z)),m("info","capability.request.published",{requestId:Y,sessionId:Z,capabilityName:Q,targetClientId:J})})}function TK($,Z){let Q=typeof Z.payload?.requestId==="string"?Z.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(Q);if(!W)return h(Z,"capability_not_found",`Unknown capability request: ${Q}`);if((Z.clientId?.trim()||"")!==W.targetClientId)return h(Z,"capability_wrong_client",`Capability request ${Q} is owned by ${W.targetClientId}`);if(Z.sessionId?.trim()&&Z.sessionId.trim()!==W.sessionId)return h(Z,"capability_wrong_session",`Capability request ${Q} belongs to session ${W.sessionId}`);let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:{};return W.onProgress?.(X),g(Z,{requestId:Q})}function V$($,Z,Q){let W=0;for(let[J,X]of[...$.pendingCapabilityRequests.entries()]){if(!Z({requestId:J,...X}))continue;$.pendingCapabilityRequests.delete(J),m("warn","capability.request.cancelled",{requestId:J,sessionId:X.sessionId,capabilityName:X.capabilityName,targetClientId:X.targetClientId,reason:Q}),X.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:X.capabilityName,targetClientId:X.targetClientId,ok:!1,cancelled:!0,error:Q},X.sessionId)),W+=1}return W}async function OK($,Z){let Q=typeof Z.payload?.sessionId==="string"?Z.payload.sessionId.trim():Z.sessionId?.trim()||"",W=typeof Z.payload?.capabilityName==="string"?Z.payload.capabilityName.trim():"",J=typeof Z.payload?.targetClientId==="string"?Z.payload.targetClientId.trim():"";if(!Q||!W||!J)return h(Z,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:{},Y=await $.requestCapability(Q,W,X,J);return g(Z,Y)}catch(X){return h(Z,"capability_request_failed",X instanceof Error?X.message:String(X))}}function qK($,Z){let Q=typeof Z.payload?.requestId==="string"?Z.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(Q);if(!W)return h(Z,"capability_not_found",`Unknown capability request: ${Q}`);let J=Z.clientId?.trim()||"";if(J!==W.targetClientId)return h(Z,"capability_wrong_client",`Capability request ${Q} is owned by ${W.targetClientId}`);if(Z.sessionId?.trim()&&Z.sessionId.trim()!==W.sessionId)return h(Z,"capability_wrong_session",`Capability request ${Q} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(Q);let X=Z.payload?.payload&&typeof Z.payload.payload==="object"&&!Array.isArray(Z.payload.payload)?Z.payload.payload:void 0,Y=typeof Z.payload?.error==="string"?Z.payload.error:void 0,j=Z.payload?.ok===!0;return m(j?"info":"warn","capability.respond",{requestId:Q,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:J,ok:j,error:Y}),W.resolve({ok:j,payload:X,error:Y}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:J,ok:j,payload:X,error:Y},W.sessionId)),g(Z,{requestId:Q,ok:j})}import{createSessionId as aS}from"@cline/shared";function MK($,Z){let Q=Z.payload,W=Q?.clientId?.trim()||Z.clientId?.trim()||aS("client_");return $.clients.set(W,{clientId:W,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),g(Z,{clientId:W})}function RK($,Z){let Q=Z.clientId?.trim(),W=Q?$.clients.get(Q):void 0;if(!Q||!W)return h(Z,"client_not_found","Client is not registered with this hub.");let J=E9(Z.payload?.metadata);if(W.lastSeenAt=Date.now(),J)W.metadata=JSON.parse(JSON.stringify(J));return g(Z)}function EK($,Z,Q){let W=Z.clientId?.trim();if(W)$.clients.delete(W),Q(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return g(Z)}function NK($,Z){return g(Z,{clients:[...$.clients.values()]})}G0();import{existsSync as PK,mkdirSync as sS,readdirSync as oS,readFileSync as tS,rmSync as eS,writeFileSync as $b}from"node:fs";import{dirname as Zb,join as wK}from"node:path";import{CONNECTOR_PLATFORMS as Qb,connectorChannelsFromPlatforms as Wb,listConnectorCatalog as SK,shouldIncludeConnectorField as Jb}from"@cline/shared";import{resolveConnectorDataDir as Xb,resolveConnectorSettingsPath as _3}from"@cline/shared/storage";var Yb=1,CK={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},jb={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 H$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function b4($){return typeof $==="string"?$.trim():void 0}function bK($){if(!PK($))return;try{let Z=JSON.parse(tS($,"utf8"));return H$(Z)?Z:void 0}catch{return}}function z3(){let $=bK(_3()),Z=H$($?.connectors)?$.connectors:{},Q={};for(let[W,J]of Object.entries(Z)){if(!H$(J))continue;let X=b4(J.type),Y=b4(J.configuredAt),j=b4(J.updatedAt);if(!X||!Y||!j)continue;let V=w9(J.values),H=H$(J.security)?{enabled:J.security.enabled===!0,values:w9(J.security.values)}:void 0;Q[W]={type:X,values:V,security:H,configuredAt:Y,updatedAt:j}}return{version:Yb,connectors:Q}}function yK($){let Z=_3();sS(Zb(Z),{recursive:!0}),$b(Z,`${JSON.stringify($,null,2)}
719
+ `,"utf8")}function w9($){if(!H$($))return{};let Z={};for(let[Q,W]of Object.entries($))if(typeof W==="string")Z[Q]=W.trim();return Z}function Vb($){if(!Number.isInteger($)||$<=0)return!1;try{return process.kill($,0),!0}catch{return!1}}function Hb($){let Z=wK(Xb(),$);if(!PK(Z))return[];return oS(Z).filter((Q)=>Q.endsWith(".json")&&!Q.endsWith(".threads.json")).map((Q)=>wK(Z,Q))}function Bb($,Z,Q){let W=Z.botUsername??Z.userName??Z.applicationId??Z.phoneNumberId??String(Q);return`${$}:${W}`}function Gb($,Z){let Q=bK(Z);if(!Q)return;let W=typeof Q.pid==="number"?Q.pid:void 0,J=typeof Q.hubUrl==="string"?Q.hubUrl:typeof Q.rpcAddress==="string"?Q.rpcAddress:void 0;if(!W||!J||!Vb(W))return;let X=jb[$];if(!X)return;let Y={};for(let j of X.required){let V=CK[j](Q);if(!V||typeof V==="string"&&!V.trim())return;Y[j]=V}for(let j of X.optional){let V=CK[j](Q);if(V!==void 0)Y[j]=V}return{id:Bb($,Y,W),type:$,pid:W,hubUrl:J,...Y}}function Kb(){let $=[];for(let{name:Z}of SK())for(let Q of Hb(Z)){let W=Gb(Z,Q);if(W)$.push(W)}return $.sort((Z,Q)=>{if(Z.type!==Q.type)return Z.type.localeCompare(Q.type);let W=Z.botUsername??Z.userName??"",J=Q.botUsername??Q.userName??"";return W.localeCompare(J)})}function Fb(){let $=z3();return Object.entries($.connectors).map(([Z,Q])=>({id:Z,type:Q.type,configuredAt:Q.configuredAt,updatedAt:Q.updatedAt})).sort((Z,Q)=>Z.type.localeCompare(Q.type))}function T3(){return{available:Wb(),active:Kb(),configured:Fb()}}function Ab($,Z){if($.required&&!Z[$.flag]?.trim())throw Error(`${$.label} is required`)}function fb($,Z){let Q={};for(let J of $.fields)Q[J.flag]=Z[J.flag]??J.initialValue??"";let W={};for(let J of $.fields){if(!Jb(J,Q))continue;Ab(J,Q),W[J.flag]=Q[J.flag]}return W}function Ub($){if(!H$($))throw Error("connector.configure payload must be an object.");let Z=b4($.channel);if(!Z)throw Error("channel is required");let Q=Qb.find((K)=>K.id===Z);if(!Q)throw Error(`unknown connector channel: ${Z}`);if(!new Set(SK().map((K)=>K.name)).has(Q.id))throw Error(`connector channel is not available: ${Z}`);let J=w9($.values),X=fb(Q,J),Y=H$($.security)?$.security:{},j=Y.enabled===!0,V=w9(Y.values);if(j&&Q.security)for(let K of Q.security.fields){let F=V[K.key];if(!F)throw Error(K.requiredMessage);let A=K.validate?.(F);if(A)throw Error(A)}let H=z3(),B=new Date().toISOString(),G=H.connectors[Z];return H.connectors[Z]={type:Z,values:X,security:j?{enabled:!0,values:V}:{enabled:!1,values:{}},configuredAt:G?.configuredAt??B,updatedAt:B},yK(H),T3()}function Db($){if(!H$($))throw Error("connector.delete_config payload must be an object.");let Z=b4($.channel);if(!Z)throw Error("channel is required");let Q=z3();if(delete Q.connectors[Z],Object.keys(Q.connectors).length>0)yK(Q);else eS(_3(),{force:!0});return T3()}function Lb($){return $==="connector.configure"||$==="connector.delete_config"}function L3($,Z,Q){if(!Lb(Z.command))return;Q8($.telemetry,{ulid:Z.sessionId??Z.requestId??"hub",tool:Z.command,success:Q})}async function hK($,Z){try{if(Z.command==="connector.channels")return g(Z,T3());if(Z.command==="connector.configure"){let Q=Ub(Z.payload);return L3($,Z,!0),g(Z,Q)}if(Z.command==="connector.delete_config"){let Q=Db(Z.payload);return L3($,Z,!0),g(Z,Q)}return h(Z,"unsupported_connector_command",`unsupported connector command: ${Z.command}`)}catch(Q){return L3($,Z,!1),h(Z,"connector_command_failed",Q instanceof Error?Q.message:String(Q))}}var _b=30000;function zb($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function Tb($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function Ob($,Z,Q){let W=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${Z}`;return h($,c8,W)}function qb($){return $?$:void 0}function Mb($){let Z=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(Z&&Number.isFinite(Z)&&Z>0)return Math.floor(Z);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function Rb($,Z,Q,W){let J=performance.now(),X=!1,Y={command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Q.sessionId,timeoutMs:W},j=setInterval(()=>{if(X)return;let B=Math.round(performance.now()-J);m("warn","run.heartbeat",{...Y,elapsedMs:B}),$.publish($.buildEvent("run.heartbeat",{requestId:Z.requestId,elapsedMs:B,...W?{timeoutMs:W}:{}},Q.sessionId))},_b),V=$.sessionHost.runTurn(Q);V.then((B)=>{if(!X)return;m("warn","run.late_end",{...Y,elapsedMs:Math.round(performance.now()-J),finishReason:B?.finishReason})},(B)=>{if(!X)return;m("error","run.late_error",{...Y,elapsedMs:Math.round(performance.now()-J),error:B})});let H;try{if(!W)return await V;return await Promise.race([V,new Promise((B,G)=>{H=setTimeout(()=>{let K=`Hub run ${Z.command} timed out after ${W}ms.`;X=!0,clearInterval(j),G(Error(K)),m("error","run.timeout",{...Y,elapsedMs:Math.round(performance.now()-J)}),U3($,(F)=>F.sessionId===Q.sessionId,K),V$($,(F)=>F.sessionId===Q.sessionId,K),$.sessionHost.abort(Q.sessionId,K).catch((F)=>{m("error","run.timeout_abort_failed",{...Y,error:F})})},W)})])}finally{if(X=!0,clearInterval(j),H)clearTimeout(H)}}async function kK($,Z){let Q=C0(Z),W=Z.payload&&typeof Z.payload==="object"?Z.payload:{},J=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!J.trim())return h(Z,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let X=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,Y=Array.isArray(X?.userFiles)?X.userFiles.filter((B)=>typeof B==="string"):void 0,j=Mb(W);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let V;try{V=await Rb($,Z,{sessionId:Q,prompt:J,mode:qb(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(X?.userImages)?X.userImages:void 0,userFiles:Y,timeoutMs:j},j)}catch(B){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(S$(B))return Ob(Z,Q,B);throw $.publish($.buildEvent("run.failed",{reason:"error",error:B instanceof Error?B.message:String(B)},Q)),B}if(V){let B=await d0($,Q),G=Tb(V);if($.publish($.buildEvent(zb(V.finishReason),{reason:V.finishReason,...G?{error:G}:{},result:V,...B?{snapshot:B}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let H=await d0($,Q);return g(Z,V||H?{...V?{result:V}:{},...H?{snapshot:H}:{}}:void 0)}async function IK($,Z){let Q=C0(Z),W=typeof Z.payload?.reason==="string"?Z.payload.reason:"Run was aborted before pending approval or capability request was resolved.";U3($,(J)=>J.sessionId===Q,W);try{await $.sessionHost.abort(Q,Z.payload?.reason)}catch(J){m("warn","run.abort_failed",{command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Q,error:J})}finally{V$($,(J)=>J.sessionId===Q,W)}return g(Z,{applied:!0})}async function xK($,Z){let Q=A9(Z.payload?.payload);if(!Q)return h(Z,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),g(Z,{applied:!0})}async function gK($,Z){switch(Z.type){case"chunk":return;case"agent_event":await Eb($,Z);return;case"hook":if(Z.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:Z.payload.toolName},Z.payload.sessionId));else if(Z.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:Z.payload.toolName},Z.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:Z.payload.sessionId,summary:Z.payload.summary,lastEvent:Z.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,Z.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:Z.payload.sessionId,prompts:Z.payload.prompts},Z.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:Z.payload.id,prompt:Z.payload.prompt,delivery:Z.payload.delivery,attachmentCount:Z.payload.attachmentCount,userImages:Z.payload.userImages,userFiles:Z.payload.userFiles};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:Z.payload.sessionId,prompt:Q},Z.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:Z.payload.sessionId,snapshot:Z.payload.snapshot},Z.payload.sessionId));return;case"status":{let[Q,W]=await Promise.all([u0($,Z.payload.sessionId),d0($,Z.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...W?{snapshot:W}:{}},Z.payload.sessionId));return}case"ended":await Nb($,Z);return;default:return}}async function Eb($,Z){let{sessionId:Q,event:W}=Z.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},Q));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},Q));return}if(W.type==="content_start"){if(W.contentType==="text"&&typeof W.text==="string"&&W.text.length>0){$.publish($.buildEvent("assistant.delta",{text:W.text},Q));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},Q));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},Q));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},Q));break}return}if(W.type==="usage"){let J;try{J=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{J=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:W.inputTokens,outputTokens:W.outputTokens,cacheReadTokens:W.cacheReadTokens??0,cacheWriteTokens:W.cacheWriteTokens??0,totalCost:W.cost??0},totals:{inputTokens:W.totalInputTokens,outputTokens:W.totalOutputTokens,cacheReadTokens:W.totalCacheReadTokens??0,cacheWriteTokens:W.totalCacheWriteTokens??0,totalCost:W.totalCost??0},usage:J?.usage,aggregateUsage:J?.aggregateUsage,agent:{kind:Z.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:Z.payload.teamAgentId,teamRole:Z.payload.teamRole}},Q));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},Q))}async function Nb($,Z){let Q=$.suppressNextTerminalEventBySession.get(Z.payload.sessionId),W=Q===Z.payload.reason||Q==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(Z.payload.sessionId);let[J,X]=await Promise.all([u0($,Z.payload.sessionId),d0($,Z.payload.sessionId)]);if(Z.payload.reason==="completed"){let Y=await DK(J);$.publish($.buildEvent("ui.notify",Y,Z.payload.sessionId))}if(W)return;$.publish($.buildEvent(Z.payload.reason==="aborted"?"run.aborted":Z.payload.reason==="error"||Z.payload.reason==="failed"?"run.failed":"run.completed",{reason:Z.payload.reason,...X?{snapshot:X}:{}},Z.payload.sessionId))}import{createSessionId as cK,parseRuntimeConfigExtensions as uK}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as vo,HUB_COMPACTION_CAPABILITY as co,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as uo,HUB_HOOK_CAPABILITY_PREFIX as lo,HUB_MISTAKE_LIMIT_CAPABILITY as po,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ro,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as io,isHubToolExecutorName as wb}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as to,HUB_COMPACTION_CAPABILITY as eo,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as $t,HUB_HOOK_CAPABILITY_PREFIX as Zt,HUB_MISTAKE_LIMIT_CAPABILITY as Qt,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Wt,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Jt}from"@cline/shared";var Cb=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function t$($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function Pb($,Z){let Q=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",J=typeof $.capabilityName==="string"?$.capabilityName.trim():"",X=t$($.inputSchema);if(!Q||!W||!X||!J||Z.has(J))return;return Z.add(J),{kind:"tool",capabilityName:J,name:Q,description:W,inputSchema:X,...t$($.lifecycle)?{lifecycle:t$($.lifecycle)}:{}}}function q3($){if(!Array.isArray($))return[];let Z=[],Q=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let J=W,X=J.kind,Y=typeof J.capabilityName==="string"?J.capabilityName.trim():"";if(!Y||Q.has(Y))continue;if(X==="tool"){let j=Pb(J,Q);if(j)Z.push(j);continue}if(X==="toolExecutor"){let j=J.executor;if(!wb(j))continue;Q.add(Y),Z.push({kind:"toolExecutor",capabilityName:Y,executor:j});continue}if(X==="hook"){let j=typeof J.name==="string"?J.name.trim():"";if(!j)continue;Q.add(Y),Z.push({kind:"hook",capabilityName:Y,name:j});continue}if(X==="compaction"){Q.add(Y),Z.push({kind:"compaction",capabilityName:Y,...t$(J.config)?{config:t$(J.config)}:{}});continue}if(X==="checkpoint"){Q.add(Y),Z.push({kind:"checkpoint",capabilityName:Y,...t$(J.config)?{config:t$(J.config)}:{}});continue}if(X==="mistakeLimit"){Q.add(Y),Z.push({kind:"mistakeLimit",capabilityName:Y});continue}if(X==="userInstructionService")Q.add(Y),Z.push({kind:"userInstructionService",capabilityName:Y})}return Z}function vK($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function Sb($){return Object.hasOwn($,"update")?$.update:$}function y4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function bb($){let Z=($??[]).map(y4).filter(Boolean);return Z.length>0?new Set(Z):void 0}function yb($,Z,Q){if(!Q)return!0;let W=y4($),J=y4(Z),X=W.includes(":")?W.split(":").at(-1)??W:W,Y=J.includes(":")?J.split(":").at(-1)??J:J;return Q.has(W)||Q.has(J)||Q.has(X)||Q.has(Y)}function O3($,Z){let Q=bb(Z);return $.records.skill.map((W)=>({id:W.id,name:W.item.name,description:"description"in W.item&&typeof W.item.description==="string"?W.item.description:void 0,disabled:W.item.disabled===!0,skill:W.item})).filter((W)=>yb(W.id,W.name,Q))}function mK($,Z){let Q=async(W,J)=>{let X=y4(W),j=O3($,Z).filter((K)=>K.id===X||y4(K.name)===X||K.id.endsWith(`:${X}`)).filter((K)=>!K.disabled);if(j.length!==1)return j.length>1?`Skill "${W}" is ambiguous. Use one of: ${j.map((K)=>K.id).join(", ")}`:`Skill "${W}" not found.`;let V=j[0].skill,H=J?.trim(),B=H?`
720
720
  <command-args>${H}</command-args>`:"",G=V.description?.trim()?`Description: ${V.description.trim()}
721
721
 
722
722
  `:"";return`<command-name>${V.name}</command-name>${B}
723
723
  <command-instructions>
724
724
  ${G}${V.instructions}
725
- </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>O3($,Z).map(({skill:W,...J})=>J),enumerable:!0}),Q}function Pb($,Z,Q,W){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},X=async()=>{let Y=await W($,Q.capabilityName,{},Z);if(Y?.snapshot)J=Y.snapshot};return{start:X,stop:()=>{},refreshType:async()=>{await X()},listRecords:(Y)=>[...J.records[Y]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(Y)=>{if(!Y.startsWith("/")||Y.length<2)return Y;let V=Y.match(/^\/(\S+)/)?.[1];if(!V)return Y;let H=J.runtimeCommands.find((B)=>B.name===V);return H?`${H.instructions}${Y.slice(V.length+1)}`:Y},hasConfiguredSkills:(Y)=>O3(J,Y).some((j)=>!j.disabled),createSkillsExecutor:(Y)=>mK(J,Y),createExtension:(Y)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Y.includeRules?"rules":void 0,Y.registerSkillsTool?"tools":void 0,Y.includeSkills||Y.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Y.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>M6(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(Y.registerSkillsTool)j.registerTool(z2(mK(J,Y.allowedSkillNames)));for(let V of J.runtimeCommands.filter((H)=>H.kind==="skill"&&Y.includeSkills||H.kind==="workflow"&&Y.includeWorkflows))j.registerCommand({name:V.name,description:V.description,handler:(H)=>{let B=H.trim();return B?`${V.instructions}
725
+ </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>O3($,Z).map(({skill:W,...J})=>J),enumerable:!0}),Q}function hb($,Z,Q,W){let J={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},X=async()=>{let Y=await W($,Q.capabilityName,{},Z);if(Y?.snapshot)J=Y.snapshot};return{start:X,stop:()=>{},refreshType:async()=>{await X()},listRecords:(Y)=>[...J.records[Y]],listRuntimeCommands:()=>[...J.runtimeCommands],resolveRuntimeSlashCommand:(Y)=>{if(!Y.startsWith("/")||Y.length<2)return Y;let V=Y.match(/^\/(\S+)/)?.[1];if(!V)return Y;let H=J.runtimeCommands.find((B)=>B.name===V);return H?`${H.instructions}${Y.slice(V.length+1)}`:Y},hasConfiguredSkills:(Y)=>O3(J,Y).some((j)=>!j.disabled),createSkillsExecutor:(Y)=>mK(J,Y),createExtension:(Y)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[Y.includeRules?"rules":void 0,Y.registerSkillsTool?"tools":void 0,Y.includeSkills||Y.includeWorkflows?"commands":void 0].filter((j)=>Boolean(j))},setup(j){if(Y.includeRules)j.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>M6(J.records.rule.map((V)=>V.item).filter((V)=>V.disabled!==!0))});if(Y.registerSkillsTool)j.registerTool(z2(mK(J,Y.allowedSkillNames)));for(let V of J.runtimeCommands.filter((H)=>H.kind==="skill"&&Y.includeSkills||H.kind==="workflow"&&Y.includeWorkflows))j.registerCommand({name:V.name,description:V.description,handler:(H)=>{let B=H.trim();return B?`${V.instructions}
726
726
 
727
- ${B}`:V.instructions}})}})}}function Sb($,Z,Q,W){let J=Q.map((X)=>[X.executor,async(...Y)=>{let j=Y.at(-1),V=Y.slice(0,-1);return(await W($,X.capabilityName,{executor:X.executor,args:V,context:vK(j)},Z))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function bb($,Z,Q,W){if(Q.length===0)return;return Q.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(X,Y){return(await W($,J.capabilityName,{toolName:J.name,input:X,context:vK(Y)},Z,Y.emitUpdate?(V)=>{Y.emitUpdate?.(Nb(V))}:void 0))?.result}}))}function yb($,Z,Q,W){let J=new Map(Q.map((Y)=>[Y.name,Y])),X={};for(let Y of Rb){let j=J.get(Y);if(!j)continue;X[Y]=async(V)=>{return(await W($,j.capabilityName,{context:V},Z))?.control}}return Object.keys(X).length>0?X:void 0}function M3($){let Z=$.contributions.filter((V)=>V.kind==="toolExecutor"),Q=$.contributions.filter((V)=>V.kind==="tool"),W=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),X=$.contributions.find((V)=>V.kind==="checkpoint"),Y=$.contributions.find((V)=>V.kind==="mistakeLimit"),j=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:Sb($.sessionId,$.targetClientId,Z,$.requestCapability),localRuntime:{...W.length>0?{hooks:yb($.sessionId,$.targetClientId,W,$.requestCapability)}:{},...Q.length>0?{extraTools:bb($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{checkpoint:{...$.sessionConfig?.checkpoint??{},...X.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...Y?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,Y.capabilityName,{context:V},$.targetClientId))?.result}}:{},...j?{userInstructionService:Pb($.sessionId,$.targetClientId,j,$.requestCapability)}:{}}}}var dK="hubCapabilityOwnerClientId";function lK($,Z){$[dK]=Z}function hb($){let Z=$?.[dK];return typeof Z==="string"&&Z.trim()?Z.trim():void 0}async function pK($,Z,Q){let W=performance.now(),J={command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Z.sessionId};m("info","session.create.begin",J);let X=Z.payload&&typeof Z.payload==="object"?Z.payload:{},Y=X.metadata&&typeof X.metadata==="object"?JSON.parse(JSON.stringify(X.metadata)):{},j=X.sessionConfig&&typeof X.sessionConfig==="object"?JSON.parse(JSON.stringify(X.sessionConfig)):void 0,V=X.runtimeOptions&&typeof X.runtimeOptions==="object"?X.runtimeOptions:{};if(typeof j?.mode==="string")Y.mode=j.mode;else if(typeof V.mode==="string")Y.mode=V.mode;if(typeof j?.systemPrompt==="string")Y.systemPrompt=j.systemPrompt;else if(typeof V.systemPrompt==="string")Y.systemPrompt=V.systemPrompt;if(j?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)Y.checkpointEnabled=!0;let H=X.modelSelection&&typeof X.modelSelection==="object"?X.modelSelection:{},B=typeof X.workspaceRoot==="string"&&X.workspaceRoot.trim()?X.workspaceRoot.trim():typeof X.cwd==="string"&&X.cwd.trim()?X.cwd.trim():"";if(!B)return m("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(Z,"invalid_session_create","session.create requires workspaceRoot or cwd");let G=Z.clientId?.trim()||"hub-client",K=q3(V.clientContributions);if(m("info","session.create.contributions_parsed",{...J,clientId:G,workspaceRoot:B,cwd:typeof X.cwd==="string"?X.cwd:void 0,contributionCount:K.length}),K.length>0)lK(Y,G);let A=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||cK(),L=uK(V.configExtensions);m("info","session.create.runtime_build.begin",{...J,sessionId:A,configExtensionCount:L?.length??0});let f=M3({sessionId:A,targetClientId:G,contributions:K,sessionConfig:j,requestCapability:$.requestCapability});m("info","session.create.start_session.begin",{...J,sessionId:A,provider:j?.providerId??(typeof H.provider==="string"?H.provider:typeof Y.provider==="string"?Y.provider:"hub"),model:j?.modelId??(typeof H.model==="string"?H.model:typeof Y.model==="string"?Y.model:"hub")});let D=await $.sessionHost.startSession({source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:Object.keys(Y).length>0?Y:void 0,initialMessages:Array.isArray(X.initialMessages)?X.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:L,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Q},config:{...j??{},sessionId:A,providerId:j?.providerId??(typeof H.provider==="string"?H.provider:typeof Y.provider==="string"?Y.provider:"hub"),modelId:j?.modelId??(typeof H.model==="string"?H.model:typeof Y.model==="string"?Y.model:"hub"),apiKey:j?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:j?.cwd??(typeof X.cwd==="string"&&X.cwd.trim()?X.cwd.trim():B),workspaceRoot:j?.workspaceRoot??B,systemPrompt:j?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:j?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:j?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:j?.enableTools??V.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??V.enableTeams!==!1,checkpoint:j?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:X.toolPolicies&&typeof X.toolPolicies==="object"&&!Array.isArray(X.toolPolicies)?JSON.parse(JSON.stringify(X.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});m("info","session.create.start_session.end",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!D.result}),E9($,D.sessionId,G,"creator",{interactive:Y.interactive!==!1}),m("info","session.create.read_records.begin",{...J,sessionId:D.sessionId});let[U,T]=await Promise.all([u0($,D.sessionId),d0($,D.sessionId)]);if(m("info","session.create.read_records.end",{...J,sessionId:D.sessionId,hasSession:!!U,hasSnapshot:!!T,elapsedMs:Math.round(performance.now()-W)}),U)$.publish($.buildEvent("session.created",{session:U,...T?{snapshot:T}:{}},D.sessionId));return m("info","session.create.reply",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-W)}),g(Z,{session:U,...T?{snapshot:T}:{}})}async function rK($,Z,Q){let W=Z.payload&&typeof Z.payload==="object"?Z.payload:{},J=typeof W.sessionId==="string"?W.sessionId.trim():Z.sessionId?.trim()||"",X=W.checkpointRunCount;if(!J)return h(Z,"invalid_restore","session.restore requires a session id");let Y=W.restore&&typeof W.restore==="object"?W.restore:{},j=Y.messages!==!1;if(typeof X!=="number")return h(Z,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!V)return h(Z,"invalid_restore","sessionConfig is required when restore.messages is true");let H=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},B=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof V?.mode==="string")B.mode=V.mode;else if(typeof H.mode==="string")B.mode=H.mode;if(typeof V?.systemPrompt==="string")B.systemPrompt=V.systemPrompt;else if(typeof H.systemPrompt==="string")B.systemPrompt=H.systemPrompt;if(V?.checkpoint?.enabled===!0)B.checkpointEnabled=!0;else if(H.checkpointEnabled===!0)B.checkpointEnabled=!0;let G=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},K=Z.clientId?.trim()||"hub-client",F=q3(H.clientContributions);if(F.length>0)lK(B,K);let L=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||cK(),f=uK(H.configExtensions),D=M3({sessionId:L,targetClientId:K,contributions:F,sessionConfig:V,requestCapability:$.requestCapability}),T=await new r2().restoreCheckpoint({sessionId:J,checkpointRunCount:X,restore:{messages:Y.messages,workspace:Y.workspace,omitCheckpointMessageFromSession:Y.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(M)=>$.sessionHost.getSession(M),readMessages:(M)=>$.sessionHost.readSessionMessages(M),buildStartInput:(M)=>{if(M.restoredCheckpointMetadata)B.checkpoint=M.restoredCheckpointMetadata;let E=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():M.sourceSession.workspaceRoot||M.sourceSession.cwd;return{source:typeof B.source==="string"?B.source:void 0,interactive:B.interactive!==!1,sessionMetadata:{...B,restoredFromSessionId:J,restoredCheckpointRunCount:X},initialMessages:M.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...V??{},sessionId:L,providerId:V?.providerId??(typeof G.provider==="string"?G.provider:M.sourceSession.provider),modelId:V?.modelId??(typeof G.model==="string"?G.model:M.sourceSession.model),apiKey:V?.apiKey??(typeof G.apiKey==="string"?G.apiKey:""),cwd:V?.cwd??M.plan.cwd,workspaceRoot:V?.workspaceRoot??E,systemPrompt:V?.systemPrompt??(typeof H.systemPrompt==="string"?H.systemPrompt:""),mode:V?.mode??(H.mode==="plan"||H.mode==="yolo"?H.mode:"act"),maxIterations:V?.maxIterations??(typeof H.maxIterations==="number"?H.maxIterations:void 0),enableTools:V?.enableTools??H.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??H.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??H.enableTeams!==!1,checkpoint:V?.checkpoint??(H.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof B.teamName==="string"?B.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):H.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(M)=>$.sessionHost.startSession(M),getStartedSessionId:(M)=>M.sessionId,readRestoredSession:(M)=>$.sessionHost.getSession(M)});if(!j)return g(Z,{checkpoint:T.checkpoint});let O=T.startResult;if(!O)return h(Z,"restore_failed","Checkpoint restore did not start a session");E9($,O.sessionId,K,"creator",{interactive:B.interactive!==!1});let[z,_]=await Promise.all([u0($,O.sessionId),d0($,O.sessionId)]);if(z)$.publish($.buildEvent("session.created",{session:z,..._?{snapshot:_}:{}},O.sessionId));return g(Z,{session:z,..._?{snapshot:_}:{},messages:T.messages??[],checkpoint:T.checkpoint})}catch(V){if(V instanceof s0)return h(Z,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(Z,"restore_failed",V instanceof Error?V.message:String(V))}}async function iK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_attach","session.attach requires a session id");E9($,Q,Z.clientId?.trim()||"hub-client","participant");let W=await u0($,Q);if(W)$.publish($.buildEvent("session.attached",{session:W},Q));return W?g(Z,{session:W}):h(Z,"session_not_found",`Unknown session: ${Q}`)}async function nK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_detach","session.detach requires a session id");let W=Z.clientId?.trim()||"hub-client",[J]=await Promise.all([u0($,Q)]),X=hb(J?.metadata)??W,Y=$.sessionState.get(Q);if(Y){if(Y.participants.delete(W),Y.createdByClientId===W)Y.createdByClientId=X;if(Y.participants.size===0)$.sessionState.delete(Q)}V$($,(H)=>H.sessionId===Q&&H.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[j,V]=await Promise.all([u0($,Q),d0($,Q)]);return $.publish($.buildEvent("session.detached",j?{session:j,...V?{snapshot:V}:{},clientId:W}:{clientId:W},Q)),g(Z)}async function aK($,Z){let Q=C0(Z),W=Z.payload?.includeSnapshot===!0,[J,X]=await Promise.all([u0($,Q),W?d0($,Q):Promise.resolve(void 0)]);return J?g(Z,{session:J,...X?{snapshot:X}:{}}):h(Z,"session_not_found",`Unknown session: ${Q}`)}async function sK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_id","session.messages requires a session id");if(!await u0($,Q))return h(Z,"session_not_found",`Unknown session: ${Q}`);let J=await $.sessionHost.readSessionMessages(Q);return g(Z,{sessionId:Q,messages:J})}async function oK($,Z){let Q=typeof Z.payload?.limit==="number"?Z.payload.limit:200,J=(await $.sessionHost.listSessions(Q)).map((X)=>M9(X,$.sessionState.get(X.sessionId)));return g(Z,{sessions:J})}async function tK($,Z){let Q=C0(Z),W=R9(Z.payload?.metadata),J=await $.sessionHost.updateSession(Q,{metadata:W}),[X,Y]=await Promise.all([u0($,Q),d0($,Q)]);if(X)$.publish($.buildEvent("session.updated",{session:X,...Y?{snapshot:Y}:{}},Q));return{version:Z.version,requestId:Z.requestId,ok:J.updated,payload:{updated:J.updated,session:X,...Y?{snapshot:Y}:{}}}}async function eK($,Z){let Q=C0(Z),W=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),g(Z,{deleted:W})}async function $F($,Z){let Q=C0(Z),W=$.sessionHost.pendingPrompts;if(!W)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await W.list({sessionId:Q});return g(Z,{sessionId:Q,prompts:J})}async function ZF($,Z){let Q=C0(Z),W=typeof Z.payload?.promptId==="string"?Z.payload.promptId.trim():"",J=typeof Z.payload?.prompt==="string"?Z.payload.prompt:void 0,X=Z.payload?.delivery==="queue"||Z.payload?.delivery==="steer"?Z.payload.delivery:void 0,Y=$.sessionHost.pendingPrompts;if(!Y)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Y.update({sessionId:Q,promptId:W,prompt:J,delivery:X});return g(Z,j)}async function QF($,Z){let Q=C0(Z),W=typeof Z.payload?.promptId==="string"?Z.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await J.delete({sessionId:Q,promptId:W});return g(Z,X)}function WF($){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 Ib=new Set(["skills","workflows","rules","tools","mcp"]);function R3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function h4($,Z){let Q=$[Z];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${Z}' must be a string.`);return Q}function xb($,Z){let Q=$[Z];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${Z}' must be a boolean.`);return Q}function JF($){if($===void 0)return{};if(!R3($))throw Error("settings.list payload must be an object.");return{cwd:h4($,"cwd"),workspaceRoot:h4($,"workspaceRoot"),availabilityContext:R3($.availabilityContext)?$.availabilityContext:void 0}}function gb($){if(!R3($))throw Error("settings.toggle payload must be an object.");let{type:Z}=$;if(typeof Z!=="string"||!Ib.has(Z))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...JF($),type:Z,id:h4($,"id"),path:h4($,"path"),name:h4($,"name"),enabled:xb($,"enabled")}}class C9{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=kb("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new j$({sessionService:new Q$(new Z$),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:(Z)=>this.publish(Z),buildEvent:s$,requestCapability:(Z,Q,W,J,X)=>zK(this.ctx,Z,Q,W,J,X)},this.schedules=new L9({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(Z,Q)=>{let W=Z==="schedule.execution.completed"?"schedule.execution_completed":Z==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(s$(W,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new f9(this.schedules),this.settings=$.settingsService??new h2,$.cronOptions)this.cronService=new a8({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((Z)=>{gK(this.ctx,Z).catch((Q)=>{D3("session event handling failed",Q),w9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:Z.type,sessionId:Z.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())f3(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(V$(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 Z=await this.dispatchCommand($);return this.captureFailedReply($,Z),Z}catch(Z){throw w9(this.options.telemetry,{component:"core",operation:"hub.command",error:Z,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),Z}}async dispatchCommand($){switch($.command){case"client.register":return MK(this.ctx,$);case"client.update":return RK(this.ctx,$);case"client.unregister":return EK(this.ctx,$,(Z)=>{this.listeners.delete(Z),this.detachClientFromSessions(Z)});case"client.list":return NK(this.ctx,$);case"session.create":return await pK(this.ctx,$,(Z)=>A3(this.ctx,Z));case"session.restore":return await rK(this.ctx,$,(Z)=>A3(this.ctx,Z));case"session.attach":return await iK(this.ctx,$);case"session.detach":return await nK(this.ctx,$);case"session.get":return await aK(this.ctx,$);case"session.messages":return await sK(this.ctx,$);case"session.list":return await oK(this.ctx,$);case"session.update":return await tK(this.ctx,$);case"session.pending_prompts":return await $F(this.ctx,$);case"session.update_pending_prompt":return await ZF(this.ctx,$);case"session.remove_pending_prompt":return await QF(this.ctx,$);case"session.delete":return await eK(this.ctx,$);case"session.hook":return await xK(this.ctx,$);case"run.start":case"session.send_input":return await kK(this.ctx,$);case"run.abort":return await IK(this.ctx,$);case"capability.request":return await OK(this.ctx,$);case"approval.respond":return await LK(this.ctx,$);case"capability.respond":return qK(this.ctx,$);case"capability.progress":return TK(this.ctx,$);case"ui.notify":return this.publish(s$("ui.notify",$.payload??{})),g($);case"ui.show_window":return this.publish(s$("ui.show_window",$.payload??{})),g($);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 hK(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 Z=await this.scheduleCommands.handleCommand($);if(Z.ok){let Q=WF($.command);if(Q)this.publish(s$(Q,Z.payload))}return Z}}}captureFailedReply($,Z){if(Z.ok||!Z.error||!mb(Z.error.code))return;w9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(Z.error.message),severity:Z.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:Z.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let Z=await this.settings.list(JF($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:Z}}}catch(Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:Z instanceof Error?Z.message:String(Z)}}}}async handleSettingsToggle($){try{let Z=await this.settings.toggle(gb($.payload));return this.publish(s$("settings.changed",{types:Z.changedTypes,snapshot:Z.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:Z.snapshot,changedTypes:Z.changedTypes}}}catch(Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:Z instanceof Error?Z.message:String(Z)}}}}subscribe($,Z,Q){let W=this.listeners.get($)??new Set,J={sessionId:Q?.sessionId,listener:Z};return W.add(J),this.listeners.set($,W),()=>{let X=this.listeners.get($);if(!X)return;if(X.delete(J),X.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[Z,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(Z);V$(this.ctx,(Z)=>Z.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let Z of this.listeners.values())for(let Q of Z){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(W){D3(`listener threw while publishing ${$.event}`,W),w9(this.options.telemetry,{component:"core",operation:"hub.publish",error:W,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function mb($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as db}from"node:crypto";import lb from"node:http";import pb from"node:net";import{URL as S3}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as jF,HUB_CAPABILITIES as rb,isHubProtocolCompatible as ib,MAX_CLIENT_HUB_PROTOCOL_VERSION as VF,MIN_CLIENT_HUB_PROTOCOL_VERSION as HF}from"@cline/shared";import{WebSocketServer as nb}from"ws";import{captureSdkError as XF,HUB_COMMAND_SLOW_LOG_MS as vb,resolveHubCommandTimeoutMs as cb,safeJsonParse as ub}from"@cline/shared";function E3($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function YF($,Z,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:Z,message:Q}}}class N3{transport;telemetry;constructor($,Z){this.transport=$;this.telemetry=Z}attach($){let Z=new Map,Q=new Set,W=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(H){console.error(`[hub] failed to send websocket frame: ${H instanceof Error?H.stack||H.message:String(H)}`)}},X=(V)=>{J({kind:"event",envelope:V})},Y=async(V)=>{try{let H=JSON.parse(V.data);switch(H.kind){case"command":{let B=performance.now(),G=!1,K=E3(H);m("info","command.start",K);let F=setTimeout(()=>{if(G)return;m("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-B)})},vb),A=this.transport.command(H.envelope);A.then((O)=>{if(!G)return;m(O.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-B),ok:O.ok,errorCode:O.error?.code,errorMessage:O.error?.message})},(O)=>{if(!G)return;m("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-B),error:O})});let L=!1,f,D,U=cb(H.envelope.command,H.envelope.timeoutMs);try{D=U===null?await A:await Promise.race([A,new Promise((O)=>{f=setTimeout(()=>{L=!0,XF(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${H.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:U}}),O(YF(H,"hub_command_timeout",`Hub command ${H.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${H.envelope.requestId}.`))},U)})])}catch(O){if(clearTimeout(F),f)clearTimeout(f);throw O}if(G=L,clearTimeout(F),f)clearTimeout(f);let T=Math.round(performance.now()-B);if(L)m("error","command.timeout",{...K,durationMs:T,timeoutMs:U});else m(D.ok?"info":"warn","command.end",{...K,durationMs:T,ok:D.ok,errorCode:D.error?.code,errorMessage:D.error?.message});if(H.envelope.command==="client.register"&&D.ok){let z=(H.envelope.payload??{}).clientId?.trim()||H.envelope.clientId?.trim();if(z)Q.add(z)}else if(H.envelope.command==="client.unregister"&&D.ok){let O=H.envelope.clientId?.trim();if(O)Q.delete(O)}J({kind:"reply",envelope:D});break}case"stream.subscribe":{let B=`${H.clientId}:${H.sessionId??"*"}`;if(Z.has(B))break;let G=await this.transport.subscribe(H.clientId,X,{sessionId:H.sessionId});Z.set(B,G);break}case"stream.unsubscribe":{let B=`${H.clientId}:${H.sessionId??"*"}`;Z.get(B)?.(),Z.delete(B);break}case"reply":case"event":break}}catch(H){let B=typeof V.data==="string"?ub(V.data):void 0;if(!B||B.kind!=="command"){m("error","rejected malformed websocket frame",{error:H});return}m("error","command.error",{...E3(B),error:H}),XF(this.telemetry,{component:"core",operation:"hub.websocket_command",error:H,severity:"error",handled:!0,context:E3(B)}),J({kind:"reply",envelope:YF(B,"command_failed",H instanceof Error?H.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!0;for(let V of Z.values())V();Z.clear();for(let V of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Q.clear(),$.removeEventListener("message",Y),$.removeEventListener("close",j)};return $.addEventListener("message",Y),$.addEventListener("close",j),j}}class w3{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,Z,Q){return this.transport.subscribe($,Z,Q)}}function ab($){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((Z)=>Buffer.from(Z))).toString();return String($)}function sb($){return{send(Z){$.send(Z)},addEventListener(Z,Q){if(Z==="message"){$.on("message",(W)=>{Q({data:ab(W)})});return}$.on("close",Q)},removeEventListener(){}}}function ob($){try{$.write(`HTTP/1.1 400 Bad Request\r
727
+ ${B}`:V.instructions}})}})}}function kb($,Z,Q,W){let J=Q.map((X)=>[X.executor,async(...Y)=>{let j=Y.at(-1),V=Y.slice(0,-1);return(await W($,X.capabilityName,{executor:X.executor,args:V,context:vK(j)},Z))?.result}]);return J.length>0?Object.fromEntries(J):void 0}function Ib($,Z,Q,W){if(Q.length===0)return;return Q.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema,lifecycle:J.lifecycle,async execute(X,Y){return(await W($,J.capabilityName,{toolName:J.name,input:X,context:vK(Y)},Z,Y.emitUpdate?(V)=>{Y.emitUpdate?.(Sb(V))}:void 0))?.result}}))}function xb($,Z,Q,W){let J=new Map(Q.map((Y)=>[Y.name,Y])),X={};for(let Y of Cb){let j=J.get(Y);if(!j)continue;X[Y]=async(V)=>{return(await W($,j.capabilityName,{context:V},Z))?.control}}return Object.keys(X).length>0?X:void 0}function M3($){let Z=$.contributions.filter((V)=>V.kind==="toolExecutor"),Q=$.contributions.filter((V)=>V.kind==="tool"),W=$.contributions.filter((V)=>V.kind==="hook"),J=$.contributions.find((V)=>V.kind==="compaction"),X=$.contributions.find((V)=>V.kind==="checkpoint"),Y=$.contributions.find((V)=>V.kind==="mistakeLimit"),j=$.contributions.find((V)=>V.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:kb($.sessionId,$.targetClientId,Z,$.requestCapability),localRuntime:{...W.length>0?{hooks:xb($.sessionId,$.targetClientId,W,$.requestCapability)}:{},...Q.length>0?{extraTools:Ib($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J?{compaction:{...$.sessionConfig?.compaction??{},...J.config,compact:async(V)=>{return(await $.requestCapability($.sessionId,J.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...X?{checkpoint:{...$.sessionConfig?.checkpoint??{},...X.config,createCheckpoint:async(V)=>{return(await $.requestCapability($.sessionId,X.capabilityName,{context:V},$.targetClientId))?.result}}}:{},...Y?{onConsecutiveMistakeLimitReached:async(V)=>{return(await $.requestCapability($.sessionId,Y.capabilityName,{context:V},$.targetClientId))?.result}}:{},...j?{userInstructionService:hb($.sessionId,$.targetClientId,j,$.requestCapability)}:{}}}}var dK="hubCapabilityOwnerClientId";function lK($,Z){$[dK]=Z}function gb($){let Z=$?.[dK];return typeof Z==="string"&&Z.trim()?Z.trim():void 0}async function pK($,Z,Q){let W=performance.now(),J={command:Z.command,requestId:Z.requestId,clientId:Z.clientId,sessionId:Z.sessionId};m("info","session.create.begin",J);let X=Z.payload&&typeof Z.payload==="object"?Z.payload:{},Y=X.metadata&&typeof X.metadata==="object"?JSON.parse(JSON.stringify(X.metadata)):{},j=X.sessionConfig&&typeof X.sessionConfig==="object"?JSON.parse(JSON.stringify(X.sessionConfig)):void 0,V=X.runtimeOptions&&typeof X.runtimeOptions==="object"?X.runtimeOptions:{};if(typeof j?.mode==="string")Y.mode=j.mode;else if(typeof V.mode==="string")Y.mode=V.mode;if(typeof j?.systemPrompt==="string")Y.systemPrompt=j.systemPrompt;else if(typeof V.systemPrompt==="string")Y.systemPrompt=V.systemPrompt;if(j?.checkpoint?.enabled===!0)Y.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)Y.checkpointEnabled=!0;let H=X.modelSelection&&typeof X.modelSelection==="object"?X.modelSelection:{},B=typeof X.workspaceRoot==="string"&&X.workspaceRoot.trim()?X.workspaceRoot.trim():typeof X.cwd==="string"&&X.cwd.trim()?X.cwd.trim():"";if(!B)return m("warn","session.create.invalid",{...J,reason:"missing_workspace_root"}),h(Z,"invalid_session_create","session.create requires workspaceRoot or cwd");let G=Z.clientId?.trim()||"hub-client",K=q3(V.clientContributions);if(m("info","session.create.contributions_parsed",{...J,clientId:G,workspaceRoot:B,cwd:typeof X.cwd==="string"?X.cwd:void 0,contributionCount:K.length}),K.length>0)lK(Y,G);let A=(typeof j?.sessionId==="string"?j.sessionId.trim():"")||cK(),L=uK(V.configExtensions);m("info","session.create.runtime_build.begin",{...J,sessionId:A,configExtensionCount:L?.length??0});let f=M3({sessionId:A,targetClientId:G,contributions:K,sessionConfig:j,requestCapability:$.requestCapability});m("info","session.create.start_session.begin",{...J,sessionId:A,provider:j?.providerId??(typeof H.provider==="string"?H.provider:typeof Y.provider==="string"?Y.provider:"hub"),model:j?.modelId??(typeof H.model==="string"?H.model:typeof Y.model==="string"?Y.model:"hub")});let D=await $.sessionHost.startSession({source:typeof Y.source==="string"?Y.source:void 0,interactive:Y.interactive!==!1,sessionMetadata:Object.keys(Y).length>0?Y:void 0,initialMessages:Array.isArray(X.initialMessages)?X.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:L,...f.localRuntime},capabilities:{toolExecutors:f.toolExecutors,requestToolApproval:Q},config:{...j??{},sessionId:A,providerId:j?.providerId??(typeof H.provider==="string"?H.provider:typeof Y.provider==="string"?Y.provider:"hub"),modelId:j?.modelId??(typeof H.model==="string"?H.model:typeof Y.model==="string"?Y.model:"hub"),apiKey:j?.apiKey??(typeof H.apiKey==="string"?H.apiKey:void 0),cwd:j?.cwd??(typeof X.cwd==="string"&&X.cwd.trim()?X.cwd.trim():B),workspaceRoot:j?.workspaceRoot??B,systemPrompt:j?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:j?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:j?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:j?.enableTools??V.enableTools!==!1,enableSpawnAgent:j?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:j?.enableAgentTeams??V.enableTeams!==!1,checkpoint:j?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:j?.teamName??(typeof Y.teamName==="string"?Y.teamName:void 0)},toolPolicies:X.toolPolicies&&typeof X.toolPolicies==="object"&&!Array.isArray(X.toolPolicies)?JSON.parse(JSON.stringify(X.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});m("info","session.create.start_session.end",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-W),hasImmediateResult:!!D.result}),N9($,D.sessionId,G,"creator",{interactive:Y.interactive!==!1}),m("info","session.create.read_records.begin",{...J,sessionId:D.sessionId});let[U,T]=await Promise.all([u0($,D.sessionId),d0($,D.sessionId)]);if(m("info","session.create.read_records.end",{...J,sessionId:D.sessionId,hasSession:!!U,hasSnapshot:!!T,elapsedMs:Math.round(performance.now()-W)}),U)$.publish($.buildEvent("session.created",{session:U,...T?{snapshot:T}:{}},D.sessionId));return m("info","session.create.reply",{...J,sessionId:D.sessionId,elapsedMs:Math.round(performance.now()-W)}),g(Z,{session:U,...T?{snapshot:T}:{}})}async function rK($,Z,Q){let W=Z.payload&&typeof Z.payload==="object"?Z.payload:{},J=typeof W.sessionId==="string"?W.sessionId.trim():Z.sessionId?.trim()||"",X=W.checkpointRunCount;if(!J)return h(Z,"invalid_restore","session.restore requires a session id");let Y=W.restore&&typeof W.restore==="object"?W.restore:{},j=Y.messages!==!1;if(typeof X!=="number")return h(Z,"invalid_restore","checkpointRunCount must be a positive integer");try{let V=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0;if(j&&!V)return h(Z,"invalid_restore","sessionConfig is required when restore.messages is true");let H=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{},B=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{};if(typeof V?.mode==="string")B.mode=V.mode;else if(typeof H.mode==="string")B.mode=H.mode;if(typeof V?.systemPrompt==="string")B.systemPrompt=V.systemPrompt;else if(typeof H.systemPrompt==="string")B.systemPrompt=H.systemPrompt;if(V?.checkpoint?.enabled===!0)B.checkpointEnabled=!0;else if(H.checkpointEnabled===!0)B.checkpointEnabled=!0;let G=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},K=Z.clientId?.trim()||"hub-client",F=q3(H.clientContributions);if(F.length>0)lK(B,K);let L=(typeof V?.sessionId==="string"?V.sessionId.trim():"")||cK(),f=uK(H.configExtensions),D=M3({sessionId:L,targetClientId:K,contributions:F,sessionConfig:V,requestCapability:$.requestCapability}),T=await new r2().restoreCheckpoint({sessionId:J,checkpointRunCount:X,restore:{messages:Y.messages,workspace:Y.workspace,omitCheckpointMessageFromSession:Y.omitCheckpointMessageFromSession===!0},start:V,cwd:typeof V?.cwd==="string"&&V.cwd.trim()||typeof V?.workspaceRoot==="string"&&V.workspaceRoot.trim()||void 0,getSession:(M)=>$.sessionHost.getSession(M),readMessages:(M)=>$.sessionHost.readSessionMessages(M),buildStartInput:(M)=>{if(M.restoredCheckpointMetadata)B.checkpoint=M.restoredCheckpointMetadata;let E=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():M.sourceSession.workspaceRoot||M.sourceSession.cwd;return{source:typeof B.source==="string"?B.source:void 0,interactive:B.interactive!==!1,sessionMetadata:{...B,restoredFromSessionId:J,restoredCheckpointRunCount:X},initialMessages:M.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:f,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...V??{},sessionId:L,providerId:V?.providerId??(typeof G.provider==="string"?G.provider:M.sourceSession.provider),modelId:V?.modelId??(typeof G.model==="string"?G.model:M.sourceSession.model),apiKey:V?.apiKey??(typeof G.apiKey==="string"?G.apiKey:""),cwd:V?.cwd??M.plan.cwd,workspaceRoot:V?.workspaceRoot??E,systemPrompt:V?.systemPrompt??(typeof H.systemPrompt==="string"?H.systemPrompt:""),mode:V?.mode??(H.mode==="plan"||H.mode==="yolo"?H.mode:"act"),maxIterations:V?.maxIterations??(typeof H.maxIterations==="number"?H.maxIterations:void 0),enableTools:V?.enableTools??H.enableTools!==!1,enableSpawnAgent:V?.enableSpawnAgent??H.enableSpawn!==!1,enableAgentTeams:V?.enableAgentTeams??H.enableTeams!==!1,checkpoint:V?.checkpoint??(H.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:V?.teamName??(typeof B.teamName==="string"?B.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):H.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(M)=>$.sessionHost.startSession(M),getStartedSessionId:(M)=>M.sessionId,readRestoredSession:(M)=>$.sessionHost.getSession(M)});if(!j)return g(Z,{checkpoint:T.checkpoint});let q=T.startResult;if(!q)return h(Z,"restore_failed","Checkpoint restore did not start a session");N9($,q.sessionId,K,"creator",{interactive:B.interactive!==!1});let[z,_]=await Promise.all([u0($,q.sessionId),d0($,q.sessionId)]);if(z)$.publish($.buildEvent("session.created",{session:z,..._?{snapshot:_}:{}},q.sessionId));return g(Z,{session:z,..._?{snapshot:_}:{},messages:T.messages??[],checkpoint:T.checkpoint})}catch(V){if(V instanceof s0)return h(Z,V.code,V.code==="session_not_found"?`Unknown session: ${J}`:V.message);return h(Z,"restore_failed",V instanceof Error?V.message:String(V))}}async function iK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_attach","session.attach requires a session id");N9($,Q,Z.clientId?.trim()||"hub-client","participant");let W=await u0($,Q);if(W)$.publish($.buildEvent("session.attached",{session:W},Q));return W?g(Z,{session:W}):h(Z,"session_not_found",`Unknown session: ${Q}`)}async function nK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_detach","session.detach requires a session id");let W=Z.clientId?.trim()||"hub-client",[J]=await Promise.all([u0($,Q)]),X=gb(J?.metadata)??W,Y=$.sessionState.get(Q);if(Y){if(Y.participants.delete(W),Y.createdByClientId===W)Y.createdByClientId=X;if(Y.participants.size===0)$.sessionState.delete(Q)}V$($,(H)=>H.sessionId===Q&&H.targetClientId===W,`Capability owner client ${W} detached before request was resolved.`);let[j,V]=await Promise.all([u0($,Q),d0($,Q)]);return $.publish($.buildEvent("session.detached",j?{session:j,...V?{snapshot:V}:{},clientId:W}:{clientId:W},Q)),g(Z)}async function aK($,Z){let Q=C0(Z),W=Z.payload?.includeSnapshot===!0,[J,X]=await Promise.all([u0($,Q),W?d0($,Q):Promise.resolve(void 0)]);return J?g(Z,{session:J,...X?{snapshot:X}:{}}):h(Z,"session_not_found",`Unknown session: ${Q}`)}async function sK($,Z){let Q=C0(Z);if(!Q)return h(Z,"invalid_session_id","session.messages requires a session id");if(!await u0($,Q))return h(Z,"session_not_found",`Unknown session: ${Q}`);let J=await $.sessionHost.readSessionMessages(Q);return g(Z,{sessionId:Q,messages:J})}async function oK($,Z){let Q=typeof Z.payload?.limit==="number"?Z.payload.limit:200,J=(await $.sessionHost.listSessions(Q)).map((X)=>R9(X,$.sessionState.get(X.sessionId)));return g(Z,{sessions:J})}async function tK($,Z){let Q=C0(Z),W=E9(Z.payload?.metadata),J=await $.sessionHost.updateSession(Q,{metadata:W}),[X,Y]=await Promise.all([u0($,Q),d0($,Q)]);if(X)$.publish($.buildEvent("session.updated",{session:X,...Y?{snapshot:Y}:{}},Q));return{version:Z.version,requestId:Z.requestId,ok:J.updated,payload:{updated:J.updated,session:X,...Y?{snapshot:Y}:{}}}}async function eK($,Z){let Q=C0(Z),W=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),g(Z,{deleted:W})}async function $F($,Z){let Q=C0(Z),W=$.sessionHost.pendingPrompts;if(!W)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let J=await W.list({sessionId:Q});return g(Z,{sessionId:Q,prompts:J})}async function ZF($,Z){let Q=C0(Z),W=typeof Z.payload?.promptId==="string"?Z.payload.promptId.trim():"",J=typeof Z.payload?.prompt==="string"?Z.payload.prompt:void 0,X=Z.payload?.delivery==="queue"||Z.payload?.delivery==="steer"?Z.payload.delivery:void 0,Y=$.sessionHost.pendingPrompts;if(!Y)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await Y.update({sessionId:Q,promptId:W,prompt:J,delivery:X});return g(Z,j)}async function QF($,Z){let Q=C0(Z),W=typeof Z.payload?.promptId==="string"?Z.payload.promptId.trim():"",J=$.sessionHost.pendingPrompts;if(!J)return h(Z,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await J.delete({sessionId:Q,promptId:W});return g(Z,X)}function WF($){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 vb=new Set(["skills","workflows","rules","tools","mcp"]);function R3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function h4($,Z){let Q=$[Z];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${Z}' must be a string.`);return Q}function cb($,Z){let Q=$[Z];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${Z}' must be a boolean.`);return Q}function JF($){if($===void 0)return{};if(!R3($))throw Error("settings.list payload must be an object.");return{cwd:h4($,"cwd"),workspaceRoot:h4($,"workspaceRoot"),availabilityContext:R3($.availabilityContext)?$.availabilityContext:void 0}}function ub($){if(!R3($))throw Error("settings.toggle payload must be an object.");let{type:Z}=$;if(typeof Z!=="string"||!vb.has(Z))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...JF($),type:Z,id:h4($,"id"),path:h4($,"path"),name:h4($,"name"),enabled:cb($,"enabled")}}class P9{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=mb("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new j$({sessionService:new Q$(new Z$),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:(Z)=>this.publish(Z),buildEvent:o$,requestCapability:(Z,Q,W,J,X)=>zK(this.ctx,Z,Q,W,J,X)},this.schedules=new _9({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(Z,Q)=>{let W=Z==="schedule.execution.completed"?"schedule.execution_completed":Z==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!W)return;this.publish(o$(W,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new U9(this.schedules),this.settings=$.settingsService??new h2,$.cronOptions)this.cronService=new a8({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((Z)=>{gK(this.ctx,Z).catch((Q)=>{D3("session event handling failed",Q),C9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:Z.type,sessionId:Z.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())f3(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(V$(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 Z=await this.dispatchCommand($);return this.captureFailedReply($,Z),Z}catch(Z){throw C9(this.options.telemetry,{component:"core",operation:"hub.command",error:Z,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),Z}}async dispatchCommand($){switch($.command){case"client.register":return MK(this.ctx,$);case"client.update":return RK(this.ctx,$);case"client.unregister":return EK(this.ctx,$,(Z)=>{this.listeners.delete(Z),this.detachClientFromSessions(Z)});case"client.list":return NK(this.ctx,$);case"session.create":return await pK(this.ctx,$,(Z)=>A3(this.ctx,Z));case"session.restore":return await rK(this.ctx,$,(Z)=>A3(this.ctx,Z));case"session.attach":return await iK(this.ctx,$);case"session.detach":return await nK(this.ctx,$);case"session.get":return await aK(this.ctx,$);case"session.messages":return await sK(this.ctx,$);case"session.list":return await oK(this.ctx,$);case"session.update":return await tK(this.ctx,$);case"session.pending_prompts":return await $F(this.ctx,$);case"session.update_pending_prompt":return await ZF(this.ctx,$);case"session.remove_pending_prompt":return await QF(this.ctx,$);case"session.delete":return await eK(this.ctx,$);case"session.hook":return await xK(this.ctx,$);case"run.start":case"session.send_input":return await kK(this.ctx,$);case"run.abort":return await IK(this.ctx,$);case"capability.request":return await OK(this.ctx,$);case"approval.respond":return await LK(this.ctx,$);case"capability.respond":return qK(this.ctx,$);case"capability.progress":return TK(this.ctx,$);case"ui.notify":return this.publish(o$("ui.notify",$.payload??{})),g($);case"ui.show_window":return this.publish(o$("ui.show_window",$.payload??{})),g($);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 hK(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 Z=await this.scheduleCommands.handleCommand($);if(Z.ok){let Q=WF($.command);if(Q)this.publish(o$(Q,Z.payload))}return Z}}}captureFailedReply($,Z){if(Z.ok||!Z.error||!db(Z.error.code))return;C9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(Z.error.message),severity:Z.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:Z.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let Z=await this.settings.list(JF($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:Z}}}catch(Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:Z instanceof Error?Z.message:String(Z)}}}}async handleSettingsToggle($){try{let Z=await this.settings.toggle(ub($.payload));return this.publish(o$("settings.changed",{types:Z.changedTypes,snapshot:Z.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:Z.snapshot,changedTypes:Z.changedTypes}}}catch(Z){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:Z instanceof Error?Z.message:String(Z)}}}}subscribe($,Z,Q){let W=this.listeners.get($)??new Set,J={sessionId:Q?.sessionId,listener:Z};return W.add(J),this.listeners.set($,W),()=>{let X=this.listeners.get($);if(!X)return;if(X.delete(J),X.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[Z,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(Z);V$(this.ctx,(Z)=>Z.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let Z of this.listeners.values())for(let Q of Z){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(W){D3(`listener threw while publishing ${$.event}`,W),C9(this.options.telemetry,{component:"core",operation:"hub.publish",error:W,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function db($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as ib}from"node:crypto";import nb from"node:http";import ab from"node:net";import{URL as S3}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as jF,HUB_CAPABILITIES as sb,isHubProtocolCompatible as ob,MAX_CLIENT_HUB_PROTOCOL_VERSION as VF,MIN_CLIENT_HUB_PROTOCOL_VERSION as HF}from"@cline/shared";import{WebSocketServer as tb}from"ws";import{captureSdkError as XF,HUB_COMMAND_SLOW_LOG_MS as lb,resolveHubCommandTimeoutMs as pb,safeJsonParse as rb}from"@cline/shared";function E3($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function YF($,Z,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:Z,message:Q}}}class N3{transport;telemetry;constructor($,Z){this.transport=$;this.telemetry=Z}attach($){let Z=new Map,Q=new Set,W=!1,J=(V)=>{try{$.send(JSON.stringify(V))}catch(H){console.error(`[hub] failed to send websocket frame: ${H instanceof Error?H.stack||H.message:String(H)}`)}},X=(V)=>{J({kind:"event",envelope:V})},Y=async(V)=>{try{let H=JSON.parse(V.data);switch(H.kind){case"command":{let B=performance.now(),G=!1,K=E3(H);m("info","command.start",K);let F=setTimeout(()=>{if(G)return;m("warn","command.slow",{...K,elapsedMs:Math.round(performance.now()-B)})},lb),A=this.transport.command(H.envelope);A.then((q)=>{if(!G)return;m(q.ok?"warn":"error","command.late_end",{...K,elapsedMs:Math.round(performance.now()-B),ok:q.ok,errorCode:q.error?.code,errorMessage:q.error?.message})},(q)=>{if(!G)return;m("error","command.late_error",{...K,elapsedMs:Math.round(performance.now()-B),error:q})});let L=!1,f,D,U=pb(H.envelope.command,H.envelope.timeoutMs);try{D=U===null?await A:await Promise.race([A,new Promise((q)=>{f=setTimeout(()=>{L=!0,XF(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${H.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...K,timeoutMs:U}}),q(YF(H,"hub_command_timeout",`Hub command ${H.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${H.envelope.requestId}.`))},U)})])}catch(q){if(clearTimeout(F),f)clearTimeout(f);throw q}if(G=L,clearTimeout(F),f)clearTimeout(f);let T=Math.round(performance.now()-B);if(L)m("error","command.timeout",{...K,durationMs:T,timeoutMs:U});else m(D.ok?"info":"warn","command.end",{...K,durationMs:T,ok:D.ok,errorCode:D.error?.code,errorMessage:D.error?.message});if(H.envelope.command==="client.register"&&D.ok){let z=(H.envelope.payload??{}).clientId?.trim()||H.envelope.clientId?.trim();if(z)Q.add(z)}else if(H.envelope.command==="client.unregister"&&D.ok){let q=H.envelope.clientId?.trim();if(q)Q.delete(q)}J({kind:"reply",envelope:D});break}case"stream.subscribe":{let B=`${H.clientId}:${H.sessionId??"*"}`;if(Z.has(B))break;let G=await this.transport.subscribe(H.clientId,X,{sessionId:H.sessionId});Z.set(B,G);break}case"stream.unsubscribe":{let B=`${H.clientId}:${H.sessionId??"*"}`;Z.get(B)?.(),Z.delete(B);break}case"reply":case"event":break}}catch(H){let B=typeof V.data==="string"?rb(V.data):void 0;if(!B||B.kind!=="command"){m("error","rejected malformed websocket frame",{error:H});return}m("error","command.error",{...E3(B),error:H}),XF(this.telemetry,{component:"core",operation:"hub.websocket_command",error:H,severity:"error",handled:!0,context:E3(B)}),J({kind:"reply",envelope:YF(B,"command_failed",H instanceof Error?H.message:"Unknown hub error")})}},j=()=>{if(W)return;W=!0;for(let V of Z.values())V();Z.clear();for(let V of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:V});Q.clear(),$.removeEventListener("message",Y),$.removeEventListener("close",j)};return $.addEventListener("message",Y),$.addEventListener("close",j),j}}class w3{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,Z,Q){return this.transport.subscribe($,Z,Q)}}function eb($){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((Z)=>Buffer.from(Z))).toString();return String($)}function $y($){return{send(Z){$.send(Z)},addEventListener(Z,Q){if(Z==="message"){$.on("message",(W)=>{Q({data:eb(W)})});return}$.on("close",Q)},removeEventListener(){}}}function Zy($){try{$.write(`HTTP/1.1 400 Bad Request\r
728
728
  Connection: close\r
729
729
  Content-Length: 0\r
730
730
  \r
731
- `),$.end()}catch{$.destroy()}}function tb($){try{$.write(`HTTP/1.1 401 Unauthorized\r
731
+ `),$.end()}catch{$.destroy()}}function Qy($){try{$.write(`HTTP/1.1 401 Unauthorized\r
732
732
  Connection: close\r
733
733
  Content-Length: 0\r
734
734
  \r
735
- `),$.end()}catch{$.destroy()}}function C3($,Z){if(!$||!Z)return!1;let Q=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return Q.length===W.length&&db(Q,W)}function BF($,Z){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,W=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${Z.host}:${Z.port}${Z.pathname}: ${W}`,X=Error(Q?`${J} (${Q})`:J);if(Q)$.code=Q,X.code=Q;if($ instanceof Error&&$.stack)X.stack=`${X.name}: ${X.message}
736
- Caused by: ${$.stack}`;return X}async function eb($){return await new Promise((Z,Q)=>{let W=pb.createServer();W.once("error",Q),W.listen(0,$,()=>{let J=W.address();if(!J||typeof J==="string"){W.close(()=>Q(Error("Failed to resolve free port")));return}let X=J.port;W.close((Y)=>{if(Y){Q(Y);return}Z(X)})})})}function $y($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var P3=new Map,GF="cline-hub-auth.",Zy=30000;function b3($){return Array.isArray($)?$.join(","):$??""}function KF($){return $===32||$===9}function FF($){let Z=b3($).trim(),Q="bearer";if(Z.length<=6||Z.slice(0,6).toLowerCase()!=="bearer"||!KF(Z.charCodeAt(6)))return null;let W=7;while(W<Z.length&&KF(Z.charCodeAt(W)))W+=1;return Z.slice(W).trim()||null}function Qy($){for(let Z of b3($).split(",")){let Q=Z.trim();if(Q.startsWith(GF))return Q.slice(GF.length).trim()||null}return null}function AF($){let Z=$.trim().toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"||Z==="[::1]"}function Wy($){let Z=b3($).trim();if(!Z)return!1;try{return AF(new S3(Z).hostname)}catch{return!1}}async function y3($){let Z=$.owner??I$(),Q=$.host??"127.0.0.1",W=$.pathname??"/hub",J=$.port??O5(),X=J===0?await eb(Q):J,Y=X,j=D1(Q,X,W),V=OH(),H=TH(),B=new C9($);await B.start();let G=new N3(new w3(B),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:jF,minClientProtocolVersion:HF,maxClientProtocolVersion:VF,capabilities:rb,coreVersion:Q4.version,buildId:V,pid:process.pid,startedAt:F},L=new Set,f,D,U=async()=>{if(D)return D;return D=(async()=>{if(f)clearInterval(f),f=void 0;for(let _ of L)_.terminate?.();L.clear();for(let _ of K)_();if(K.clear(),await new Promise((_,M)=>{O.close((E)=>{if(E){M(E);return}_()})}),await new Promise((_,M)=>{T.close((E)=>{if(E){M(E);return}_()})}),await B.stop(),(await A0(Z.discoveryPath))?.url===j)await a0(Z.discoveryPath)})(),D},T=lb.createServer((z,_)=>{if((z.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Q,port:Y,url:j});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(E);return}if((z.url??"/")==="/status"){if(!C3(FF(z.headers.authorization),H)){_.statusCode=401,_.end("Unauthorized");return}let E=JSON.stringify({hubId:B.getHubId(),...A,authToken:H,host:Q,port:Y,url:j,updatedAt:new Date().toISOString()});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(E);return}if((z.url??"/")==="/version"){_.statusCode=200,_.setHeader("content-type","application/json"),_.end(JSON.stringify(A));return}if(new S3(z.url??"/",`http://${Q}:${Y}`).pathname==="/shutdown"&&z.method==="POST"){if(!C3(FF(z.headers.authorization),H)){_.statusCode=401,_.end("Unauthorized");return}_.statusCode=202,_.setHeader("content-type","application/json"),_.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}_.statusCode=404,_.end("Not found")}),O=new nb({noServer:!0});f=setInterval(()=>{for(let z of L){if(z.isAlive===!1){try{z.terminate?.()}catch{}L.delete(z);continue}z.isAlive=!1;try{z.ping?.()}catch{try{z.terminate?.()}catch{}L.delete(z)}}},Zy),T.on("upgrade",(z,_,M)=>{if(new S3(z.url??"/",`http://${Q}:${Y}`).pathname!==W){_.destroy();return}if(!(C3(Qy(z.headers["sec-websocket-protocol"]),H)||AF(Q)&&Wy(z.headers.origin))){tb(_);return}try{O.handleUpgrade(z,_,M,(c)=>{let n=c;n.isAlive=!0,n.on("pong",()=>{n.isAlive=!0}),L.add(n);let a=G.attach(sb(c));K.add(a),c.once("close",()=>{L.delete(n),a(),K.delete(a)})})}catch{ob(_)}});try{await new Promise((z,_)=>{T.once("error",(M)=>{_(BF(M,{host:Q,port:X,pathname:W}))}),T.listen(X,Q,()=>{let M=T.address();if(!M||typeof M==="string"){_(BF(Error("Failed to resolve hub port"),{host:Q,port:X,pathname:W}));return}Y=M.port,j=D1(Q,Y,W),z()})})}catch(z){if(f)clearInterval(f),f=void 0;throw await B.stop().catch(()=>{return}),z}return await qH(Z.discoveryPath,{hubId:B.getHubId(),protocolVersion:jF,minClientProtocolVersion:HF,maxClientProtocolVersion:VF,capabilities:[...A.capabilities],coreVersion:Q4.version,buildId:V,authToken:H,host:Q,port:Y,url:j,pid:process.pid,startedAt:F,updatedAt:F}),{host:Q,port:Y,url:j,authToken:H,close:U}}async function fF($){let Z=$.owner??I$(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.host??"127.0.0.1",J=$.port??O5(),X=$.pathname??"/hub",Y=D1(W,J,X),j=Z.discoveryPath,V=(B)=>{if(!Q)k2(B.url,B.authToken);return B},H=P3.get(j);if(H){let B=await H;if(B.url===Y)return V({server:B,url:B.url,authToken:B.authToken,action:"reuse"})}return await MH(Z.discoveryPath,async()=>{let B=await A0(Z.discoveryPath);if(B?.url&&(B.url===Y||$.allowPortFallback===!0)){let F=await x$(B.url,{authToken:B.authToken});if(F?.url&&ib(F).compatible&&await o1(F.url,{authToken:B.authToken}))return V({url:F.url,authToken:B.authToken,action:"reuse"})}if(B?.url)await a0(Z.discoveryPath);let K=async(F)=>{let A=y3({...F,owner:Z});P3.set(j,A);try{let L=await A;return V({server:L,url:L.url,authToken:L.authToken,action:"started"})}catch(L){throw P3.delete(j),L}};try{return await K($)}catch(F){if(!$.allowPortFallback||!$y(F))throw F;return await K({...$,port:0})}})}function DF(){return UF()==="production"?s1():L1()}function Jy($){return UF()!=="production"&&!$}async function Je($){let Z=a1({host:$.host,port:$.port,pathname:$.pathname});return await y3({...$,...Z,owner:DF()})}async function Xe($){let Z=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=a1({host:$.host,port:$.port,pathname:$.pathname});return await fF({...$,...Q,allowPortFallback:$.allowPortFallback??Jy(Z),owner:DF()})}P9();import{buildRemoteConfigSessionBlobUploadMetadata as _F,clearRemoteConfigSessionBlobUpload as Xy,createClineTelemetryServiceConfig as Yy,createSessionId as jy,createRemoteConfigSessionMessagesArtifactUploader as Vy,prepareRemoteConfigRuntime as Hy,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as zF,readRemoteConfigSessionBlobUploadMetadata as By,registerRemoteConfigSessionBlobUpload as TF}from"@cline/shared";function Gy($,Z){let Q=$.telemetry||Z.telemetryService?{...Z.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return a$(Yy(Q)).telemetry}function Ky(){let $=Vy();return{async uploadMessagesFile(Z){await $.uploadMessagesFile(Z)}}}async function Fy($){let Z=await Hy($),Q=Gy(Z,$),W=[Z.pluginDefinition],J=Z.claims?.subject,X=_F(Z.bundle?.remoteConfig,J),Y;return{prepared:Z,extensions:W,telemetry:Q,applyToStartSessionInput(j){let V=j.config.extensions??[],H=j.config.telemetry,B=X?j.config.sessionId?.trim()||jy():j.config.sessionId;if(B&&X)Y=B;let G=B&&X?TF(B,Z.bundle?.remoteConfig,J):void 0,K=G?{...j.sessionMetadata??{},[zF]:G}:j.sessionMetadata;return{...j,...K?{sessionMetadata:K}:{},config:{...j.config,...B?{sessionId:B}:{},extensions:[...V,...W],telemetry:Q??H}}},async dispose(){if(Y)Xy(Y)}}}import{mkdir as Ay,readFile as fy,unlink as Uy,writeFile as Dy}from"node:fs/promises";import{join as OF}from"node:path";function Ly($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function _y($){return new Promise((Z)=>setTimeout(Z,$))}async function h3($){try{await Uy($)}catch{}}async function zy($,Z={}){let Q=Z.approvalDir?.trim(),W=Z.sessionId?.trim();if(!Q||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Ay(Q,{recursive:!0});let J=Ly(`${$.toolCallId}`),X=OF(Q,`${W}.request.${J}.json`),Y=OF(Q,`${W}.decision.${J}.json`),j=Z.nowIso??(()=>new Date().toISOString());await Dy(X,`${JSON.stringify({requestId:J,sessionId:W,createdAt:j(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
737
- `,"utf8");let V=Z.timeoutMs??300000,H=Z.pollIntervalMs??200,B=Date.now();while(Date.now()-B<V){try{let G=await fy(Y,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([h3(Y),h3(X)]),F}catch{}await _y(H)}return await h3(X),{approved:!1,reason:"Tool approval request timed out"}}r0();function Ty($){let Z=($??"stdio").trim();if(Z==="http"||Z==="streamable-http")return"streamableHttp";if(Z==="stdio"||Z==="sse"||Z==="streamableHttp")return Z;throw Error(`Unsupported MCP transport "${Z}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function Oy($){let Z;try{Z=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(Z.protocol!=="http:"&&Z.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function qy($){let Z=$.indexOf(":");if(Z<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Q=$.slice(0,Z).trim(),W=$.slice(Z+1).trim();if(!Q||!W)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Q))throw Error(`Invalid MCP header name "${Q}".`);return[Q,W]}function My($){let Z=$.indexOf("<");return Z>=0&&$.indexOf(">",Z+1)>Z+1}function qF($){let Z=[...$.headers??[]],Q=[],W=$.transport,J=$.targetArgs??[];for(let X=0;X<J.length;X++){let Y=J[X];if($.parseTransport&&Y==="--transport"){let j=J[X+1];if(!j)throw Error("--transport requires a value");W=j,X++;continue}if($.parseTransport&&Y?.startsWith("--transport=")){W=Y.slice(12);continue}if(Y==="--header"){let j=J[X+1];if(!j)throw Error("--header requires a value");Z.push(j),X++;continue}if(Y?.startsWith("--header=")){Z.push(Y.slice(9));continue}Q.push(Y)}return{headers:Z,targetArgs:Q,transport:W}}function Ry($){if($.length===0)return{warnings:[]};let Z={},Q=[];for(let W of $){let[J,X]=qy(W);if(Z[J]=X,My(X))Q.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:Z,warnings:Q}}function MF($){let Z=$.name.trim();if(!Z)throw Error("MCP server name is required");let{headers:Q,targetArgs:W,transport:J}=qF({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),X=Ty(J),{headers:Y,warnings:j}=Ry(Q);if(X==="stdio"){if(Q.length>0)throw Error("Stdio MCP installs do not support request headers.");let[H,...B]=W;if(!H?.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:Z,transport:{type:X,command:H,args:B.length>0?B:void 0},warnings:j}}if(W.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=W[0]?.trim()??"";return Oy(V),{name:Z,transport:Y?{type:X,url:V,headers:Y}:{type:X,url:V},warnings:j}}function k3($){let[Z,...Q]=$;if(!Z)throw Error("Marketplace MCP install args must start with a server name.");return{name:Z,...qF({parseTransport:!0,targetArgs:Q})}}function Ey($,Z,Q){f1(Q,(W)=>{let J=W.mcpServers,X=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};X[$]={transport:Z},W.mcpServers=X})}function Ny($){let{name:Z,transport:Q,warnings:W}=MF($);return Ey(Z,Q,$.settingsPath??Z0()),{name:Z,status:"installed",transport:Q,warnings:W}}import{spawn as Xh}from"node:child_process";import{existsSync as bF,rmSync as Yh}from"node:fs";import{homedir as jh,platform as Vh}from"node:os";import{dirname as Hh,join as SF}from"node:path";import{resolveClineDir as Bh,resolveMcpSettingsPath as Gh}from"@cline/shared/storage";r0();import{existsSync as o2,readdirSync as xy,readFileSync as gy,rmdirSync as my,rmSync as vy,statSync as cy}from"node:fs";import{basename as l0,dirname as B$,extname as uy,isAbsolute as dy,join as M1,relative as ly,resolve as s2,sep as c3}from"node:path";import{discoverPluginModulePaths as py,resolvePluginConfigSearchPaths as ry}from"@cline/shared/storage";import{existsSync as wy,mkdirSync as Cy,readFileSync as Py,writeFileSync as Sy}from"node:fs";import{dirname as EF,isAbsolute as by,relative as yy,resolve as RF}from"node:path";function t$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function S9($,Z){let Q=yy(RF($),RF(Z));return Q===""||!Q.startsWith("..")&&!by(Q)}function I3($){if(!wy($))return{mcpServers:{}};try{let Z=JSON.parse(Py($,"utf8"));if(t$(Z))return Z}catch(Z){throw Error(`Invalid MCP settings at "${$}": ${Z instanceof Error?Z.message:String(Z)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function x3($){if(t$($.mcpServers))return{...$.mcpServers};return{}}function g3($,Z,Q){Cy(EF($),{recursive:!0}),Sy($,`${JSON.stringify({...Z,mcpServers:Q},null,2)}
738
- `,"utf8")}function NF($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((Z)=>Z.trim()).filter((Z)=>Z.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((Z)=>Z.trim()).filter((Z)=>Z.length>0))]}}function y9($){if(!t$($))return;let Z=$.metadata;return t$(Z)?Z:void 0}function b9($,Z){let Q=y9($);if(!Q||Q.source!=="plugin")return!1;let W=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,J=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(Z.pluginName&&W===Z.pluginName){if(!Z.pluginPath||J===Z.pluginPath)return!0}if(J&&Z.pluginPath&&(J===Z.pluginPath||S9(Z.pluginPath,J)||S9(J,Z.pluginPath)))return!0;if(W&&Z.pluginNames?.some((X)=>X===W))return!0;if(J&&Z.pluginPaths?.some((X)=>J===X||S9(X,J)||S9(J,X)))return!0;return!1}function hy($){let Z=t$($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:EF($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...Z,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function ky($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let Z=await F2({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],W=[],J=(Z.failures??[]).map((X)=>({pluginPath:X.pluginPath,pluginName:X.pluginName,message:X.message}));for(let X of Z.extensions??[]){let Y=X.__clinePluginPath;if(!Y)continue;if(!X.setup){Q.push({pluginName:X.name,pluginPath:Y});continue}let j=[],V={registerTool:(H)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(H)=>{if(!X.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');j.push(H)}};try{await X.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(H){J.push({pluginPath:Y,pluginName:X.name,message:H instanceof Error?H.message:String(H)});continue}Q.push({pluginName:X.name,pluginPath:Y});for(let H of j)W.push({pluginName:X.name,pluginPath:Y,server:{...H,metadata:{...H.metadata??{},source:"plugin",pluginName:X.name,pluginPath:Y}}})}return{plugins:Q,servers:W,failures:J}}finally{await Z.shutdown().catch(()=>{})}}async function m3($){let Z=$.settingsPath??Z0(),Q={mutations:[],failures:[]},W;try{W=await ky($)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)});return Q}Q.failures.push(...W.failures);let J;try{J=I3(Z)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)});return Q}let X=x3(J),Y=new Map,j=new Map;for(let H of W.plugins)Y.set(H.pluginPath,new Set),j.set(H.pluginPath,H.pluginName);let V=W7(W.servers.map((H)=>({server:H.server,owner:H,ownerLabel:H.pluginName})));for(let H of V){let B=H.owner;if(!Y.has(B.pluginPath))Y.set(B.pluginPath,new Set);if(H.name)Y.get(B.pluginPath)?.add(H.name);if(!H.registration){Q.mutations.push({name:H.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:"skipped",reason:H.loadError??"invalid MCP server registration"});continue}let G=X[H.registration.name];if(G!==void 0){if(!b9(G,{pluginName:B.pluginName,pluginPath:B.pluginPath})){Q.mutations.push({name:H.registration.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}X[H.registration.name]=hy({registration:H.registration,pluginName:B.pluginName,pluginPath:B.pluginPath,existing:t$(G)?G:void 0}),Q.mutations.push({name:H.registration.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:G===void 0?"created":"updated"})}for(let[H,B]of Object.entries(X)){let G=y9(B),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=Y.get(K);if(F&&b9(B,{pluginPath:K})&&!F.has(H))delete X[H],Q.mutations.push({name:H,pluginName:typeof G?.pluginName==="string"?G.pluginName:j.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((H)=>H.action!=="skipped"))try{g3(Z,J,X)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)})}return Q}function Iy($){let Z=$.settingsPath??Z0(),Q;try{Q=I3(Z)}catch{return[]}let W=x3(Q),J=NF($),X=[];for(let[Y,j]of Object.entries(W)){if(!t$(j)||!b9(j,J))continue;let V=y9(j);W[Y]={...j,disabled:!0},X.push({name:Y,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(X.length>0)g3(Z,Q,W);return X}function v3($){let Z=$.settingsPath??Z0(),Q;try{Q=I3(Z)}catch{return[]}let W=x3(Q),J=NF($),X=[];for(let[Y,j]of Object.entries(W)){if(!b9(j,J))continue;let V=y9(j);delete W[Y],X.push({name:Y,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(X.length>0)g3(Z,Q,W);return X}var r3="_installed",iy="package",ny=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function u3($){return $.trim().toLowerCase()}function o0($,Z){let Q=Z?.trim();if(!Q)return;$.add(Q)}function ay($){return $.replace(/-[0-9a-f]{12}$/i,"")}function d3($){let Z=uy($);return Z?$.slice(0,-Z.length):$}function l3($){if(!o2($))return;try{let Z=JSON.parse(gy($,"utf8"));return typeof Z.name==="string"?Z.name.trim():void 0}catch{return}}function i3($,Z){let Q=ly(Z,$);return Q===""||!Q.startsWith("..")&&!dy(Q)}function wF($){let Q=s2($).split(c3),W=Q.lastIndexOf(r3);if(W<0)return;let J=Q[W+1];if(!J)return;let X=ny.get(J)??1,Y=W+2+X;if(Q.length<Y)return;let j=Q.slice(0,Y).join(c3)||c3;return o2(j)?j:void 0}function h9($){try{return xy($,{withFileTypes:!0})}catch{return[]}}function sy($){let Z=M1($,r3);if(!o2(Z))return[];let Q=[];for(let W of h9(Z)){if(!W.isDirectory())continue;let J=M1(Z,W.name);if(W.name==="git"){for(let X of h9(J)){if(!X.isDirectory())continue;let Y=M1(J,X.name);for(let j of h9(Y))if(j.isDirectory())Q.push(M1(Y,j.name))}continue}for(let X of h9(J))if(X.isDirectory())Q.push(M1(J,X.name))}return Q.sort((W,J)=>W.localeCompare(J))}function CF($){try{return py($)}catch{return[]}}function p3($){let Z=CF($),Q=new Set;o0(Q,l0($)),o0(Q,ay(l0($))),o0(Q,l3(M1($,"package.json"))),o0(Q,l3(M1($,iy,"package.json")));for(let W of Z)o0(Q,l0(W)),o0(Q,d3(l0(W)));return{installPath:$,entryPaths:Z,names:[...Q].sort((W,J)=>W.localeCompare(J)),installed:!0}}function oy($,Z){let Q=s2($),W=Z.find((Y)=>i3(Q,Y));if(!W)return;let J=B$(Q);while(J!==W&&J!==B$(J)){if(o2(M1(J,"package.json")))return J;J=B$(J)}let X=l0(Q);if((X==="index.ts"||X==="index.js")&&B$(Q)!==W)return B$(Q);return Q}function PF($,Z){let Q=oy($,Z);if(!Q)return;let W=new Set;return o0(W,l0($)),o0(W,d3(l0($))),o0(W,l0(Q)),o0(W,d3(l0(Q))),o0(W,l3(M1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...W].sort((J,X)=>J.localeCompare(X)),installed:!1}}function ty($){let Z=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return ry(Z).filter((Q)=>o2(Q))}function ey($){let Z=new Map;for(let Q of $){for(let W of sy(Q))Z.set(W,p3(W));for(let W of CF(Q)){let J=wF(W);if(J){if(!Z.has(J))Z.set(J,p3(J));continue}let X=PF(W,$);if(X)Z.set(X.installPath,X)}}return[...Z.values()].sort((Q,W)=>Q.installPath.localeCompare(W.installPath))}function $h($,Z){let Q=u3(Z);if(!Q)return!1;if(u3($.installPath)===Q)return!0;return $.names.some((W)=>u3(W)===Q)}function Zh($,Z,Q){let W=s2($);for(let X of Z){if(i3(W,X.installPath))return X;if(X.entryPaths.some((Y)=>s2(Y)===W))return X}let J=wF(W);if(J)return p3(J);if(o2(W))return PF(W,Q);return}function Qh($){let Z=R0(),Q=Z.disabledPlugins;if(!Q?.length)return;let W=Q.filter((J)=>{let X=s2(J);if(i3(X,$.installPath))return!1;return!$.entryPaths.some((Y)=>s2(Y)===X)});if(W.length===Q.length)return;h1({...Z,disabledPlugins:W})}function Wh($){let Z=B$($);while(Z!==B$(Z)&&l0(Z)!==r3){try{my(Z)}catch{return}Z=B$(Z)}}function Jh($){return`${$.names[0]??l0($.installPath)} at ${$.installPath}`}async function n3($){let Z=ty($),Q=ey(Z),W=$.path?.trim(),J=$.name?.trim(),X;if(W){if(X=Zh(W,Q,Z),!X)throw Error(`No plugin found at ${W}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let j=Q.filter((V)=>$h(V,J));if(j.length===0)throw Error(`No plugin found matching "${J}"`);if(j.length>1)throw Error(`Multiple plugins match "${J}": ${j.map(Jh).join(", ")}`);X=j[0]}let Y=cy(X.installPath,{throwIfNoEntry:!1});if(!Y)throw Error(`Plugin install path does not exist: ${X.installPath}`);if(v3({pluginPaths:[X.installPath,...X.entryPaths],pluginNames:X.names}),vy(X.installPath,{recursive:Y.isDirectory(),force:!0}),Qh(X),X.installed)Wh(X.installPath);return{name:J||X.names[0]||l0(X.installPath),installPath:X.installPath,removedPaths:[X.installPath],entryPaths:X.entryPaths}}var a3=120000,k4=12000,Kh=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Fh=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Ah=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,fh=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function s3($){return $.install?.args??[]}function Uh(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||jh()}function Dh($){let Z=0,Q=$.length;while(Z<Q&&($[Z]==="."||$[Z]==="-"))Z++;while(Q>Z&&($[Q-1]==="."||$[Q-1]==="-"))Q--;return $.slice(Z,Q)}function Lh($){return Dh($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function yF($){return $.split(/\r?\n/).map((Z)=>{if(!Kh.test(Z))return Z;return Z.replace(Fh,"$1[redacted]").replace(Ah,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(fh,"$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(`
739
- `).slice(-k4)}function _h($){let Z=yF([$.stdout,$.stderr].filter(Boolean).join(`
740
- `)).trim();return Z.length>0?Z:void 0}function zh($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function Th($,Z){return[$,...Z].map((Q)=>zh(yF(Q).trim())).join(" ")}var Oh=async($,Z)=>new Promise((Q,W)=>{let J=!1,X=!1,Y=Xh($,Z,{env:process.env,shell:Vh()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),j="",V="",H=setTimeout(()=>{if(!J)Y.kill("SIGKILL")},a3+5000),B=setTimeout(()=>{X=!0,V+=`
741
- Timed out after ${a3/1000}s.`,Y.kill("SIGTERM")},a3);H.unref?.(),B.unref?.(),Y.stdout?.on("data",(G)=>{if(j+=String(G),j.length>k4*2)j=j.slice(-k4)}),Y.stderr?.on("data",(G)=>{if(V+=String(G),V.length>k4*2)V=V.slice(-k4)}),Y.once("error",(G)=>{clearTimeout(B),clearTimeout(H),W(G)}),Y.once("close",(G,K)=>{J=!0,clearTimeout(B),clearTimeout(H),Q({exitCode:X?124:G??(K==="SIGINT"?130:1),stdout:j,stderr:V})})});function qh($){return`${$.type}:${$.id}`}function o3($){let Z=s3($);if(Z.length===0)throw Error("Marketplace install args are required.");return k3(Z).name}function hF($,Z={}){let Q=o3($),W=Z.mcpSettingsPath??Gh(),J=f1(W,(X)=>{let Y=X.mcpServers&&typeof X.mcpServers==="object"&&!Array.isArray(X.mcpServers)?X.mcpServers:{},j=Object.hasOwn(Y,Q);if(j)delete Y[Q];return X.mcpServers=Y,j});return{name:Q,deleted:J}}function t3($){let Z=new Set,Q=(J)=>{let X=Lh(J??"");if(X&&X!=="skill")Z.add(X)};Q($.id),Q($.name);let W=s3($);for(let J=0;J<W.length;J++){let X=W[J];if((X==="--skill"||X==="-s")&&W[J+1]){Q(W[J+1]),J++;continue}let Y=X.split("@").at(1);if(Y)Q(Y)}return[...Z]}function e3($){return[SF(Bh(),"skills",$,"SKILL.md"),SF(Uh(),".agents","skills",$,"SKILL.md")].filter((Z,Q,W)=>W.indexOf(Z)===Q)}function $J($){if($.type!=="skill")return;return t3($).find((Z)=>e3(Z).some((Q)=>bF(Q)))}function kF($){return $J($)!==void 0}function Mh($){let Z=[];if($.type!=="skill")return Z;for(let Q of t3($))for(let W of e3(Q)){if(!bF(W))continue;let J=Hh(W);Yh(J,{recursive:!0,force:!0}),Z.push(J)}return Z}async function IF($,Z={}){let Q=$J($);if(!Q)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let W="npx",J=["-y","skills@latest","remove",Q,"-g","-y"],X=Th(W,J),Y=Z.spawnCommand??Oh,j;try{j=await Y(W,J)}catch(B){throw Error(`Failed to start ${$.name??$.id} uninstall command:
735
+ `),$.end()}catch{$.destroy()}}function C3($,Z){if(!$||!Z)return!1;let Q=Buffer.from($,"utf8"),W=Buffer.from(Z,"utf8");return Q.length===W.length&&ib(Q,W)}function BF($,Z){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,W=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",J=`Failed to start hub server on ${Z.host}:${Z.port}${Z.pathname}: ${W}`,X=Error(Q?`${J} (${Q})`:J);if(Q)$.code=Q,X.code=Q;if($ instanceof Error&&$.stack)X.stack=`${X.name}: ${X.message}
736
+ Caused by: ${$.stack}`;return X}async function Wy($){return await new Promise((Z,Q)=>{let W=ab.createServer();W.once("error",Q),W.listen(0,$,()=>{let J=W.address();if(!J||typeof J==="string"){W.close(()=>Q(Error("Failed to resolve free port")));return}let X=J.port;W.close((Y)=>{if(Y){Q(Y);return}Z(X)})})})}function Jy($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var P3=new Map,GF="cline-hub-auth.",Xy=30000;function b3($){return Array.isArray($)?$.join(","):$??""}function KF($){return $===32||$===9}function FF($){let Z=b3($).trim(),Q="bearer";if(Z.length<=6||Z.slice(0,6).toLowerCase()!=="bearer"||!KF(Z.charCodeAt(6)))return null;let W=7;while(W<Z.length&&KF(Z.charCodeAt(W)))W+=1;return Z.slice(W).trim()||null}function Yy($){for(let Z of b3($).split(",")){let Q=Z.trim();if(Q.startsWith(GF))return Q.slice(GF.length).trim()||null}return null}function AF($){let Z=$.trim().toLowerCase();return Z==="localhost"||Z==="127.0.0.1"||Z==="::1"||Z==="[::1]"}function jy($){let Z=b3($).trim();if(!Z)return!1;try{return AF(new S3(Z).hostname)}catch{return!1}}async function y3($){let Z=$.owner??x$(),Q=$.host??"127.0.0.1",W=$.pathname??"/hub",J=$.port??q5(),X=J===0?await Wy(Q):J,Y=X,j=L1(Q,X,W),V=OH(),H=TH(),B=new P9($);await B.start();let G=new N3(new w3(B),$.telemetry),K=new Set,F=new Date().toISOString(),A={protocolVersion:jF,minClientProtocolVersion:HF,maxClientProtocolVersion:VF,capabilities:sb,coreVersion:Q4.version,buildId:V,pid:process.pid,startedAt:F},L=new Set,f,D,U=async()=>{if(D)return D;return D=(async()=>{if(f)clearInterval(f),f=void 0;for(let _ of L)_.terminate?.();L.clear();for(let _ of K)_();if(K.clear(),await new Promise((_,M)=>{q.close((E)=>{if(E){M(E);return}_()})}),await new Promise((_,M)=>{T.close((E)=>{if(E){M(E);return}_()})}),await B.stop(),(await A0(Z.discoveryPath))?.url===j)await a0(Z.discoveryPath)})(),D},T=nb.createServer((z,_)=>{if((z.url??"/")==="/health"){let E=JSON.stringify({ok:!0,protocolVersion:A.protocolVersion,minClientProtocolVersion:A.minClientProtocolVersion,maxClientProtocolVersion:A.maxClientProtocolVersion,coreVersion:A.coreVersion,host:Q,port:Y,url:j});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(E);return}if((z.url??"/")==="/status"){if(!C3(FF(z.headers.authorization),H)){_.statusCode=401,_.end("Unauthorized");return}let E=JSON.stringify({hubId:B.getHubId(),...A,authToken:H,host:Q,port:Y,url:j,updatedAt:new Date().toISOString()});_.statusCode=200,_.setHeader("content-type","application/json"),_.end(E);return}if((z.url??"/")==="/version"){_.statusCode=200,_.setHeader("content-type","application/json"),_.end(JSON.stringify(A));return}if(new S3(z.url??"/",`http://${Q}:${Y}`).pathname==="/shutdown"&&z.method==="POST"){if(!C3(FF(z.headers.authorization),H)){_.statusCode=401,_.end("Unauthorized");return}_.statusCode=202,_.setHeader("content-type","application/json"),_.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}_.statusCode=404,_.end("Not found")}),q=new tb({noServer:!0});f=setInterval(()=>{for(let z of L){if(z.isAlive===!1){try{z.terminate?.()}catch{}L.delete(z);continue}z.isAlive=!1;try{z.ping?.()}catch{try{z.terminate?.()}catch{}L.delete(z)}}},Xy),T.on("upgrade",(z,_,M)=>{if(new S3(z.url??"/",`http://${Q}:${Y}`).pathname!==W){_.destroy();return}if(!(C3(Yy(z.headers["sec-websocket-protocol"]),H)||AF(Q)&&jy(z.headers.origin))){Qy(_);return}try{q.handleUpgrade(z,_,M,(c)=>{let n=c;n.isAlive=!0,n.on("pong",()=>{n.isAlive=!0}),L.add(n);let a=G.attach($y(c));K.add(a),c.once("close",()=>{L.delete(n),a(),K.delete(a)})})}catch{Zy(_)}});try{await new Promise((z,_)=>{T.once("error",(M)=>{_(BF(M,{host:Q,port:X,pathname:W}))}),T.listen(X,Q,()=>{let M=T.address();if(!M||typeof M==="string"){_(BF(Error("Failed to resolve hub port"),{host:Q,port:X,pathname:W}));return}Y=M.port,j=L1(Q,Y,W),z()})})}catch(z){if(f)clearInterval(f),f=void 0;throw await B.stop().catch(()=>{return}),z}return await qH(Z.discoveryPath,{hubId:B.getHubId(),protocolVersion:jF,minClientProtocolVersion:HF,maxClientProtocolVersion:VF,capabilities:[...A.capabilities],coreVersion:Q4.version,buildId:V,authToken:H,host:Q,port:Y,url:j,pid:process.pid,startedAt:F,updatedAt:F}),{host:Q,port:Y,url:j,authToken:H,close:U}}async function fF($){let Z=$.owner??x$(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=$.host??"127.0.0.1",J=$.port??q5(),X=$.pathname??"/hub",Y=L1(W,J,X),j=Z.discoveryPath,V=(B)=>{if(!Q)k2(B.url,B.authToken);return B},H=P3.get(j);if(H){let B=await H;if(B.url===Y)return V({server:B,url:B.url,authToken:B.authToken,action:"reuse"})}return await MH(Z.discoveryPath,async()=>{let B=await A0(Z.discoveryPath);if(B?.url&&(B.url===Y||$.allowPortFallback===!0)){let F=await g$(B.url,{authToken:B.authToken});if(F?.url&&ob(F).compatible&&await o1(F.url,{authToken:B.authToken}))return V({url:F.url,authToken:B.authToken,action:"reuse"})}if(B?.url)await a0(Z.discoveryPath);let K=async(F)=>{let A=y3({...F,owner:Z});P3.set(j,A);try{let L=await A;return V({server:L,url:L.url,authToken:L.authToken,action:"started"})}catch(L){throw P3.delete(j),L}};try{return await K($)}catch(F){if(!$.allowPortFallback||!Jy(F))throw F;return await K({...$,port:0})}})}function DF(){return UF()==="production"?s1():_1()}function Vy($){return UF()!=="production"&&!$}async function Ve($){let Z=a1({host:$.host,port:$.port,pathname:$.pathname});return await y3({...$,...Z,owner:DF()})}async function He($){let Z=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=a1({host:$.host,port:$.port,pathname:$.pathname});return await fF({...$,...Q,allowPortFallback:$.allowPortFallback??Vy(Z),owner:DF()})}S9();import{buildRemoteConfigSessionBlobUploadMetadata as _F,clearRemoteConfigSessionBlobUpload as Hy,createClineTelemetryServiceConfig as By,createSessionId as Gy,createRemoteConfigSessionMessagesArtifactUploader as Ky,prepareRemoteConfigRuntime as Fy,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as zF,readRemoteConfigSessionBlobUploadMetadata as Ay,registerRemoteConfigSessionBlobUpload as TF}from"@cline/shared";function fy($,Z){let Q=$.telemetry||Z.telemetryService?{...Z.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return s$(By(Q)).telemetry}function Uy(){let $=Ky();return{async uploadMessagesFile(Z){await $.uploadMessagesFile(Z)}}}async function Dy($){let Z=await Fy($),Q=fy(Z,$),W=[Z.pluginDefinition],J=Z.claims?.subject,X=_F(Z.bundle?.remoteConfig,J),Y;return{prepared:Z,extensions:W,telemetry:Q,applyToStartSessionInput(j){let V=j.config.extensions??[],H=j.config.telemetry,B=X?j.config.sessionId?.trim()||Gy():j.config.sessionId;if(B&&X)Y=B;let G=B&&X?TF(B,Z.bundle?.remoteConfig,J):void 0,K=G?{...j.sessionMetadata??{},[zF]:G}:j.sessionMetadata;return{...j,...K?{sessionMetadata:K}:{},config:{...j.config,...B?{sessionId:B}:{},extensions:[...V,...W],telemetry:Q??H}}},async dispose(){if(Y)Hy(Y)}}}import{mkdir as Ly,readFile as _y,unlink as zy,writeFile as Ty}from"node:fs/promises";import{join as OF}from"node:path";function Oy($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function qy($){return new Promise((Z)=>setTimeout(Z,$))}async function h3($){try{await zy($)}catch{}}async function My($,Z={}){let Q=Z.approvalDir?.trim(),W=Z.sessionId?.trim();if(!Q||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await Ly(Q,{recursive:!0});let J=Oy(`${$.toolCallId}`),X=OF(Q,`${W}.request.${J}.json`),Y=OF(Q,`${W}.decision.${J}.json`),j=Z.nowIso??(()=>new Date().toISOString());await Ty(X,`${JSON.stringify({requestId:J,sessionId:W,createdAt:j(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
737
+ `,"utf8");let V=Z.timeoutMs??300000,H=Z.pollIntervalMs??200,B=Date.now();while(Date.now()-B<V){try{let G=await _y(Y,"utf8"),K=JSON.parse(G),F={approved:K.approved===!0,reason:typeof K.reason==="string"?K.reason:void 0};return await Promise.all([h3(Y),h3(X)]),F}catch{}await qy(H)}return await h3(X),{approved:!1,reason:"Tool approval request timed out"}}r0();function Ry($){let Z=($??"stdio").trim();if(Z==="http"||Z==="streamable-http")return"streamableHttp";if(Z==="stdio"||Z==="sse"||Z==="streamableHttp")return Z;throw Error(`Unsupported MCP transport "${Z}". Expected stdio, sse, http, streamable-http, or streamableHttp.`)}function Ey($){let Z;try{Z=new URL($)}catch{throw Error(`Invalid MCP server URL: ${$}`)}if(Z.protocol!=="http:"&&Z.protocol!=="https:")throw Error(`Invalid MCP server URL: ${$} (only http and https are supported)`)}function Ny($){let Z=$.indexOf(":");if(Z<=0)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);let Q=$.slice(0,Z).trim(),W=$.slice(Z+1).trim();if(!Q||!W)throw Error(`Invalid MCP header "${$}". Expected "Header-Name: header value".`);if(!/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(Q))throw Error(`Invalid MCP header name "${Q}".`);return[Q,W]}function wy($){let Z=$.indexOf("<");return Z>=0&&$.indexOf(">",Z+1)>Z+1}function qF($){let Z=[...$.headers??[]],Q=[],W=$.transport,J=$.targetArgs??[];for(let X=0;X<J.length;X++){let Y=J[X];if($.parseTransport&&Y==="--transport"){let j=J[X+1];if(!j)throw Error("--transport requires a value");W=j,X++;continue}if($.parseTransport&&Y?.startsWith("--transport=")){W=Y.slice(12);continue}if(Y==="--header"){let j=J[X+1];if(!j)throw Error("--header requires a value");Z.push(j),X++;continue}if(Y?.startsWith("--header=")){Z.push(Y.slice(9));continue}Q.push(Y)}return{headers:Z,targetArgs:Q,transport:W}}function Cy($){if($.length===0)return{warnings:[]};let Z={},Q=[];for(let W of $){let[J,X]=Ny(W);if(Z[J]=X,wy(X))Q.push(`Header "${J}" looks like it contains a placeholder. Update it in MCP settings before using this server.`)}return{headers:Z,warnings:Q}}function MF($){let Z=$.name.trim();if(!Z)throw Error("MCP server name is required");let{headers:Q,targetArgs:W,transport:J}=qF({headers:$.headers,targetArgs:$.targetArgs,transport:$.transport}),X=Ry(J),{headers:Y,warnings:j}=Cy(Q);if(X==="stdio"){if(Q.length>0)throw Error("Stdio MCP installs do not support request headers.");let[H,...B]=W;if(!H?.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:Z,transport:{type:X,command:H,args:B.length>0?B:void 0},warnings:j}}if(W.length!==1)throw Error("Remote MCP install requires exactly one URL argument after the server name.");let V=W[0]?.trim()??"";return Ey(V),{name:Z,transport:Y?{type:X,url:V,headers:Y}:{type:X,url:V},warnings:j}}function k3($){let[Z,...Q]=$;if(!Z)throw Error("Marketplace MCP install args must start with a server name.");return{name:Z,...qF({parseTransport:!0,targetArgs:Q})}}function Py($,Z,Q){U1(Q,(W)=>{let J=W.mcpServers,X=J&&typeof J==="object"&&!Array.isArray(J)?{...J}:{};X[$]={transport:Z},W.mcpServers=X})}function Sy($){let{name:Z,transport:Q,warnings:W}=MF($);return Py(Z,Q,$.settingsPath??Z0()),{name:Z,status:"installed",transport:Q,warnings:W}}import{spawn as Hh}from"node:child_process";import{existsSync as bF,rmSync as Bh}from"node:fs";import{homedir as Gh,platform as Kh}from"node:os";import{dirname as Fh,join as SF}from"node:path";import{resolveClineDir as Ah,resolveMcpSettingsPath as fh}from"@cline/shared/storage";r0();import{existsSync as o2,readdirSync as cy,readFileSync as uy,rmdirSync as dy,rmSync as ly,statSync as py}from"node:fs";import{basename as l0,dirname as B$,extname as ry,isAbsolute as iy,join as R1,relative as ny,resolve as s2,sep as c3}from"node:path";import{discoverPluginModulePaths as ay,resolvePluginConfigSearchPaths as sy}from"@cline/shared/storage";import{existsSync as by,mkdirSync as yy,readFileSync as hy,writeFileSync as ky}from"node:fs";import{dirname as EF,isAbsolute as Iy,relative as xy,resolve as RF}from"node:path";function e$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function b9($,Z){let Q=xy(RF($),RF(Z));return Q===""||!Q.startsWith("..")&&!Iy(Q)}function I3($){if(!by($))return{mcpServers:{}};try{let Z=JSON.parse(hy($,"utf8"));if(e$(Z))return Z}catch(Z){throw Error(`Invalid MCP settings at "${$}": ${Z instanceof Error?Z.message:String(Z)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function x3($){if(e$($.mcpServers))return{...$.mcpServers};return{}}function g3($,Z,Q){yy(EF($),{recursive:!0}),ky($,`${JSON.stringify({...Z,mcpServers:Q},null,2)}
738
+ `,"utf8")}function NF($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((Z)=>Z.trim()).filter((Z)=>Z.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((Z)=>Z.trim()).filter((Z)=>Z.length>0))]}}function h9($){if(!e$($))return;let Z=$.metadata;return e$(Z)?Z:void 0}function y9($,Z){let Q=h9($);if(!Q||Q.source!=="plugin")return!1;let W=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,J=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(Z.pluginName&&W===Z.pluginName){if(!Z.pluginPath||J===Z.pluginPath)return!0}if(J&&Z.pluginPath&&(J===Z.pluginPath||b9(Z.pluginPath,J)||b9(J,Z.pluginPath)))return!0;if(W&&Z.pluginNames?.some((X)=>X===W))return!0;if(J&&Z.pluginPaths?.some((X)=>J===X||b9(X,J)||b9(J,X)))return!0;return!1}function gy($){let Z=e$($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:EF($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...Z,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function my($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let Z=await F2({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],W=[],J=(Z.failures??[]).map((X)=>({pluginPath:X.pluginPath,pluginName:X.pluginName,message:X.message}));for(let X of Z.extensions??[]){let Y=X.__clinePluginPath;if(!Y)continue;if(!X.setup){Q.push({pluginName:X.name,pluginPath:Y});continue}let j=[],V={registerTool:(H)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(H)=>{if(!X.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');j.push(H)}};try{await X.setup(V,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(H){J.push({pluginPath:Y,pluginName:X.name,message:H instanceof Error?H.message:String(H)});continue}Q.push({pluginName:X.name,pluginPath:Y});for(let H of j)W.push({pluginName:X.name,pluginPath:Y,server:{...H,metadata:{...H.metadata??{},source:"plugin",pluginName:X.name,pluginPath:Y}}})}return{plugins:Q,servers:W,failures:J}}finally{await Z.shutdown().catch(()=>{})}}async function m3($){let Z=$.settingsPath??Z0(),Q={mutations:[],failures:[]},W;try{W=await my($)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)});return Q}Q.failures.push(...W.failures);let J;try{J=I3(Z)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)});return Q}let X=x3(J),Y=new Map,j=new Map;for(let H of W.plugins)Y.set(H.pluginPath,new Set),j.set(H.pluginPath,H.pluginName);let V=W7(W.servers.map((H)=>({server:H.server,owner:H,ownerLabel:H.pluginName})));for(let H of V){let B=H.owner;if(!Y.has(B.pluginPath))Y.set(B.pluginPath,new Set);if(H.name)Y.get(B.pluginPath)?.add(H.name);if(!H.registration){Q.mutations.push({name:H.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:"skipped",reason:H.loadError??"invalid MCP server registration"});continue}let G=X[H.registration.name];if(G!==void 0){if(!y9(G,{pluginName:B.pluginName,pluginPath:B.pluginPath})){Q.mutations.push({name:H.registration.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}X[H.registration.name]=gy({registration:H.registration,pluginName:B.pluginName,pluginPath:B.pluginPath,existing:e$(G)?G:void 0}),Q.mutations.push({name:H.registration.name,pluginName:B.pluginName,pluginPath:B.pluginPath,action:G===void 0?"created":"updated"})}for(let[H,B]of Object.entries(X)){let G=h9(B),K=typeof G?.pluginPath==="string"?G.pluginPath:"",F=Y.get(K);if(F&&y9(B,{pluginPath:K})&&!F.has(H))delete X[H],Q.mutations.push({name:H,pluginName:typeof G?.pluginName==="string"?G.pluginName:j.get(K)??"plugin",pluginPath:K,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((H)=>H.action!=="skipped"))try{g3(Z,J,X)}catch(H){for(let B of $.pluginPaths)Q.failures.push({pluginPath:B,message:H instanceof Error?H.message:String(H)})}return Q}function vy($){let Z=$.settingsPath??Z0(),Q;try{Q=I3(Z)}catch{return[]}let W=x3(Q),J=NF($),X=[];for(let[Y,j]of Object.entries(W)){if(!e$(j)||!y9(j,J))continue;let V=h9(j);W[Y]={...j,disabled:!0},X.push({name:Y,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"disabled"})}if(X.length>0)g3(Z,Q,W);return X}function v3($){let Z=$.settingsPath??Z0(),Q;try{Q=I3(Z)}catch{return[]}let W=x3(Q),J=NF($),X=[];for(let[Y,j]of Object.entries(W)){if(!y9(j,J))continue;let V=h9(j);delete W[Y],X.push({name:Y,pluginName:typeof V?.pluginName==="string"?V.pluginName:"plugin",pluginPath:typeof V?.pluginPath==="string"?V.pluginPath:"",action:"removed"})}if(X.length>0)g3(Z,Q,W);return X}var r3="_installed",oy="package",ty=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function u3($){return $.trim().toLowerCase()}function o0($,Z){let Q=Z?.trim();if(!Q)return;$.add(Q)}function ey($){return $.replace(/-[0-9a-f]{12}$/i,"")}function d3($){let Z=ry($);return Z?$.slice(0,-Z.length):$}function l3($){if(!o2($))return;try{let Z=JSON.parse(uy($,"utf8"));return typeof Z.name==="string"?Z.name.trim():void 0}catch{return}}function i3($,Z){let Q=ny(Z,$);return Q===""||!Q.startsWith("..")&&!iy(Q)}function wF($){let Q=s2($).split(c3),W=Q.lastIndexOf(r3);if(W<0)return;let J=Q[W+1];if(!J)return;let X=ty.get(J)??1,Y=W+2+X;if(Q.length<Y)return;let j=Q.slice(0,Y).join(c3)||c3;return o2(j)?j:void 0}function k9($){try{return cy($,{withFileTypes:!0})}catch{return[]}}function $h($){let Z=R1($,r3);if(!o2(Z))return[];let Q=[];for(let W of k9(Z)){if(!W.isDirectory())continue;let J=R1(Z,W.name);if(W.name==="git"){for(let X of k9(J)){if(!X.isDirectory())continue;let Y=R1(J,X.name);for(let j of k9(Y))if(j.isDirectory())Q.push(R1(Y,j.name))}continue}for(let X of k9(J))if(X.isDirectory())Q.push(R1(J,X.name))}return Q.sort((W,J)=>W.localeCompare(J))}function CF($){try{return ay($)}catch{return[]}}function p3($){let Z=CF($),Q=new Set;o0(Q,l0($)),o0(Q,ey(l0($))),o0(Q,l3(R1($,"package.json"))),o0(Q,l3(R1($,oy,"package.json")));for(let W of Z)o0(Q,l0(W)),o0(Q,d3(l0(W)));return{installPath:$,entryPaths:Z,names:[...Q].sort((W,J)=>W.localeCompare(J)),installed:!0}}function Zh($,Z){let Q=s2($),W=Z.find((Y)=>i3(Q,Y));if(!W)return;let J=B$(Q);while(J!==W&&J!==B$(J)){if(o2(R1(J,"package.json")))return J;J=B$(J)}let X=l0(Q);if((X==="index.ts"||X==="index.js")&&B$(Q)!==W)return B$(Q);return Q}function PF($,Z){let Q=Zh($,Z);if(!Q)return;let W=new Set;return o0(W,l0($)),o0(W,d3(l0($))),o0(W,l0(Q)),o0(W,d3(l0(Q))),o0(W,l3(R1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...W].sort((J,X)=>J.localeCompare(X)),installed:!1}}function Qh($){let Z=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return sy(Z).filter((Q)=>o2(Q))}function Wh($){let Z=new Map;for(let Q of $){for(let W of $h(Q))Z.set(W,p3(W));for(let W of CF(Q)){let J=wF(W);if(J){if(!Z.has(J))Z.set(J,p3(J));continue}let X=PF(W,$);if(X)Z.set(X.installPath,X)}}return[...Z.values()].sort((Q,W)=>Q.installPath.localeCompare(W.installPath))}function Jh($,Z){let Q=u3(Z);if(!Q)return!1;if(u3($.installPath)===Q)return!0;return $.names.some((W)=>u3(W)===Q)}function Xh($,Z,Q){let W=s2($);for(let X of Z){if(i3(W,X.installPath))return X;if(X.entryPaths.some((Y)=>s2(Y)===W))return X}let J=wF(W);if(J)return p3(J);if(o2(W))return PF(W,Q);return}function Yh($){let Z=D0(),Q=Z.disabledPlugins;if(!Q?.length)return;let W=Q.filter((J)=>{let X=s2(J);if(i3(X,$.installPath))return!1;return!$.entryPaths.some((Y)=>s2(Y)===X)});if(W.length===Q.length)return;G1({...Z,disabledPlugins:W})}function jh($){let Z=B$($);while(Z!==B$(Z)&&l0(Z)!==r3){try{dy(Z)}catch{return}Z=B$(Z)}}function Vh($){return`${$.names[0]??l0($.installPath)} at ${$.installPath}`}async function n3($){let Z=Qh($),Q=Wh(Z),W=$.path?.trim(),J=$.name?.trim(),X;if(W){if(X=Xh(W,Q,Z),!X)throw Error(`No plugin found at ${W}`)}else{if(!J)throw Error("plugin uninstall requires a plugin name");let j=Q.filter((V)=>Jh(V,J));if(j.length===0)throw Error(`No plugin found matching "${J}"`);if(j.length>1)throw Error(`Multiple plugins match "${J}": ${j.map(Vh).join(", ")}`);X=j[0]}let Y=py(X.installPath,{throwIfNoEntry:!1});if(!Y)throw Error(`Plugin install path does not exist: ${X.installPath}`);if(v3({pluginPaths:[X.installPath,...X.entryPaths],pluginNames:X.names}),ly(X.installPath,{recursive:Y.isDirectory(),force:!0}),Yh(X),X.installed)jh(X.installPath);return{name:J||X.names[0]||l0(X.installPath),installPath:X.installPath,removedPaths:[X.installPath],entryPaths:X.entryPaths}}var a3=120000,k4=12000,Uh=/(api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|authorization|credential)/i,Dh=/((?:^|[^\w])(?:[a-z0-9_]*?(?:api[_ -]?key|access[_ -]?token|refresh[_ -]?token|auth(?:orization)?[_ -]?token|token|secret|password|credential)[a-z0-9_]*)\s*[:=]\s*)(.+)$/gi,Lh=/((?:^|[^\w])authorization\s*[:=]\s*)bearer\s+([^\s,"'}\]]+)/gi,_h=/((?:^|[^\w])authorization\s*[:=])(?!\s*bearer\b)\s*(.+)$/gi;function s3($){return $.install?.args??[]}function zh(){return process.env.HOME?.trim()||process.env.USERPROFILE?.trim()||Gh()}function Th($){let Z=0,Q=$.length;while(Z<Q&&($[Z]==="."||$[Z]==="-"))Z++;while(Q>Z&&($[Q-1]==="."||$[Q-1]==="-"))Q--;return $.slice(Z,Q)}function Oh($){return Th($.toLowerCase().replace(/[^a-z0-9._]+/g,"-")).slice(0,255)||"skill"}function yF($){return $.split(/\r?\n/).map((Z)=>{if(!Uh.test(Z))return Z;return Z.replace(Dh,"$1[redacted]").replace(Lh,"$1Bearer [redacted]").replace(/\b(Bearer)\s+(?!\[redacted\])([^\s,"'}\]]+)/gi,"$1 [redacted]").replace(_h,"$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(`
739
+ `).slice(-k4)}function qh($){let Z=yF([$.stdout,$.stderr].filter(Boolean).join(`
740
+ `)).trim();return Z.length>0?Z:void 0}function Mh($){if($==="")return'""';if(/^[a-zA-Z0-9_./:=@%+,-]+$/.test($))return $;return JSON.stringify($)}function Rh($,Z){return[$,...Z].map((Q)=>Mh(yF(Q).trim())).join(" ")}var Eh=async($,Z)=>new Promise((Q,W)=>{let J=!1,X=!1,Y=Hh($,Z,{env:process.env,shell:Kh()==="win32",stdio:["ignore","pipe","pipe"],windowsHide:!0}),j="",V="",H=setTimeout(()=>{if(!J)Y.kill("SIGKILL")},a3+5000),B=setTimeout(()=>{X=!0,V+=`
741
+ Timed out after ${a3/1000}s.`,Y.kill("SIGTERM")},a3);H.unref?.(),B.unref?.(),Y.stdout?.on("data",(G)=>{if(j+=String(G),j.length>k4*2)j=j.slice(-k4)}),Y.stderr?.on("data",(G)=>{if(V+=String(G),V.length>k4*2)V=V.slice(-k4)}),Y.once("error",(G)=>{clearTimeout(B),clearTimeout(H),W(G)}),Y.once("close",(G,K)=>{J=!0,clearTimeout(B),clearTimeout(H),Q({exitCode:X?124:G??(K==="SIGINT"?130:1),stdout:j,stderr:V})})});function Nh($){return`${$.type}:${$.id}`}function o3($){let Z=s3($);if(Z.length===0)throw Error("Marketplace install args are required.");return k3(Z).name}function hF($,Z={}){let Q=o3($),W=Z.mcpSettingsPath??fh(),J=U1(W,(X)=>{let Y=X.mcpServers&&typeof X.mcpServers==="object"&&!Array.isArray(X.mcpServers)?X.mcpServers:{},j=Object.hasOwn(Y,Q);if(j)delete Y[Q];return X.mcpServers=Y,j});return{name:Q,deleted:J}}function t3($){let Z=new Set,Q=(J)=>{let X=Oh(J??"");if(X&&X!=="skill")Z.add(X)};Q($.id),Q($.name);let W=s3($);for(let J=0;J<W.length;J++){let X=W[J];if((X==="--skill"||X==="-s")&&W[J+1]){Q(W[J+1]),J++;continue}let Y=X.split("@").at(1);if(Y)Q(Y)}return[...Z]}function e3($){return[SF(Ah(),"skills",$,"SKILL.md"),SF(zh(),".agents","skills",$,"SKILL.md")].filter((Z,Q,W)=>W.indexOf(Z)===Q)}function $J($){if($.type!=="skill")return;return t3($).find((Z)=>e3(Z).some((Q)=>bF(Q)))}function kF($){return $J($)!==void 0}function wh($){let Z=[];if($.type!=="skill")return Z;for(let Q of t3($))for(let W of e3(Q)){if(!bF(W))continue;let J=Fh(W);Bh(J,{recursive:!0,force:!0}),Z.push(J)}return Z}async function IF($,Z={}){let Q=$J($);if(!Q)return{id:$.id,type:"skill",status:"uninstalled",message:`${$.name??$.id} is not installed.`};let W="npx",J=["-y","skills@latest","remove",Q,"-g","-y"],X=Rh(W,J),Y=Z.spawnCommand??Eh,j;try{j=await Y(W,J)}catch(B){throw Error(`Failed to start ${$.name??$.id} uninstall command:
742
742
  ${X}
743
- ${B instanceof Error?B.message:String(B)}`)}let V=_h(j);if(j.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${j.exitCode}.
743
+ ${B instanceof Error?B.message:String(B)}`)}let V=qh(j);if(j.exitCode!==0)throw Error(`${$.name??$.id} uninstall failed with exit code ${j.exitCode}.
744
744
  Command:
745
745
  ${X}${V?`
746
746
 
747
- ${V}`:""}`);let H=Mh($);if(kF($))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,...H.map((B)=>`Removed: ${B}`)].filter(Boolean).join(`
747
+ ${V}`:""}`);let H=wh($);if(kF($))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,...H.map((B)=>`Removed: ${B}`)].filter(Boolean).join(`
748
748
  `)||void 0}}async function xF($,Z={}){let[Q]=s3($),W=Q?.trim()||$.id;if(!W)throw Error("Plugin marketplace uninstalls require a plugin name.");let J=await n3({name:W,workspaceRoot:Z.workspaceRoot});return{id:$.id,type:"plugin",status:"uninstalled",message:`Uninstalled ${$.name??J.name??$.id}.`,output:[`Path: ${J.installPath}`,...J.removedPaths.map((X)=>`Removed: ${X}`)].join(`
749
- `)}}async function Rh($,Z={}){if($.type==="mcp"){let Q=o3($);if(Z.deleteMcpServer)await Z.deleteMcpServer(Q);else hF($,Z);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Q??$.id}.`}}if($.type==="skill")return IF($,Z);if($.type==="plugin")return xF($,Z);throw Error(`Unsupported marketplace entry type: ${$.type}`)}import{spawn as Eh}from"node:child_process";import{createHash as Nh}from"node:crypto";import{existsSync as J1,mkdirSync as WJ,readdirSync as wh,readFileSync as Ch,renameSync as k9,rmSync as g9,statSync as JJ}from"node:fs";import{cp as QJ,mkdir as pF,writeFile as m9}from"node:fs/promises";import{homedir as gF}from"node:os";import{basename as E1,dirname as mF,extname as Ph,join as r,relative as rF,resolve as G$,sep as Sh}from"node:path";import{isPluginModulePath as x9,resolveClineDir as bh,resolvePluginModuleEntries as yh}from"@cline/shared/storage";var t2="_installed",v9="package",hh="https://github.com/cline/plugins.git",vF=30000,I9=10485760,cF="@cline/",kh=["dependencies","devDependencies","optionalDependencies","peerDependencies"],Ih={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function c9($){if($==="~")return gF();if($.startsWith("~/"))return r(gF(),$.slice(2));return $}function iF($){return $.split(Sh).join("/")}function e$($){return Nh("sha256").update($).digest("hex").slice(0,12)}function xh($){let Z=0;while(Z<$.length&&$[Z]==="-")Z++;let Q=$.length;while(Q>Z&&$[Q-1]==="-")Q--;return $.slice(Z,Q)}function R1($){let Z="",Q=!1,W=$.startsWith("@")?$.slice(1):$;for(let X of W.slice(0,256)){if(X>="a"&&X<="z"||X>="A"&&X<="Z"||X>="0"&&X<="9"||X==="."||X==="_"||X==="-")Z+=X,Q=X==="-";else if(!Q)Z+="-",Q=!0;if(Z.length>=80)break}return xh(Z)||"plugin"}function nF($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function gh($){return $?.trim()||hh}function uF($){let Q=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Q?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Q[1]}}function mh($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[Z,...Q]=$.split("/");return!!Z&&Q.length>=2&&Z.includes(".")&&!Z.startsWith(".")&&!Z.endsWith(".")}function vh($){let Z=$.match(/^git@([^:]+):(.+)$/);if(Z){let Y=Z[2]??"",j=Y.indexOf("@");if(j<0)return{repo:$};return{repo:`git@${Z[1]}:${Y.slice(0,j)}`,ref:Y.slice(j+1)||void 0}}if($.includes("://"))try{let Y=new URL($),j=Y.pathname.replace(/^\/+/,""),V=j.indexOf("@");if(V<0)return{repo:$};return Y.pathname=`/${j.slice(0,V)}`,{repo:Y.toString().replace(/\/$/,""),ref:j.slice(V+1)||void 0}}catch{return{repo:$}}let Q=$.indexOf("/");if(Q<0)return{repo:$};let W=$.slice(0,Q),J=$.slice(Q+1),X=J.indexOf("@");if(X<0)return{repo:$};return{repo:`${W}/${J.slice(0,X)}`,ref:J.slice(X+1)||void 0}}function ch($){try{return decodeURIComponent($)}catch{return $}}function uh($){return E1(ch($))||"plugin"}function dh($){let Z=$.split("/").filter(Boolean);return Z.length>=5&&(Z[2]==="blob"||Z[2]==="raw")}function dF($){if(!/^https?:\/\//i.test($))return null;let Z;try{Z=new URL($)}catch{return null}let Q=Z.hostname.toLowerCase(),W=uh(Z.pathname),J=x9(W),X=(Q==="github.com"||Q==="www.github.com")&&dh(Z.pathname);if(Z.protocol!=="https:"){if(X||Q==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Q==="github.com"||Q==="www.github.com"){let Y=Z.pathname.split("/").filter(Boolean);if(!X)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[Y[0],Y[1],...Y.slice(3)].join("/")}`,filename:W}}if(Q==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:Z.toString(),filename:W}}if(!J)return null;return{type:"remote",url:Z.toString(),filename:W}}function lF($,Z={}){let Q=$.trim(),W=Q.startsWith("git:")&&!Q.startsWith("git://"),J=W?Q.slice(4).trim():Q;if(!Z.force&&!W&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:X,ref:Y}=vh(J),j="",V="";if(X.startsWith("git@")){let G=X.match(/^git@([^:]+):(.+)$/);j=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(X)){let G=new URL(X);j=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=X.indexOf("/");if(G<0)return null;j=X.slice(0,G),V=X.slice(G+1)}let H=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!j||!H||H.split("/").length<2)return null;return{type:"git",repo:X.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(X)?X:`https://${X}`,ref:Y,host:j,path:H}}function aF($,Z){let Q=$.trim();if(!Q)throw Error("plugin install requires a source");if(Z==="npm"){let Y=Q.startsWith("npm:")?Q.slice(4).trim():Q,{name:j}=uF(Y);return{type:"npm",spec:Y,name:j}}if(Z==="git"){let Y=lF(Q,{force:!0});if(!Y)throw Error(`Invalid git plugin source: ${$}`);return Y}if(Z==="local")return{type:"local",path:$};if(Z==="remote"){let Y=dF(Q);if(!Y)throw Error(`Invalid remote plugin source: ${$}`);return Y}if(Q.startsWith("npm:")){let Y=Q.slice(4).trim(),{name:j}=uF(Y);return{type:"npm",spec:Y,name:j}}if(Q.startsWith(".")||Q.startsWith("/")||Q==="~"||Q.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Q))return{type:"local",path:$};let J=dF(Q);if(J)return J;let X=lF(Q);if(X)return X;if(nF(Q))return{type:"official",slug:Q};if(mh(Q))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 lh($){return $?r($,".cline","plugins"):r(bh(),"plugins")}function ph($,Z,Q){if(Z.type==="npm")return r($,t2,"npm",`${R1(Z.name)}-${e$(Q)}`);if(Z.type==="git")return r($,t2,"git",R1(Z.host),`${R1(Z.path)}-${e$(Q)}`);if(Z.type==="remote")return r($,t2,"remote",`${R1(Z.filename)}-${e$(Q)}`);if(Z.type==="official")return r($,t2,"official",`${R1(Z.slug)}-${e$(Q)}`);return r($,t2,"local",`${R1(E1(c9(Z.path)))}-${e$(Q)}`)}function rh($,Z,Q){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:${Q}#plugins/${$.slug}`;return`local:${G$(Z,c9($.path))}`}function ih($,Z){if($.type==="npm")return $.name;if($.type==="git")return R1(E1($.path));if($.type==="remote")return R1(E1($.filename,Ph($.filename)));if($.type==="official")return $.slug;return R1(E1(G$(Z,c9($.path))))}async function e2($,Z,Q={}){await new Promise((W,J)=>{let X=Eh($,Z,{cwd:Q.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),Y="";X.stderr.on("data",(j)=>{Y+=String(j)}),X.on("error",J),X.on("close",(j)=>{if(j===0){W();return}let V=Y.trim();J(Error(`${$} ${Z.join(" ")} failed with exit code ${j}${V?`: ${V}`:""}`))})})}function sF($){let Z=r($,"package.json");if(!J1(Z))return null;try{return JSON.parse(Ch(Z,"utf8"))}catch{return null}}function nh($){let Z=$?.cline?.plugins;if(!Array.isArray(Z))return[];return Z.flatMap((Q)=>{if(typeof Q==="string")return[Q];return Q.paths??[]})}async function ah($){let Z=r($,"package.json"),Q=sF($);if(!Q)return;let W=!1;for(let J of kh){let X=Q[J];if(!X||typeof X!=="object")continue;for(let Y of Object.keys(X)){if(!Y.startsWith(cF))continue;delete X[Y],delete Q.peerDependenciesMeta?.[Y],W=!0}if(Object.keys(X).length===0)delete Q[J]}if(Q.peerDependenciesMeta){for(let J of Object.keys(Q.peerDependenciesMeta)){if(!J.startsWith(cF))continue;delete Q.peerDependenciesMeta[J],W=!0}if(Object.keys(Q.peerDependenciesMeta).length===0)delete Q.peerDependenciesMeta}if(!W)return;await m9(Z,`${JSON.stringify(Q,null,2)}
750
- `,"utf8")}function sh($,Z){let Q=r($,"node_modules","@cline");if(!J1(Q))return;for(let W of tF(Q)){if(`@cline/${W.name}`===Z)continue;g9(r(Q,W.name),{recursive:!0,force:!0})}}function oF($){let Z=nh(sF($)).map((X)=>G$($,X)).filter((X)=>J1(X)&&JJ(X).isFile()&&x9(X));if(Z.length>0)return Z;let Q=yh($);if(Q?.length)return Q;let W=[],J=[$];while(J.length>0){let X=J.pop();if(!X)continue;for(let Y of tF(X)){let j=r(X,Y.name);if(Y.name==="node_modules"||Y.name===".git")continue;if(Y.isDirectory()){J.push(j);continue}if(Y.isFile()&&!Y.name.startsWith(".")&&x9(j))W.push(j)}}return W.sort((X,Y)=>X.localeCompare(Y))}function tF($){try{return wh($,{withFileTypes:!0})}catch{return[]}}function oh($,Z){let Q=oF(Z);if(Q.length===0)throw Error(`No plugin entry files found in ${Z}`);return Q.map((W)=>`./${iF(rF($,W))}`)}async function th($,Z,Q){let W=oh($,Z);return await m9(r($,"package.json"),JSON.stringify({...Ih,name:Q,cline:{plugins:[{paths:W}]}},null,2),"utf8"),W}async function eh($,Z,Q){let W=r(Z,v9);return await pF(W,{recursive:!0}),await m9(r(W,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await e2(Q,["install",$.spec,"--prefix",W,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),sh(W,$.name),r(W,"node_modules",$.name)}async function XJ($,Z){if(!J1(r($,"package.json")))return;await ah($),await e2(Z,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function $k($,Z,Q){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let W=r(Z,v9),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,W);try{await e2("git",J)}catch(X){if(!$.ref)throw X;await e2("git",["clone","--filter=blob:none","--",$.repo,W]),await e2("git",["checkout","--detach",$.ref],{cwd:W})}return await XJ(W,Q),W}async function Zk($,Z,Q,W){let J=r(Z,"repo");await e2("git",["clone","--filter=blob:none","--depth","1","--",W,J]);let X=r(J,"plugins",$.slug);if(!J1(X)||!JJ(X).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${W}`);let Y=r(Z,v9);return await QJ(X,Y,{recursive:!0,filter:(j)=>{let V=E1(j);return V!==".git"&&V!=="node_modules"}}),g9(J,{recursive:!0,force:!0}),await XJ(Y,Q),Y}function ZJ($){return Error(`Remote plugin file from ${$} exceeds the ${I9} byte limit`)}function Qk($){let Z=$.headers.get("content-length");if(!Z)return;let Q=Number(Z);if(!Number.isFinite(Q)||Q<0)return;return Q}async function Wk($,Z){let Q=Qk($);if(Q!==void 0&&Q>I9)throw ZJ(Z);if(!$.body){let Y=Buffer.from(await $.text(),"utf8");if(Y.byteLength>I9)throw ZJ(Z);return Y}let W=$.body.getReader(),J=[],X=0;try{while(!0){let{done:Y,value:j}=await W.read();if(Y)break;let V=Buffer.from(j);if(X+=V.byteLength,X>I9)throw await W.cancel().catch(()=>{return}),ZJ(Z);J.push(V)}return Buffer.concat(J,X)}finally{W.releaseLock()}}async function Jk($,Z){let Q=new AbortController,W=setTimeout(()=>{Q.abort()},vF);try{let J=await fetch($.url,{signal:Q.signal});if(!J.ok){let Y=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${Y}`)}let X=await Wk(J,$.url);return WJ(Z,{recursive:!0}),await m9(r(Z,$.filename),X),Z}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${vF}ms`);throw J}finally{clearTimeout(W)}}async function Xk($,Z,Q,W){let J=G$(Q,c9($.path));if(!J1(J))throw Error(`Plugin source path does not exist: ${J}`);let X=JJ(J);if(X.isFile()){if(!x9(J))throw Error(`Plugin file must be .js or .ts: ${J}`);WJ(Z,{recursive:!0});let j=r(Z,E1(J));return await QJ(J,j),Z}if(!X.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let Y=r(Z,v9);return await QJ(J,Y,{recursive:!0,filter:(j)=>{let V=E1(j);return V!==".git"&&V!=="node_modules"}}),await XJ(Y,W),Y}function Yk($,Z){if(J1($)&&!Z)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function jk($,Z,Q){if(WJ(mF(Z),{recursive:!0}),!J1(Z)){k9($,Z);return}if(!Q)throw Error(`Plugin is already installed at ${Z}. Use --force to replace it.`);let W=r(mF(Z),`.replace-${E1(Z)}-${Date.now()}-${process.pid}-${e$(`${Z}:${Math.random()}`)}`);k9(Z,W);try{k9($,Z)}catch(J){if(!J1(Z)&&J1(W))k9(W,Z);throw J}try{g9(W,{recursive:!0,force:!0})}catch{}}function Vk($){let Z=$.transport;if(Z.type==="stdio")return!1;return Z.headers!==void 0&&Object.keys(Z.headers).length>0}function Hk($){let Z=$.oauth?.tokens?.access_token;return typeof Z==="string"&&Z.trim().length>0}function Bk($){let Z=$.metadata;if(!Z||Z.source!=="plugin"||typeof Z.pluginName!=="string"||typeof Z.pluginPath!=="string")return;return{pluginName:Z.pluginName,pluginPath:Z.pluginPath}}function eF($){let Z=new Set($.pluginPaths.map((J)=>G$(J)));if(Z.size===0)return[];let Q;try{Q=$1({filePath:$.settingsPath??Z0()})}catch{return[]}let W=[];for(let J of Q){let X=Bk(J);if(!X||!Z.has(G$(X.pluginPath)))continue;let Y=J.transport.type;if(Y==="stdio")continue;if(Vk(J)||Hk(J))continue;W.push({name:J.name,pluginName:X.pluginName,pluginPath:X.pluginPath,transportType:Y,lastError:J.oauth?.lastError})}return W.sort((J,X)=>J.name.localeCompare(X.name))}async function Gk($){let Z=$.source.trim(),Q=aF(Z,$.sourceType),W=$.cwd?.trim(),J=W?G$(W):process.cwd(),X=lh(W?J:void 0),Y=gh($.officialPluginsRepo),j=rh(Q,J,Y),V=ph(X,Q,j),H=ih(Q,J),B=r(X,t2,".tmp"),G=r(B,`${Date.now()}-${process.pid}-${e$(`${Z}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;Yk(V,F),await pF(B,{recursive:!0});let A;try{if(Q.type==="npm")A=await eh(Q,G,K);else if(Q.type==="git")A=await $k(Q,G,K);else if(Q.type==="official")A=await Zk(Q,G,K,Y);else if(Q.type==="remote")A=await Jk(Q,G);else A=await Xk(Q,G,J,K);let L=(Q.type==="local"||Q.type==="remote")&&A===G?oF(G).map((U)=>`./${iF(rF(G,U))}`):await th(G,A,H);if(L.length===0)throw Error(`No plugin entry files found for ${Z}`);jk(G,V,F);let f={source:Z,installPath:V,entryPaths:L.map((U)=>G$(V,U)),mcpSyncFailures:[],mcpOAuthCandidates:[]},D=await m3({pluginPaths:f.entryPaths,cwd:J,workspacePath:J});return f.mcpSyncFailures=D.failures,f.mcpOAuthCandidates=eF({pluginPaths:f.entryPaths}),f}catch(L){throw g9(G,{recursive:!0,force:!0}),L}}import*as q0 from"@cline/llms";var ZA="cline-pass";function Kk($){return $.apiKey??$.auth?.apiKey}function Fk($){return($.auth?.accessToken?.trim()??"").length>0}function QA($){return $.split(/[-_]/).filter(Boolean).map((Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)).join(" ")}function Ak($){let Z=$.split(/\s+/).filter(Boolean);if(Z.length===0)return"?";if(Z.length===1)return Z[0].slice(0,2).toUpperCase();return`${Z[0][0]}${Z[1][0]}`.toUpperCase()}function fk($){let Z=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let W of $)Q=Q*31+W.charCodeAt(0)>>>0;return Z[Q%Z.length]}function WA($){return Object.entries($).sort(([Z],[Q])=>Z.localeCompare(Q)).map(([Z,Q])=>UG(Z,Q))}async function Uk($,Z){let Q=await q0.getModelsForProvider($),W=$===ZA;if(!Z&&!W)return Q;let J=await hZ($,{loadLatestOnInit:W,loadPrivateOnAuth:!0,failOnError:!1},Z);if($==="litellm"&&J?.knownModels)return J.knownModels;if(W&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Q,...J.knownModels}:Q}function YJ($){return[...new Set(($??[]).map((Z)=>Z.trim()).filter(Boolean))]}function Dk($){if(!$?.length)return;return[...new Set($)]}function Lk($,Z){return Dk([...$??[],...Z??[]])}function _k($){let Z=$?.popularRank;return typeof Z==="number"&&Number.isFinite(Z)?Z:Number.MAX_SAFE_INTEGER}function zk($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.path==="string"&&Z.path.trim().length>0&&typeof Z.label==="string"&&Z.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(Z.type))}function Tk($){let Z=$?.configFields;if(!Array.isArray(Z))return;return Z.filter(zk)}var u9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},$A={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function Ok($){if(!$)return[u9];if($.source!=="system")return $.baseUrl?[u9,$A]:[u9];let Z=[];if($.env?.length)Z.push(u9);if($.baseUrl)Z.push($A);return Z}function qk($,Z){return Z.split(".").reduce((Q,W)=>{if(!Q||typeof Q!=="object")return;return Q[W]},$)}function Mk($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Rk($,Z,Q){if(!$?.length)return;let W={};for(let J of $){let Y=Mk(J.path==="baseUrl"&&Z?.baseUrl===void 0?Q?.baseUrl:qk(Z,J.path))??J.defaultValue;if(Y!==void 0)W[J.path]=Y}return W}function JA($){let Z=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return Z.length>0?Object.fromEntries(Z):void 0}function jJ($,Z){let Q=Z?.includes("vision")??!1,W=Z?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Q,supportsAttachments:Q,supportsReasoning:W}]))}async function XA($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let Z=$.modelsSourceUrl?await o4($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...Z])]}function YA($,Z){let Q=$.read(),W=!1;if(Q.providers[Z])delete Q.providers[Z],W=!0;if(Q.lastUsedProvider===Z)delete Q.lastUsedProvider,W=!0;if(W)$.write(Q);q0.unregisterProvider(Z)}async function Ek($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=Z.baseUrl.trim(),J=Z.apiKey?.trim()??"";if(!W&&!J){let A=p$($);if((await d2(A)).providers[Q]){let f=await VA($,{providerId:Q});return{providerId:Q,settingsPath:f.settingsPath,modelsPath:f.modelsPath,modelsCount:0}}return YA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(q0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let X=Z.name.trim();if(!X)throw Error("name is required");if(!W)throw Error("baseUrl is required");let Y=YJ(Z.models),j=Z.modelsSourceUrl?.trim(),V=await XA({providerId:Q,explicitModels:Y,modelsSourceUrl:j,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let H=Z.defaultModelId?.trim()&&V.includes(Z.defaultModelId.trim())?Z.defaultModelId.trim():V[0],B=Z.capabilities?.length?[...new Set(Z.capabilities)]:void 0,G=JA(Z.headers);$.saveProviderSettings({provider:Q,apiKey:J||void 0,baseUrl:W,headers:G,timeout:Z.timeoutMs,model:H,protocol:Z.protocol,client:Z.client},{setLastUsed:!1});let K=p$($),F=await d2(K);return F.providers[Q]={provider:{name:X,baseUrl:W,defaultModelId:H,protocol:Z.protocol,client:Z.client,capabilities:B,modelsSourceUrl:j},models:jJ(V,B)},await $9(K,F),T4(Q,F.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function jA($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=p$($),J=await d2(W),X=J.providers[Q];if(!X){let O=$.getProviderSettings(Q);if(!O)throw Error(`provider "${Q}" does not exist`);let z=Z.modelsSourceUrl?.trim(),_=YJ(Z.models)[0]??O.model?.trim();if(!_&&!z)throw Error(`provider "${Q}" cannot be updated because no model is configured`);X={provider:{name:Z.name?.trim()||QA(Q),baseUrl:Z.baseUrl?.trim()??O.baseUrl?.trim()??"",defaultModelId:_,protocol:O.protocol,client:O.client,capabilities:O.capabilities},models:_?jJ([_],O.capabilities):{}}}if(!X.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let Y=Z.name?.trim()??X.provider.name.trim();if(!Y)throw Error("name is required");let j=Z.baseUrl?.trim()??X.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let V=Z.capabilities===void 0?X.provider.capabilities:Z.capabilities===null?void 0:[...new Set(Z.capabilities)],H=Z.protocol===void 0?X.provider.protocol:Z.protocol??void 0,B=Z.client===void 0?X.provider.client:Z.client??void 0,G=YJ(Z.models),K=Z.modelsSourceUrl===void 0?X.provider.modelsSourceUrl:Z.modelsSourceUrl?.trim()||void 0,F=Z.models!==void 0||Z.modelsSourceUrl!==void 0&&!!K,A=Object.keys(X.models??{}).map((O)=>O.trim()).filter(Boolean),L=await XA({providerId:Q,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(L.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let f=Z.defaultModelId===void 0?X.provider.defaultModelId?.trim():Z.defaultModelId?.trim(),D=f&&L.includes(f)?f:L[0],T={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:j,model:D};if(H)T.protocol=H;else delete T.protocol;if(B)T.client=B;else delete T.client;if(Z.apiKey!==void 0){let O=Z.apiKey?.trim()??"";if(O)T.apiKey=O;else delete T.apiKey}if(Z.headers!==void 0){let O=JA(Z.headers);if(O)T.headers=O;else delete T.headers}if(Z.timeoutMs!==void 0)if(typeof Z.timeoutMs==="number")T.timeout=Z.timeoutMs;else delete T.timeout;return $.saveProviderSettings(T,{setLastUsed:!1}),J.providers[Q]={provider:{name:Y,baseUrl:j,defaultModelId:D,protocol:H,client:B,capabilities:V,modelsSourceUrl:K},models:jJ(L,V)},await $9(W,J),T4(Q,J.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:L.length}}async function VA($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=p$($),J=await d2(W);if(!J.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete J.providers[Q],await $9(W,J),q0.unregisterProvider(Q),YA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:W}}async function Nk($,Z={}){let Q=$.read(),W=q0.getProviderIds(),J=await Promise.all(W.map(async(Y)=>{let[j,V]=await Promise.all([q0.getProvider(Y),q0.getModelsForProvider(Y)]),H=WA(V),B=Q.providers[Y]?.settings,G=j?.name??QA(Y),K=Lk(j?.capabilities,B?.capabilities),F=Tk(j?.metadata)??Ok(j);return{provider:{id:Y,name:G,models:H.length,color:fk(Y),letter:Ak(G),enabled:Boolean(B),apiKey:B?Kk(B):void 0,oauthAccessTokenPresent:B?Fk(B):void 0,baseUrl:B?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:B?.protocol??j?.protocol,client:B?.client??j?.client,capabilities:K,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:F,configValues:Rk(F,B,j),modelList:H},rank:_k(j?.metadata)}}));J.sort((Y,j)=>{if(Y.rank!==j.rank)return Y.rank-j.rank;return Y.provider.name.localeCompare(j.provider.name)||Y.provider.id.localeCompare(j.provider.id)});let X=J.map((Y)=>Y.provider);if(Z.isClinePassEnabled!==!0)X=X.filter((Y)=>Y.id!==ZA);return{providers:X,settingsPath:$.getFilePath()}}async function wk($,Z){let Q=$.trim(),W=await Uk(Q,Z),J=WA(W);return{providerId:Q,models:J}}function d9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function HA($,Z){if(!d9(Z))return d9($)?{...$}:void 0;let Q=d9($)?{...$}:{};for(let[W,J]of Object.entries(Z)){if(J==null||J===""){delete Q[W];continue}if(d9(J)){let X=HA(Q[W],J);if(X&&Object.keys(X).length>0)Q[W]=X;else delete Q[W];continue}Q[W]=J}return Object.keys(Q).length>0?Q:void 0}function Ck($,Z){let Q=Z.providerId.trim();if(Z.enabled===!1){let X=$.read();if(delete X.providers[Q],X.lastUsedProvider===Q)delete X.lastUsedProvider;return $.write(X),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Q)??{},provider:Q};for(let X of["apiKey","baseUrl","model","region"])if(Object.hasOwn(Z,X)&&typeof Z[X]==="string")if(Z[X].trim().length===0)delete J[X];else J[X]=Z[X];for(let X of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(Z,X))J[X]=Z[X];for(let X of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(Z,X)&&Z[X]!=null){let Y=HA(J[X],Z[X]);if(Y)J[X]=Y;else delete J[X]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function Pk($,Z){let Q=Z.trim(),W=$.getProviderSettings(Q),X=q0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,Y=W?.baseUrl?.trim()||X?.baseUrl?.trim(),j=t4(Y,X?.baseUrl,X?.modelsSourceUrl);if(!W||!X||!Y||!j)return{providerId:Q,refreshed:!1};let V=await jA($,{providerId:Q,name:X.name,baseUrl:Y,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:j,protocol:W.protocol??X.protocol??null,client:W.client??X.client??null,capabilities:W.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:V.modelsCount}}function Sk($){let Z=$.trim().toLowerCase(),Q=B0(Z);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function bk($,Z,Q,W){let J=B0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let X=m4({onPrompt:async(Y)=>Y.defaultValue??"",openUrl:Q,onOpenUrlError:({error:Y})=>{throw Y instanceof Error?Y:Error(String(Y))}});return J.login({settings:Z,callbacks:X,telemetry:W})}function yk($,Z,Q,W,J){return X8({manager:$,providerId:Z,settings:Q,credentials:W,setLastUsed:J?.setLastUsed})}async function hk($,Z,Q,W){let J=m4({onPrompt:async(X)=>X.defaultValue??"",openUrl:Q,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return NZ($,Z,{callbacks:J,telemetry:W})}function kk($){let Z=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return Z&&Z.length>0?Z:void 0}import*as l9 from"@cline/llms";var Ik=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],xk={"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 gk($,Z){let Q={};for(let W of Ik){let J=$[W],X=Z[W];if(J||X)Q[W]={...J,...X}}return Q}function mk($){let Z=xk[$.providerId];if(!Z)return $;return{...$,description:Z.description??$.description,fields:Z.mode==="replace"?Z.fields:gk($.fields,Z.fields)}}var vk=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function ck($,Z){if(!Z?.provider.baseUrl)return!1;if(Z.provider.source!=="system")return!0;return vk.has($)}function uk($){let Z=l9.normalizeProviderId($);if(J8(Z))return{providerId:Z,authMethod:"oauth",fields:{}};let Q=l9.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:Z,authMethod:"local",fields:{}};let W=Q?.provider.baseUrl,J={apiKey:{}};if(ck(Z,Q))J.baseUrl={defaultValue:W};return mk({providerId:Z,authMethod:"api-key",fields:J})}P9();G0();O9();import{appendFileSync as dk,existsSync as VJ,mkdirSync as lk,readFileSync as pk,renameSync as rk,unlinkSync as ik,writeFileSync as nk}from"node:fs";import{join as HJ}from"node:path";import{resolveTeamDataDir as ak}from"@cline/shared/storage";function sk($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class BA{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let Z=sk($.teamName),Q=$.baseDir?.trim()||ak();this.dirPath=HJ(Q,Z),this.statePath=HJ(this.dirPath,"state.json"),this.taskHistoryPath=HJ(this.dirPath,"task-history.jsonl")}loadState(){if(!VJ(this.statePath))return;try{let $=pk(this.statePath,"utf8"),Z=JSON.parse($);if(Z.version!==1||!Z.teamState)return;for(let Q of Z.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return zB(Z.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 Z={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;nk(Q,`${JSON.stringify(Z,null,2)}
751
- `,"utf8"),rk(Q,this.statePath)}appendTaskHistory($){let Z={};switch($.type){case"team_task_updated":Z=$.task;break;case"team_message":Z={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":Z={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":Z={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":Z={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":Z={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),dk(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:Z})}
752
- `,"utf8")}ensureDir(){if(!VJ(this.dirPath))lk(this.dirPath,{recursive:!0})}hasPersistableState($){let Z=$.exportState();if(this.teammateSpecs.size>0)return!0;if(Z.members.some((Q)=>Q.role==="teammate"))return!0;return Z.tasks.length>0||Z.mailbox.length>0||Z.missionLog.length>0}clearPersistedState(){if(VJ(this.statePath))ik(this.statePath)}}import{z as S}from"zod";var GA=S.object({workspaceRoot:S.string().min(1),cwd:S.string().optional(),provider:S.string().min(1),model:S.string().min(1),mode:S.enum(["act","plan"]).default("act"),apiKey:S.string(),systemPrompt:S.string().optional(),rules:S.string().optional(),maxIterations:S.number().int().positive().optional(),enableTools:S.boolean(),enableSpawn:S.boolean().optional(),enableTeams:S.boolean().optional(),autoApproveTools:S.boolean().optional(),missionStepInterval:S.number().int().positive().optional(),missionTimeIntervalMs:S.number().int().positive().optional()}),KA=S.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),FA=S.enum(["user","assistant","tool","system","status","error"]),AA=S.object({id:S.string().min(1),sessionId:S.string().nullable(),role:FA,content:S.string(),createdAt:S.number().int().nonnegative(),meta:S.object({stream:S.enum(["stdout","stderr"]).optional(),toolName:S.string().optional(),iteration:S.number().int().nonnegative().optional(),agentId:S.string().optional(),conversationId:S.string().optional(),hookEventName:S.string().optional(),inputTokens:S.number().int().nonnegative().optional(),outputTokens:S.number().int().nonnegative().optional(),checkpoint:S.object({ref:S.string(),createdAt:S.number().int().nonnegative(),runCount:S.number().int().positive(),kind:S.enum(["stash","commit"]).optional()}).optional()}).optional()}),fA=S.object({toolCalls:S.number().int().nonnegative(),tokensIn:S.number().int().nonnegative(),tokensOut:S.number().int().nonnegative()}),ok=S.object({sessionId:S.string().nullable(),status:KA,config:GA,messages:S.array(AA),rawTranscript:S.string(),error:S.string().nullable(),summary:fA});var tk=fH;import{Agent as M$0,createAgentRuntime as R$0}from"@cline/agents";import{getClineEnvironmentConfig as ek}from"@cline/shared";var $I=5000,UA={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 ZI($){return{recommended:$.recommended.map((Z)=>({...Z,tags:[...Z.tags]})),free:$.free.map((Z)=>({...Z,tags:[...Z.tags]})),clinePass:$.clinePass.map((Z)=>({...Z,tags:[...Z.tags]}))}}function BJ($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.id!=="string"||Z.id.length===0)return null;return{id:Z.id,name:typeof Z.name==="string"&&Z.name.length>0?Z.name:Z.id,description:typeof Z.description==="string"?Z.description:"",tags:Array.isArray(Z.tags)?Z.tags.filter((Q)=>typeof Q==="string"):[]}}function QI($){if(!$||typeof $!=="object")return null;let Z=$,Q=Array.isArray(Z.recommended)?Z.recommended:[],W=Array.isArray(Z.free)?Z.free:[],J=Array.isArray(Z.clinePass)?Z.clinePass:[],X=Q.map(BJ).filter((V)=>V!==null),Y=W.map(BJ).filter((V)=>V!==null),j=J.map(BJ).filter((V)=>V!==null);if(X.length===0&&Y.length===0&&j.length===0)return null;return{recommended:X,free:Y,clinePass:j}}function WI($){let Z=$.baseUrl?.trim();if(Z)return Z;let Q=ek().apiBaseUrl;try{return($.providerSettingsManager??new Y$).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function JI($,Z,Q){let W=new AbortController,J=setTimeout(()=>W.abort(),Q);try{return await $(Z,{signal:W.signal})}finally{clearTimeout(J)}}async function XI($={}){try{let Z=WI($),Q=$.fetchImpl??fetch,W=await JI(Q,`${Z}/api/v1/ai/cline/recommended-models`,$.timeoutMs??$I);if(!W.ok)throw Error(`HTTP ${W.status}`);let J=await W.json(),X=QI(J);if(X)return X}catch{}return ZI(UA)}import{readFile as YI}from"node:fs/promises";import jI from"node:path";function VI($){return $}async function HI($){let Z=jI.resolve($),Q=await YI(Z,"utf8"),W;try{W=JSON.parse(Q)}catch(J){let X=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${Z}": ${X}`)}return BI(W,Z)}function BI($,Z){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${Z}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${Z}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${Z}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as _A,createHandler as FI,createHandlerAsync as AI,getProviderCollection as fI,hasProvider as zA,registerAsyncHandler as UI,registerHandler as DI,registerModel as LI,registerProvider as TA}from"@cline/llms";function DA($){return $?{...$}:{}}function GI($,Z){if($)return $;if(!Z)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[Z]}function KI($,Z){if(!Z.length)throw Error(`Provider "${$}" must include at least one model.`)}function LA($){let Z=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:Z,defaultModel:$.collection.provider.defaultModelId,modelCount:Z.length}}class GJ{providers=new Map;register($){KI($.id,$.models);let Z=$.defaultModel??$.models[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(Z))throw Error(`Default model "${Z}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:Z,defaults:{...Q?.defaults??{},...DA($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:GI($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...DA($.settings)}})}registerModel($,Z){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([Z]),defaultModel:Z,defaults:{}});return}Q.models.add(Z)}createHandlerConfig($){let Z=this.require($.providerId),Q=$.modelId??Z.defaultModel;if(!Z.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...Z.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($,Z){return this.providers.get($)?.models.has(Z)??!1}require($){let Z=this.providers.get($);if(!Z)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return Z}}class KJ{configuredProviders=new GJ;constructor($){this.applyConfig($)}createHandler($){return FI(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return AI(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(TA($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)DI($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)UI($.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 Z=$.exposeModels??Object.keys($.models),Q=$.defaultModel??Z[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);TA({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:Z,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){LI($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[..._A]}async getBuiltInProviders(){return(await Promise.all(_A.map((Z)=>fI(Z)))).filter((Z)=>Z!==void 0).map((Z)=>LA({collection:Z}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,Z){return this.configuredProviders.hasModel($,Z)}applyConfig($){for(let Z of $.providers)this.configuredProviders.registerSelectionConfig(Z);for(let Z of $.models??[])this.registerModel(Z);for(let Z of $.customProviders??[])this.registerProvider(Z);for(let Z of this.configuredProviders.list()){let Q=zA(Z.id),W=this.configuredProviders.createHandlerConfig({providerId:Z.id,modelId:Z.defaultModel}).routingProviderId,J=typeof W==="string"&&zA(W);if(!Q&&!J)throw Error(`Provider "${Z.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function _I($){return new KJ($)}V3();async function v00(){return Promise.resolve().then(() => (P9(),LF))}export{qH as writeHubDiscovery,h1 as writeGlobalSettings,MH as withHubStartupLock,o1 as verifyHubConnection,f1 as updateMcpSettingsFileSync,X5 as updateMcpSettingsFile,eQ as updateMcpServerOAuthStateAsync,h8 as updateMcpServerOAuthState,jA as updateLocalProvider,n3 as uninstallPlugin,IF as uninstallMarketplaceSkill,xF as uninstallMarketplacePlugin,hF as uninstallMarketplaceMcpServerFromSettings,Rh as uninstallMarketplaceEntry,F3 as truncateNotificationBody,U8 as truncateCommandOutput,vZ as toggleDisabledTool,x5 as toTeamProgressLifecycleEvent,B1 as toProviderConfig,IM as toHubStatusUrl,RH as toHubHealthUrl,SW as toHookConfigFileName,m3 as syncPluginMcpServersToSettings,d5 as summarizeUsageFromMessages,lR as stopLocalHubServerGracefully,H1 as startLocalOAuthServer,y3 as startHubWebSocketServer,Je as startHubServer,oA as startClineDeviceAuth,j7 as splitCoreSessionConfig,M5 as spawnDetachedHubServerWithRetry,TR as spawnDetachedHubServer,xU as setTelemetryOptOutGlobally,b8 as setMcpServerDisabled,LX as setDisabledTools,uU as setDisabledPlugin,mU as setAutoUpdateEnabledGlobally,vs as sendHubCommand,X8 as saveProviderOAuthCredentials,Ck as saveLocalProviderSettings,yk as saveLocalProviderOAuthCredentials,s8 as sanitizeSessionToken,HX as safeParseSettings,fU as safeCreateProviderConfig,K9 as runSubprocessEvent,A9 as runHook,yj as reviveTeamStateDates,uH as restartLocalHubIfIdleAfterStartupTimeout,Id as resolveWorkspaceHubOwnerContext,DQ as resolveWorkflowsConfigSearchPaths,fQ as resolveSkillsConfigSearchPaths,L1 as resolveSharedHubOwnerContext,zP as resolveSessionBackend,UQ as resolveRulesConfigSearchPaths,hZ as resolveProviderConfig,bf as resolveProviderApiKeyFromSettings,s1 as resolveProductionHubOwnerContext,z$ as resolvePluginSkillDirectoriesFromPaths,QQ as resolvePluginConfigSearchPaths,$1 as resolveMcpServerRegistrations,o3 as resolveMarketplaceMcpServerName,kk as resolveLocalClineAuthToken,wS as resolveHubUrl,I$ as resolveHubOwnerContext,a1 as resolveHubEndpointOptions,OH as resolveHubBuildId,CW as resolveHooksConfigSearchPaths,G1 as resolveDisabledToolNames,B6 as resolveDisabledPluginPaths,Z0 as resolveDefaultMcpSettingsPath,O5 as resolveDefaultHubPort,iM as resolveDefaultHubPathname,rM as resolveDefaultHubHost,xj as resolveCoreSelectedToolIds,m0 as resolveCoreDistinctId,a7 as resolveCompatibleLocalHubUrl,Ed as resolveClineDir,W4 as resolveClineDataDir,L6 as resolveAndLoadAgentPlugins,_$ as resolveAgentPluginPaths,l7 as requestHubShutdown,zy as requestDesktopToolApproval,v3 as removePluginMcpServersFromSettings,k2 as rememberRecoverableLocalHubUrl,TF as registerRemoteConfigSessionBlobUpload,k8 as registerMcpServersFromSettingsFile,U10 as registerDisposable,Pk as refreshProviderModelsFromSource,bJ as refreshOpenAICodexToken,vJ as refreshOcaToken,PJ as refreshClineToken,O4 as readSessionCheckpointHistory,By as readRemoteConfigSessionBlobUploadMetadata,A0 as readHubDiscovery,R0 as readGlobalSettings,FF as readBearerToken,x$ as probeHubServer,ms as probeHubConnection,hY as prewarmFileIndex,bH as prewarmDetachedHubServer,Fy as prepareRemoteConfigCoreIntegration,AQ as parseWorkflowConfigFromMarkdown,f10 as parseUserCommandEnvelope,KQ as parseSkillConfigFromMarkdown,VX as parseSettings,FQ as parseRuleConfigFromMarkdown,aF as parsePluginSource,k3 as parseMcpInstallArgs,F9 as parseHookEventPayload,WW as parseConfiguredAgentConfig,S$ as normalizeWorkspacePath,A10 as normalizeUserInput,F10 as normalizeSdkError,T0 as normalizeRuntimeCapabilities,X6 as normalizeProviderId,Sk as normalizeOAuthProvider,I2 as normalizeHubWebSocketUrl,K10 as noopBasicLogger,cW as migrateLegacyProviderSettings,R6 as mergeRulesForSystemPrompt,_4 as mergeAgentHooks,qh as marketplaceEntryKey,C7 as makeTeamTaskSubSessionId,D5 as makeSubSessionId,LZ as loginOpenAICodex,MZ as loginOcaOAuth,bk as loginLocalProvider,UZ as loginClineOAuth,NZ as loginAndSaveProviderOAuthCredentials,hk as loginAndSaveLocalProviderOAuthCredentials,v00 as loadOpenTelemetryAdapter,S8 as loadMcpSettingsFile,HI as loadLlmsConfigFromFile,y5 as loadConfiguredAgentConfigs,B8 as loadAgentPluginsFromPathsWithDiagnostics,yX as loadAgentPluginsFromPaths,sZ as loadAgentPluginFromPath,TM as listSessionHistoryFromBackend,qV as listPluginToolsWithDiagnostics,X7 as listPluginTools,$7 as listMcpServerOAuthStatuses,Nk as listLocalProviders,c2 as listHookConfigFiles,vU as isToolDisabledGlobally,mZ as isTelemetryOptedOutGlobally,P$ as isSessionNotFoundError,tX as isRuleEnabled,cU as isPluginDisabledGlobally,nF as isOfficialPluginSlug,J8 as isOAuthProvider,kF as isMarketplaceSkillInstalled,Wy as isLocalHubOrigin,AF as isLocalHubHostName,xR as isHubReconnectableTransportError,vH as isHubCommandTimeoutError,Cd as isDiscoveryFilePresent,t00 as isClineOrgIndividualInferenceSubscriptionMessage,o00 as isClineOrgIndividualInferenceSubscriptionError,s00 as isClineNotSubscribedMessage,a00 as isClineNotSubscribedError,DJ as isClineAccountActionRequest,GU as isBuiltInProviderId,gU as isAutoUpdateEnabledGlobally,Gk as installPlugin,Ny as installMcpServer,S1 as identifyAccount,w$ as hasMcpSettingsFile,_Z as getValidOpenAICodexCredentials,RZ as getValidOcaCredentials,DZ as getValidClineCredentials,wZ as getProviderOAuthCredentialsFromSettings,uk as getProviderConfigFields,oJ as getProviderConfig,Sf as getProviderAuthStorageId,B0 as getProviderAuthHandler,s4 as getPersistedProviderApiKey,y8 as getMcpServerOAuthState,t3 as getMarketplaceSkillCandidates,wk as getLocalProviderModels,J6 as getLiveModelsCatalog,e3 as getGlobalMarketplaceSkillPaths,q$ as getFileIndex,oN as getCurrentContextSize,pQ as getCoreHeadlessToolNames,Ij as getCoreDefaultEnabledToolIds,N8 as getCoreBuiltinToolCatalog,gj as getCoreAcpToolNames,n00 as getClinePassSubscriptionUrl,r00 as getClineOrgIndividualInferenceSubscriptionMessage,i00 as getClineNotSubscribedMessage,$10 as getClineDefaultSystemPrompt,K7 as generateWorkspaceInfoWithDiagnostics,f5 as generateWorkspaceInfo,M6 as formatRulesForSystemPrompt,yf as formatProviderOAuthApiKey,G10 as formatDisplayUserInput,$J as findInstalledGlobalMarketplaceSkillName,W9 as findCheckpointForRun,uZ as filterExtensionToolRegistrations,k1 as filterDisabledTools,cZ as filterDisabledPluginPaths,XI as fetchClineRecommendedModels,LJ as executeClineAccountAction,fF as ensureHubWebSocketServer,Xe as ensureHubServer,id as ensureDetachedHubServer,qG as ensureCustomProvidersLoaded,X4 as ensureCompatibleLocalHubUrl,d6 as enrichPromptWithMentions,V10 as emptyWorkspaceManifest,u2 as emptyStoredProviderSettings,WQ as discoverPluginModulePaths,Iy as disablePluginMcpServersInSettings,P7 as deriveSubsessionStatus,VA as deleteLocalProvider,VI as defineLlmsConfig,zQ as createWorkflowsConfigDefinition,w2 as createUserInstructionConfigService,mY as createToolPoliciesWithPreset,j10 as createTool,cG as createTeamName,VK as createSubprocessHooks,N2 as createSpawnAgentTool,LQ as createSkillsConfigDefinition,MQ as createShellTool,D8 as createShellExecutor,B9 as createSessionHost,B9 as createRuntimeHost,_Q as createRulesConfigDefinition,Ky as createRemoteConfigSessionMessagesArtifactUploader,AU as createProviderConfig,z9 as createOpenTelemetryTelemetryService,m4 as createOAuthClientCallbacks,K5 as createMcpTools,ts as createLocalHubScheduleRuntimeHandlers,_I as createLlmsSdk,L0 as createInitialAccumulatedUsage,wd as createInMemoryHubOwnerContext,D1 as createHubServerUrl,TH as createHubAuthToken,kW as createHookConfigFileHooks,a5 as createHookConfigFileExtension,n5 as createHookAuditHooks,J7 as createDisabledMcpToolPolicy,zV as createDisabledMcpToolPolicies,R2 as createDelegatedAgentConfigProvider,E2 as createDelegatedAgent,vY as createDefaultToolsWithPreset,T2 as createDefaultTools,CQ as createDefaultShellExecutor,B5 as createDefaultMcpServerClientFactory,i6 as createDefaultExecutors,v8 as createCoreSettingsService,t1 as createCoreSessionSnapshot,Y10 as createContributionRegistry,EW as createContextCompactionPrepareTurn,a$ as createConfiguredTelemetryService,T9 as createConfiguredTelemetryHandle,k5 as createConfiguredAgentTools,X10 as createClineTelemetryServiceMetadata,J10 as createClineTelemetryServiceConfig,$K as createCheckpointComparePlan,w8 as createBuiltinTools,E8 as createAgentTeamsTools,R$0 as createAgentRuntime,l5 as createAgentHooksExtension,FK as connectToHub,tA as completeClineDeviceAuth,J3 as compareCheckpointToWorkspace,eF as collectPluginMcpOAuthCandidates,VU as clearPrivateModelsCatalogCache,jU as clearLiveModelsCatalogCache,a0 as clearHubDiscovery,IA as captureWorkspacePathResolved,s9 as captureWorkspaceInitialized,o9 as captureWorkspaceInitError,Q8 as captureToolUsage,$Z as captureTokenUsage,e9 as captureTaskRestarted,t9 as captureTaskCreated,c4 as captureTaskCompleted,d4 as captureSubagentExecution,QZ as captureSkillUsed,W10 as captureSdkError,xA as captureProviderConfigured,u4 as captureProviderApiError,ZZ as captureModeSwitch,JZ as captureMentionUsed,YZ as captureMentionSearchResults,XZ as captureMentionFailed,VZ as captureHookDiscovery,kA as captureExtensionActivated,WZ as captureDiffEditFailure,Z8 as captureConversationTurnEvent,BZ as captureCompactionSkipped,HZ as captureCompactionExecuted,C1 as captureAuthSucceeded,w1 as captureAuthStarted,A$ as captureAuthLoggedOut,P1 as captureAuthFailed,PA as captureAgentUnexpectedReasoningTokens,jZ as captureAgentTeamCreated,f$ as captureAgentCreated,F7 as buildWorkspaceMetadata,I5 as buildTeamProgressSummary,Z10 as buildSdkErrorProperties,_F as buildRemoteConfigSessionBlobUploadMetadata,MF as buildMcpInstallTransport,M8 as buildDelegatedAgentConfig,XW as buildConfiguredAgentToolName,YW as buildConfiguredAgentToolDescriptors,ZK as buildCheckpointWorkspaceDiff,Z5 as bootstrapAgentTeams,VV as authorizeMcpServerOAuth,Ek as addLocalProvider,f0 as accumulateUsageTotals,VQ as WORKFLOWS_CONFIG_DIRECTORY_NAME,j8 as UnifiedConfigFileWatcher,e0 as ToolPresets,P4 as TelemetryService,_9 as TelemetryLoggerSink,$5 as TEAM_TOOL_NAMES,K6 as SubprocessSandbox,f8 as StructuredCommandInputSchema,s5 as StoredProviderSettingsSchema,WG as StoredProviderSettingsEntrySchema,q4 as SqliteTeamStore,Z$ as SqliteSessionStore,r2 as SessionVersioningService,s0 as SessionVersioningError,z0 as SessionSource,C$ as SessionNotFoundError,XX as SapSettingsSchema,jQ as SKILLS_CONFIG_DIRECTORY_NAME,xZ as SESSION_STATUSES,c8 as SESSION_NOT_FOUND_ERROR_CODE,D10 as SDK_ERROR_TELEMETRY_EVENT,a9 as RpcClineAccountService,w5 as RemoteRuntimeHost,ZX as ReasoningSettingsSchema,pX as RULES_CONFIG_DIRECTORY_NAME,zF as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,V2 as ProviderSettingsSchema,Y$ as ProviderSettingsManager,tJ as ProviderProtocolSchema,IZ as ProviderIdSchema,eJ as ProviderClientSchema,S4 as OpenTelemetryProvider,YX as OcaSettingsSchema,yZ as OPENAI_COMPATIBLE_PROVIDERS,_1 as NodeHubClient,w4 as NoOpFeatureFlagsProvider,w3 as NativeHubTransportAdapter,jX as ModelCatalogSettingsSchema,W5 as McpSettingsUpdateSkippedError,C2 as McpSettingsMutatorPurityError,P2 as McpSettingsLockTimeoutError,O$ as MAX_COMMAND_OUTPUT_CHARS,j$ as LocalRuntimeHost,u00 as Llms,o5 as InMemoryWorkspaceManager,I8 as InMemoryMcpManager,yS as HubUIClient,g0 as HubTransportError,bS as HubSessionClient,C9 as HubServerTransport,L9 as HubScheduleService,f9 as HubScheduleCommandService,c$ as HubRuntimeHost,R5 as HubCommandError,YK as HookEventPayloadSchema,XK as HookEventNameSchema,p5 as HookConfigFileName,PW as HOOK_CONFIG_FILE_EVENT_MAP,nB as HOOKS_CONFIG_DIRECTORY_NAME,H6 as GlobalSettingsSchema,WX as GcpSettingsSchema,BA as FileTeamPersistenceStore,N4 as FeatureFlagsService,B10 as FeatureFlagDefaultValue,H10 as FEATURE_FLAGS,UA as FALLBACK_CLINE_RECOMMENDED_MODELS,D0 as DefaultToolNames,j9 as DefaultRuntimeBuilder,KJ as DefaultLlmsSdk,nJ as DEFAULT_MODELS_CATALOG_URL,lM as DEFAULT_HUB_PORT,pM as DEFAULT_HUB_PATHNAME,dM as DEFAULT_HUB_HOST,h2 as CoreSettingsService,Q$ as CoreSessionService,Q10 as ContributionRegistry,p00 as ClineOrgIndividualInferenceSubscriptionError,l00 as ClineNotSubscribedError,Y3 as ClineCore,n9 as ClineAccountService,ok as ChatViewStateSchema,fA as ChatSummarySchema,KA as ChatSessionStatusSchema,GA as ChatSessionConfigSchema,AA as ChatMessageSchema,FA as ChatMessageRoleSchema,I as CORE_TELEMETRY_EVENTS,tk as CORE_BUILD_VERSION,N3 as BrowserWebSocketHubAdapter,BU as BUILT_IN_PROVIDER_IDS,kZ as BUILT_IN_PROVIDER,JX as AzureSettingsSchema,QX as AwsSettingsSchema,$X as AuthSettingsSchema,B4 as AgentTeamsRuntime,VW as AgentTeam,M$0 as Agent,U2 as ALL_DEFAULT_TOOL_NAMES};
749
+ `)}}async function Ch($,Z={}){if($.type==="mcp"){let Q=o3($);if(Z.deleteMcpServer)await Z.deleteMcpServer(Q);else hF($,Z);return{id:$.id,type:$.type,status:"uninstalled",message:`Uninstalled ${$.name??Q??$.id}.`}}if($.type==="skill")return IF($,Z);if($.type==="plugin")return xF($,Z);throw Error(`Unsupported marketplace entry type: ${$.type}`)}import{spawn as Ph}from"node:child_process";import{createHash as Sh}from"node:crypto";import{existsSync as J1,mkdirSync as WJ,readdirSync as bh,readFileSync as yh,renameSync as I9,rmSync as m9,statSync as JJ}from"node:fs";import{cp as QJ,mkdir as pF,writeFile as v9}from"node:fs/promises";import{homedir as gF}from"node:os";import{basename as N1,dirname as mF,extname as hh,join as r,relative as rF,resolve as G$,sep as kh}from"node:path";import{isPluginModulePath as g9,resolveClineDir as Ih,resolvePluginModuleEntries as xh}from"@cline/shared/storage";var t2="_installed",c9="package",gh="https://github.com/cline/plugins.git",vF=30000,x9=10485760,cF="@cline/",mh=["dependencies","devDependencies","optionalDependencies","peerDependencies"],vh={name:"cline-installed-plugin",private:!0,cline:{plugins:[]}};function u9($){if($==="~")return gF();if($.startsWith("~/"))return r(gF(),$.slice(2));return $}function iF($){return $.split(kh).join("/")}function $2($){return Sh("sha256").update($).digest("hex").slice(0,12)}function ch($){let Z=0;while(Z<$.length&&$[Z]==="-")Z++;let Q=$.length;while(Q>Z&&$[Q-1]==="-")Q--;return $.slice(Z,Q)}function E1($){let Z="",Q=!1,W=$.startsWith("@")?$.slice(1):$;for(let X of W.slice(0,256)){if(X>="a"&&X<="z"||X>="A"&&X<="Z"||X>="0"&&X<="9"||X==="."||X==="_"||X==="-")Z+=X,Q=X==="-";else if(!Q)Z+="-",Q=!0;if(Z.length>=80)break}return ch(Z)||"plugin"}function nF($){return/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test($.trim())}function uh($){return $?.trim()||gh}function uF($){let Q=$.trim().match(/^(@?[^@/]+(?:\/[^@/]+)?)(?:@.+)?$/);if(!Q?.[1])throw Error(`Invalid npm plugin source: npm:${$}`);return{name:Q[1]}}function dh($){if($.startsWith(".")||$.startsWith("/")||$==="~"||$.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test($))return!1;let[Z,...Q]=$.split("/");return!!Z&&Q.length>=2&&Z.includes(".")&&!Z.startsWith(".")&&!Z.endsWith(".")}function lh($){let Z=$.match(/^git@([^:]+):(.+)$/);if(Z){let Y=Z[2]??"",j=Y.indexOf("@");if(j<0)return{repo:$};return{repo:`git@${Z[1]}:${Y.slice(0,j)}`,ref:Y.slice(j+1)||void 0}}if($.includes("://"))try{let Y=new URL($),j=Y.pathname.replace(/^\/+/,""),V=j.indexOf("@");if(V<0)return{repo:$};return Y.pathname=`/${j.slice(0,V)}`,{repo:Y.toString().replace(/\/$/,""),ref:j.slice(V+1)||void 0}}catch{return{repo:$}}let Q=$.indexOf("/");if(Q<0)return{repo:$};let W=$.slice(0,Q),J=$.slice(Q+1),X=J.indexOf("@");if(X<0)return{repo:$};return{repo:`${W}/${J.slice(0,X)}`,ref:J.slice(X+1)||void 0}}function ph($){try{return decodeURIComponent($)}catch{return $}}function rh($){return N1(ph($))||"plugin"}function ih($){let Z=$.split("/").filter(Boolean);return Z.length>=5&&(Z[2]==="blob"||Z[2]==="raw")}function dF($){if(!/^https?:\/\//i.test($))return null;let Z;try{Z=new URL($)}catch{return null}let Q=Z.hostname.toLowerCase(),W=rh(Z.pathname),J=g9(W),X=(Q==="github.com"||Q==="www.github.com")&&ih(Z.pathname);if(Z.protocol!=="https:"){if(X||Q==="raw.githubusercontent.com"||J)throw Error(`Remote plugin file URLs must use https: ${$}`);return null}if(Q==="github.com"||Q==="www.github.com"){let Y=Z.pathname.split("/").filter(Boolean);if(!X)return null;if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:`https://raw.githubusercontent.com/${[Y[0],Y[1],...Y.slice(3)].join("/")}`,filename:W}}if(Q==="raw.githubusercontent.com"){if(!J)throw Error(`Remote plugin file must be .js or .ts: ${$}`);return{type:"remote",url:Z.toString(),filename:W}}if(!J)return null;return{type:"remote",url:Z.toString(),filename:W}}function lF($,Z={}){let Q=$.trim(),W=Q.startsWith("git:")&&!Q.startsWith("git://"),J=W?Q.slice(4).trim():Q;if(!Z.force&&!W&&!/^(https?|ssh|git):\/\//i.test(J))return null;let{repo:X,ref:Y}=lh(J),j="",V="";if(X.startsWith("git@")){let G=X.match(/^git@([^:]+):(.+)$/);j=G?.[1]??"",V=G?.[2]??""}else if(/^(https?|ssh|git):\/\//i.test(X)){let G=new URL(X);j=G.hostname,V=G.pathname.replace(/^\/+/,"")}else{let G=X.indexOf("/");if(G<0)return null;j=X.slice(0,G),V=X.slice(G+1)}let H=V.replace(/\.git$/,"").replace(/^\/+/,"");if(!j||!H||H.split("/").length<2)return null;return{type:"git",repo:X.startsWith("git@")||/^(https?|ssh|git):\/\//i.test(X)?X:`https://${X}`,ref:Y,host:j,path:H}}function aF($,Z){let Q=$.trim();if(!Q)throw Error("plugin install requires a source");if(Z==="npm"){let Y=Q.startsWith("npm:")?Q.slice(4).trim():Q,{name:j}=uF(Y);return{type:"npm",spec:Y,name:j}}if(Z==="git"){let Y=lF(Q,{force:!0});if(!Y)throw Error(`Invalid git plugin source: ${$}`);return Y}if(Z==="local")return{type:"local",path:$};if(Z==="remote"){let Y=dF(Q);if(!Y)throw Error(`Invalid remote plugin source: ${$}`);return Y}if(Q.startsWith("npm:")){let Y=Q.slice(4).trim(),{name:j}=uF(Y);return{type:"npm",spec:Y,name:j}}if(Q.startsWith(".")||Q.startsWith("/")||Q==="~"||Q.startsWith("~/")||/^[A-Za-z]:[\\/]|^\\\\/.test(Q))return{type:"local",path:$};let J=dF(Q);if(J)return J;let X=lF(Q);if(X)return X;if(nF(Q))return{type:"official",slug:Q};if(dh(Q))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 nh($){return $?r($,".cline","plugins"):r(Ih(),"plugins")}function ah($,Z,Q){if(Z.type==="npm")return r($,t2,"npm",`${E1(Z.name)}-${$2(Q)}`);if(Z.type==="git")return r($,t2,"git",E1(Z.host),`${E1(Z.path)}-${$2(Q)}`);if(Z.type==="remote")return r($,t2,"remote",`${E1(Z.filename)}-${$2(Q)}`);if(Z.type==="official")return r($,t2,"official",`${E1(Z.slug)}-${$2(Q)}`);return r($,t2,"local",`${E1(N1(u9(Z.path)))}-${$2(Q)}`)}function sh($,Z,Q){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:${Q}#plugins/${$.slug}`;return`local:${G$(Z,u9($.path))}`}function oh($,Z){if($.type==="npm")return $.name;if($.type==="git")return E1(N1($.path));if($.type==="remote")return E1(N1($.filename,hh($.filename)));if($.type==="official")return $.slug;return E1(N1(G$(Z,u9($.path))))}async function e2($,Z,Q={}){await new Promise((W,J)=>{let X=Ph($,Z,{cwd:Q.cwd,stdio:["ignore","ignore","pipe"],env:process.env,windowsHide:!0}),Y="";X.stderr.on("data",(j)=>{Y+=String(j)}),X.on("error",J),X.on("close",(j)=>{if(j===0){W();return}let V=Y.trim();J(Error(`${$} ${Z.join(" ")} failed with exit code ${j}${V?`: ${V}`:""}`))})})}function sF($){let Z=r($,"package.json");if(!J1(Z))return null;try{return JSON.parse(yh(Z,"utf8"))}catch{return null}}function th($){let Z=$?.cline?.plugins;if(!Array.isArray(Z))return[];return Z.flatMap((Q)=>{if(typeof Q==="string")return[Q];return Q.paths??[]})}async function eh($){let Z=r($,"package.json"),Q=sF($);if(!Q)return;let W=!1;for(let J of mh){let X=Q[J];if(!X||typeof X!=="object")continue;for(let Y of Object.keys(X)){if(!Y.startsWith(cF))continue;delete X[Y],delete Q.peerDependenciesMeta?.[Y],W=!0}if(Object.keys(X).length===0)delete Q[J]}if(Q.peerDependenciesMeta){for(let J of Object.keys(Q.peerDependenciesMeta)){if(!J.startsWith(cF))continue;delete Q.peerDependenciesMeta[J],W=!0}if(Object.keys(Q.peerDependenciesMeta).length===0)delete Q.peerDependenciesMeta}if(!W)return;await v9(Z,`${JSON.stringify(Q,null,2)}
750
+ `,"utf8")}function $k($,Z){let Q=r($,"node_modules","@cline");if(!J1(Q))return;for(let W of tF(Q)){if(`@cline/${W.name}`===Z)continue;m9(r(Q,W.name),{recursive:!0,force:!0})}}function oF($){let Z=th(sF($)).map((X)=>G$($,X)).filter((X)=>J1(X)&&JJ(X).isFile()&&g9(X));if(Z.length>0)return Z;let Q=xh($);if(Q?.length)return Q;let W=[],J=[$];while(J.length>0){let X=J.pop();if(!X)continue;for(let Y of tF(X)){let j=r(X,Y.name);if(Y.name==="node_modules"||Y.name===".git")continue;if(Y.isDirectory()){J.push(j);continue}if(Y.isFile()&&!Y.name.startsWith(".")&&g9(j))W.push(j)}}return W.sort((X,Y)=>X.localeCompare(Y))}function tF($){try{return bh($,{withFileTypes:!0})}catch{return[]}}function Zk($,Z){let Q=oF(Z);if(Q.length===0)throw Error(`No plugin entry files found in ${Z}`);return Q.map((W)=>`./${iF(rF($,W))}`)}async function Qk($,Z,Q){let W=Zk($,Z);return await v9(r($,"package.json"),JSON.stringify({...vh,name:Q,cline:{plugins:[{paths:W}]}},null,2),"utf8"),W}async function Wk($,Z,Q){let W=r(Z,c9);return await pF(W,{recursive:!0}),await v9(r(W,"package.json"),JSON.stringify({name:"cline-plugin-install",private:!0},null,2),"utf8"),await e2(Q,["install",$.spec,"--prefix",W,"--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"]),$k(W,$.name),r(W,"node_modules",$.name)}async function XJ($,Z){if(!J1(r($,"package.json")))return;await eh($),await e2(Z,["install","--omit=dev","--omit=peer","--legacy-peer-deps","--no-audit","--no-fund","--package-lock=false"],{cwd:$})}async function Jk($,Z,Q){if($.ref?.startsWith("-"))throw Error(`Invalid git ref "${$.ref}".`);let W=r(Z,c9),J=["clone","--filter=blob:none"];if($.ref)J.push("--branch",$.ref);J.push("--",$.repo,W);try{await e2("git",J)}catch(X){if(!$.ref)throw X;await e2("git",["clone","--filter=blob:none","--",$.repo,W]),await e2("git",["checkout","--detach",$.ref],{cwd:W})}return await XJ(W,Q),W}async function Xk($,Z,Q,W){let J=r(Z,"repo");await e2("git",["clone","--filter=blob:none","--depth","1","--",W,J]);let X=r(J,"plugins",$.slug);if(!J1(X)||!JJ(X).isDirectory())throw Error(`Official Cline plugin "${$.slug}" was not found at plugins/${$.slug} in ${W}`);let Y=r(Z,c9);return await QJ(X,Y,{recursive:!0,filter:(j)=>{let V=N1(j);return V!==".git"&&V!=="node_modules"}}),m9(J,{recursive:!0,force:!0}),await XJ(Y,Q),Y}function ZJ($){return Error(`Remote plugin file from ${$} exceeds the ${x9} byte limit`)}function Yk($){let Z=$.headers.get("content-length");if(!Z)return;let Q=Number(Z);if(!Number.isFinite(Q)||Q<0)return;return Q}async function jk($,Z){let Q=Yk($);if(Q!==void 0&&Q>x9)throw ZJ(Z);if(!$.body){let Y=Buffer.from(await $.text(),"utf8");if(Y.byteLength>x9)throw ZJ(Z);return Y}let W=$.body.getReader(),J=[],X=0;try{while(!0){let{done:Y,value:j}=await W.read();if(Y)break;let V=Buffer.from(j);if(X+=V.byteLength,X>x9)throw await W.cancel().catch(()=>{return}),ZJ(Z);J.push(V)}return Buffer.concat(J,X)}finally{W.releaseLock()}}async function Vk($,Z){let Q=new AbortController,W=setTimeout(()=>{Q.abort()},vF);try{let J=await fetch($.url,{signal:Q.signal});if(!J.ok){let Y=J.statusText?` ${J.statusText}`:"";throw Error(`Failed to download plugin file from ${$.url}: ${J.status}${Y}`)}let X=await jk(J,$.url);return WJ(Z,{recursive:!0}),await v9(r(Z,$.filename),X),Z}catch(J){if(J instanceof Error&&J.name==="AbortError")throw Error(`Timed out downloading plugin file from ${$.url} after ${vF}ms`);throw J}finally{clearTimeout(W)}}async function Hk($,Z,Q,W){let J=G$(Q,u9($.path));if(!J1(J))throw Error(`Plugin source path does not exist: ${J}`);let X=JJ(J);if(X.isFile()){if(!g9(J))throw Error(`Plugin file must be .js or .ts: ${J}`);WJ(Z,{recursive:!0});let j=r(Z,N1(J));return await QJ(J,j),Z}if(!X.isDirectory())throw Error(`Plugin source must be a file or directory: ${J}`);let Y=r(Z,c9);return await QJ(J,Y,{recursive:!0,filter:(j)=>{let V=N1(j);return V!==".git"&&V!=="node_modules"}}),await XJ(Y,W),Y}function Bk($,Z){if(J1($)&&!Z)throw Error(`Plugin is already installed at ${$}. Use --force to replace it.`)}function Gk($,Z,Q){if(WJ(mF(Z),{recursive:!0}),!J1(Z)){I9($,Z);return}if(!Q)throw Error(`Plugin is already installed at ${Z}. Use --force to replace it.`);let W=r(mF(Z),`.replace-${N1(Z)}-${Date.now()}-${process.pid}-${$2(`${Z}:${Math.random()}`)}`);I9(Z,W);try{I9($,Z)}catch(J){if(!J1(Z)&&J1(W))I9(W,Z);throw J}try{m9(W,{recursive:!0,force:!0})}catch{}}function Kk($){let Z=$.transport;if(Z.type==="stdio")return!1;return Z.headers!==void 0&&Object.keys(Z.headers).length>0}function Fk($){let Z=$.oauth?.tokens?.access_token;return typeof Z==="string"&&Z.trim().length>0}function Ak($){let Z=$.metadata;if(!Z||Z.source!=="plugin"||typeof Z.pluginName!=="string"||typeof Z.pluginPath!=="string")return;return{pluginName:Z.pluginName,pluginPath:Z.pluginPath}}function eF($){let Z=new Set($.pluginPaths.map((J)=>G$(J)));if(Z.size===0)return[];let Q;try{Q=$1({filePath:$.settingsPath??Z0()})}catch{return[]}let W=[];for(let J of Q){let X=Ak(J);if(!X||!Z.has(G$(X.pluginPath)))continue;let Y=J.transport.type;if(Y==="stdio")continue;if(Kk(J)||Fk(J))continue;W.push({name:J.name,pluginName:X.pluginName,pluginPath:X.pluginPath,transportType:Y,lastError:J.oauth?.lastError})}return W.sort((J,X)=>J.name.localeCompare(X.name))}async function fk($){let Z=$.source.trim(),Q=aF(Z,$.sourceType),W=$.cwd?.trim(),J=W?G$(W):process.cwd(),X=nh(W?J:void 0),Y=uh($.officialPluginsRepo),j=sh(Q,J,Y),V=ah(X,Q,j),H=oh(Q,J),B=r(X,t2,".tmp"),G=r(B,`${Date.now()}-${process.pid}-${$2(`${Z}:${Math.random()}`)}`),K=$.npmCommand??(process.env.CLINE_NPM_COMMAND?.trim()||"npm"),F=$.force===!0;Bk(V,F),await pF(B,{recursive:!0});let A;try{if(Q.type==="npm")A=await Wk(Q,G,K);else if(Q.type==="git")A=await Jk(Q,G,K);else if(Q.type==="official")A=await Xk(Q,G,K,Y);else if(Q.type==="remote")A=await Vk(Q,G);else A=await Hk(Q,G,J,K);let L=(Q.type==="local"||Q.type==="remote")&&A===G?oF(G).map((U)=>`./${iF(rF(G,U))}`):await Qk(G,A,H);if(L.length===0)throw Error(`No plugin entry files found for ${Z}`);Gk(G,V,F);let f={source:Z,installPath:V,entryPaths:L.map((U)=>G$(V,U)),mcpSyncFailures:[],mcpOAuthCandidates:[]},D=await m3({pluginPaths:f.entryPaths,cwd:J,workspacePath:J});return f.mcpSyncFailures=D.failures,f.mcpOAuthCandidates=eF({pluginPaths:f.entryPaths}),f}catch(L){throw m9(G,{recursive:!0,force:!0}),L}}import*as M0 from"@cline/llms";var ZA="cline-pass";function Uk($){return $.apiKey??$.auth?.apiKey}function Dk($){return($.auth?.accessToken?.trim()??"").length>0}function QA($){return $.split(/[-_]/).filter(Boolean).map((Z)=>Z.charAt(0).toUpperCase()+Z.slice(1)).join(" ")}function Lk($){let Z=$.split(/\s+/).filter(Boolean);if(Z.length===0)return"?";if(Z.length===1)return Z[0].slice(0,2).toUpperCase();return`${Z[0][0]}${Z[1][0]}`.toUpperCase()}function _k($){let Z=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let W of $)Q=Q*31+W.charCodeAt(0)>>>0;return Z[Q%Z.length]}function WA($){return Object.entries($).sort(([Z],[Q])=>Z.localeCompare(Q)).map(([Z,Q])=>UG(Z,Q))}async function zk($,Z){let Q=await M0.getModelsForProvider($),W=$===ZA;if(!Z&&!W)return Q;let J=await kZ($,{loadLatestOnInit:W,loadPrivateOnAuth:!0,failOnError:!1},Z);if($==="litellm"&&J?.knownModels)return J.knownModels;if(W&&J?.knownModels)return J.knownModels;return J?.knownModels?{...Q,...J.knownModels}:Q}function YJ($){return[...new Set(($??[]).map((Z)=>Z.trim()).filter(Boolean))]}function Tk($){if(!$?.length)return;return[...new Set($)]}function Ok($,Z){return Tk([...$??[],...Z??[]])}function qk($){let Z=$?.popularRank;return typeof Z==="number"&&Number.isFinite(Z)?Z:Number.MAX_SAFE_INTEGER}function Mk($){if(!$||typeof $!=="object")return!1;let Z=$;return typeof Z.path==="string"&&Z.path.trim().length>0&&typeof Z.label==="string"&&Z.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(Z.type))}function Rk($){let Z=$?.configFields;if(!Array.isArray(Z))return;return Z.filter(Mk)}var d9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},$A={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function Ek($){if(!$)return[d9];if($.source!=="system")return $.baseUrl?[d9,$A]:[d9];let Z=[];if($.env?.length)Z.push(d9);if($.baseUrl)Z.push($A);return Z}function Nk($,Z){return Z.split(".").reduce((Q,W)=>{if(!Q||typeof Q!=="object")return;return Q[W]},$)}function wk($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function Ck($,Z,Q){if(!$?.length)return;let W={};for(let J of $){let Y=wk(J.path==="baseUrl"&&Z?.baseUrl===void 0?Q?.baseUrl:Nk(Z,J.path))??J.defaultValue;if(Y!==void 0)W[J.path]=Y}return W}function JA($){let Z=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return Z.length>0?Object.fromEntries(Z):void 0}function jJ($,Z){let Q=Z?.includes("vision")??!1,W=Z?.includes("reasoning")??!1;return Object.fromEntries($.map((J)=>[J,{id:J,name:J,supportsVision:Q,supportsAttachments:Q,supportsReasoning:W}]))}async function XA($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let Z=$.modelsSourceUrl?await o4($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...Z])]}function YA($,Z){let Q=$.read(),W=!1;if(Q.providers[Z])delete Q.providers[Z],W=!0;if(Q.lastUsedProvider===Z)delete Q.lastUsedProvider,W=!0;if(W)$.write(Q);M0.unregisterProvider(Z)}async function Pk($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=Z.baseUrl.trim(),J=Z.apiKey?.trim()??"";if(!W&&!J){let A=r$($);if((await d2(A)).providers[Q]){let f=await VA($,{providerId:Q});return{providerId:Q,settingsPath:f.settingsPath,modelsPath:f.modelsPath,modelsCount:0}}return YA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:0}}if(M0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let X=Z.name.trim();if(!X)throw Error("name is required");if(!W)throw Error("baseUrl is required");let Y=YJ(Z.models),j=Z.modelsSourceUrl?.trim(),V=await XA({providerId:Q,explicitModels:Y,modelsSourceUrl:j,shouldRecompute:!0});if(V.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let H=Z.defaultModelId?.trim()&&V.includes(Z.defaultModelId.trim())?Z.defaultModelId.trim():V[0],B=Z.capabilities?.length?[...new Set(Z.capabilities)]:void 0,G=JA(Z.headers);$.saveProviderSettings({provider:Q,apiKey:J||void 0,baseUrl:W,headers:G,timeout:Z.timeoutMs,model:H,protocol:Z.protocol,client:Z.client},{setLastUsed:!1});let K=r$($),F=await d2(K);return F.providers[Q]={provider:{name:X,baseUrl:W,defaultModelId:H,protocol:Z.protocol,client:Z.client,capabilities:B,modelsSourceUrl:j},models:jJ(V,B)},await Z9(K,F),T4(Q,F.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:V.length}}async function jA($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=r$($),J=await d2(W),X=J.providers[Q];if(!X){let q=$.getProviderSettings(Q);if(!q)throw Error(`provider "${Q}" does not exist`);let z=Z.modelsSourceUrl?.trim(),_=YJ(Z.models)[0]??q.model?.trim();if(!_&&!z)throw Error(`provider "${Q}" cannot be updated because no model is configured`);X={provider:{name:Z.name?.trim()||QA(Q),baseUrl:Z.baseUrl?.trim()??q.baseUrl?.trim()??"",defaultModelId:_,protocol:q.protocol,client:q.client,capabilities:q.capabilities},models:_?jJ([_],q.capabilities):{}}}if(!X.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let Y=Z.name?.trim()??X.provider.name.trim();if(!Y)throw Error("name is required");let j=Z.baseUrl?.trim()??X.provider.baseUrl.trim();if(!j)throw Error("baseUrl is required");let V=Z.capabilities===void 0?X.provider.capabilities:Z.capabilities===null?void 0:[...new Set(Z.capabilities)],H=Z.protocol===void 0?X.provider.protocol:Z.protocol??void 0,B=Z.client===void 0?X.provider.client:Z.client??void 0,G=YJ(Z.models),K=Z.modelsSourceUrl===void 0?X.provider.modelsSourceUrl:Z.modelsSourceUrl?.trim()||void 0,F=Z.models!==void 0||Z.modelsSourceUrl!==void 0&&!!K,A=Object.keys(X.models??{}).map((q)=>q.trim()).filter(Boolean),L=await XA({providerId:Q,explicitModels:G,modelsSourceUrl:K,fallbackModelIds:A,shouldRecompute:F});if(L.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let f=Z.defaultModelId===void 0?X.provider.defaultModelId?.trim():Z.defaultModelId?.trim(),D=f&&L.includes(f)?f:L[0],T={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:j,model:D};if(H)T.protocol=H;else delete T.protocol;if(B)T.client=B;else delete T.client;if(Z.apiKey!==void 0){let q=Z.apiKey?.trim()??"";if(q)T.apiKey=q;else delete T.apiKey}if(Z.headers!==void 0){let q=JA(Z.headers);if(q)T.headers=q;else delete T.headers}if(Z.timeoutMs!==void 0)if(typeof Z.timeoutMs==="number")T.timeout=Z.timeoutMs;else delete T.timeout;return $.saveProviderSettings(T,{setLastUsed:!1}),J.providers[Q]={provider:{name:Y,baseUrl:j,defaultModelId:D,protocol:H,client:B,capabilities:V,modelsSourceUrl:K},models:jJ(L,V)},await Z9(W,J),T4(Q,J.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:L.length}}async function VA($,Z){let Q=Z.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let W=r$($),J=await d2(W);if(!J.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete J.providers[Q],await Z9(W,J),M0.unregisterProvider(Q),YA($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:W}}async function Sk($,Z={}){let Q=$.read(),W=M0.getProviderIds(),J=await Promise.all(W.map(async(Y)=>{let[j,V]=await Promise.all([M0.getProvider(Y),M0.getModelsForProvider(Y)]),H=WA(V),B=Q.providers[Y]?.settings,G=j?.name??QA(Y),K=Ok(j?.capabilities,B?.capabilities),F=Rk(j?.metadata)??Ek(j);return{provider:{id:Y,name:G,models:H.length,color:_k(Y),letter:Lk(G),enabled:Boolean(B),apiKey:B?Uk(B):void 0,oauthAccessTokenPresent:B?Dk(B):void 0,baseUrl:B?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:B?.protocol??j?.protocol,client:B?.client??j?.client,capabilities:K,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:F,configValues:Ck(F,B,j),modelList:H},rank:qk(j?.metadata)}}));J.sort((Y,j)=>{if(Y.rank!==j.rank)return Y.rank-j.rank;return Y.provider.name.localeCompare(j.provider.name)||Y.provider.id.localeCompare(j.provider.id)});let X=J.map((Y)=>Y.provider);if(Z.isClinePassEnabled!==!0)X=X.filter((Y)=>Y.id!==ZA);return{providers:X,settingsPath:$.getFilePath()}}async function bk($,Z){let Q=$.trim(),W=await zk(Q,Z),J=WA(W);return{providerId:Q,models:J}}function l9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function HA($,Z){if(!l9(Z))return l9($)?{...$}:void 0;let Q=l9($)?{...$}:{};for(let[W,J]of Object.entries(Z)){if(J==null||J===""){delete Q[W];continue}if(l9(J)){let X=HA(Q[W],J);if(X&&Object.keys(X).length>0)Q[W]=X;else delete Q[W];continue}Q[W]=J}return Object.keys(Q).length>0?Q:void 0}function yk($,Z){let Q=Z.providerId.trim();if(Z.enabled===!1){let X=$.read();if(delete X.providers[Q],X.lastUsedProvider===Q)delete X.lastUsedProvider;return $.write(X),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let J={...$.getProviderSettings(Q)??{},provider:Q};for(let X of["apiKey","baseUrl","model","region"])if(Object.hasOwn(Z,X)&&typeof Z[X]==="string")if(Z[X].trim().length===0)delete J[X];else J[X]=Z[X];for(let X of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(Z,X))J[X]=Z[X];for(let X of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(Z,X)&&Z[X]!=null){let Y=HA(J[X],Z[X]);if(Y)J[X]=Y;else delete J[X]}return $.saveProviderSettings(J,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function hk($,Z){let Q=Z.trim(),W=$.getProviderSettings(Q),X=M0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,Y=W?.baseUrl?.trim()||X?.baseUrl?.trim(),j=t4(Y,X?.baseUrl,X?.modelsSourceUrl);if(!W||!X||!Y||!j)return{providerId:Q,refreshed:!1};let V=await jA($,{providerId:Q,name:X.name,baseUrl:Y,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:j,protocol:W.protocol??X.protocol??null,client:W.client??X.client??null,capabilities:W.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:V.modelsCount}}function kk($){let Z=$.trim().toLowerCase(),Q=B0(Z);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function Ik($,Z,Q,W){let J=B0($);if(!J)throw Error(`provider "${$}" does not support OAuth login`);let X=m4({onPrompt:async(Y)=>Y.defaultValue??"",openUrl:Q,onOpenUrlError:({error:Y})=>{throw Y instanceof Error?Y:Error(String(Y))}});return J.login({settings:Z,callbacks:X,telemetry:W})}function xk($,Z,Q,W,J){return X8({manager:$,providerId:Z,settings:Q,credentials:W,setLastUsed:J?.setLastUsed})}async function gk($,Z,Q,W){let J=m4({onPrompt:async(X)=>X.defaultValue??"",openUrl:Q,onOpenUrlError:({error:X})=>{throw X instanceof Error?X:Error(String(X))}});return wZ($,Z,{callbacks:J,telemetry:W})}function mk($){let Z=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return Z&&Z.length>0?Z:void 0}import*as p9 from"@cline/llms";var vk=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],ck={"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 uk($,Z){let Q={};for(let W of vk){let J=$[W],X=Z[W];if(J||X)Q[W]={...J,...X}}return Q}function dk($){let Z=ck[$.providerId];if(!Z)return $;return{...$,description:Z.description??$.description,fields:Z.mode==="replace"?Z.fields:uk($.fields,Z.fields)}}var lk=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function pk($,Z){if(!Z?.provider.baseUrl)return!1;if(Z.provider.source!=="system")return!0;return lk.has($)}function rk($){let Z=p9.normalizeProviderId($);if(J8(Z))return{providerId:Z,authMethod:"oauth",fields:{}};let Q=p9.MODEL_COLLECTIONS_BY_PROVIDER_ID[Z];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:Z,authMethod:"local",fields:{}};let W=Q?.provider.baseUrl,J={apiKey:{}};if(pk(Z,Q))J.baseUrl={defaultValue:W};return dk({providerId:Z,authMethod:"api-key",fields:J})}S9();G0();q9();import{appendFileSync as ik,existsSync as VJ,mkdirSync as nk,readFileSync as ak,renameSync as sk,unlinkSync as ok,writeFileSync as tk}from"node:fs";import{join as HJ}from"node:path";import{resolveTeamDataDir as ek}from"@cline/shared/storage";function $I($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class BA{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let Z=$I($.teamName),Q=$.baseDir?.trim()||ek();this.dirPath=HJ(Q,Z),this.statePath=HJ(this.dirPath,"state.json"),this.taskHistoryPath=HJ(this.dirPath,"task-history.jsonl")}loadState(){if(!VJ(this.statePath))return;try{let $=ak(this.statePath,"utf8"),Z=JSON.parse($);if(Z.version!==1||!Z.teamState)return;for(let Q of Z.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return zB(Z.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 Z={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;tk(Q,`${JSON.stringify(Z,null,2)}
751
+ `,"utf8"),sk(Q,this.statePath)}appendTaskHistory($){let Z={};switch($.type){case"team_task_updated":Z=$.task;break;case"team_message":Z={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":Z={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":Z={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":Z={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":Z={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),ik(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:Z})}
752
+ `,"utf8")}ensureDir(){if(!VJ(this.dirPath))nk(this.dirPath,{recursive:!0})}hasPersistableState($){let Z=$.exportState();if(this.teammateSpecs.size>0)return!0;if(Z.members.some((Q)=>Q.role==="teammate"))return!0;return Z.tasks.length>0||Z.mailbox.length>0||Z.missionLog.length>0}clearPersistedState(){if(VJ(this.statePath))ok(this.statePath)}}import{z as S}from"zod";var GA=S.object({workspaceRoot:S.string().min(1),cwd:S.string().optional(),provider:S.string().min(1),model:S.string().min(1),mode:S.enum(["act","plan"]).default("act"),apiKey:S.string(),systemPrompt:S.string().optional(),rules:S.string().optional(),maxIterations:S.number().int().positive().optional(),enableTools:S.boolean(),enableSpawn:S.boolean().optional(),enableTeams:S.boolean().optional(),autoApproveTools:S.boolean().optional(),missionStepInterval:S.number().int().positive().optional(),missionTimeIntervalMs:S.number().int().positive().optional()}),KA=S.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),FA=S.enum(["user","assistant","tool","system","status","error"]),AA=S.object({id:S.string().min(1),sessionId:S.string().nullable(),role:FA,content:S.string(),createdAt:S.number().int().nonnegative(),meta:S.object({stream:S.enum(["stdout","stderr"]).optional(),toolName:S.string().optional(),iteration:S.number().int().nonnegative().optional(),agentId:S.string().optional(),conversationId:S.string().optional(),hookEventName:S.string().optional(),inputTokens:S.number().int().nonnegative().optional(),outputTokens:S.number().int().nonnegative().optional(),checkpoint:S.object({ref:S.string(),createdAt:S.number().int().nonnegative(),runCount:S.number().int().positive(),kind:S.enum(["stash","commit"]).optional()}).optional()}).optional()}),fA=S.object({toolCalls:S.number().int().nonnegative(),tokensIn:S.number().int().nonnegative(),tokensOut:S.number().int().nonnegative()}),ZI=S.object({sessionId:S.string().nullable(),status:KA,config:GA,messages:S.array(AA),rawTranscript:S.string(),error:S.string().nullable(),summary:fA});var QI=fH;import{Agent as w$0,createAgentRuntime as C$0}from"@cline/agents";import{getClineEnvironmentConfig as WI}from"@cline/shared";var JI=5000,UA={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 XI($){return{recommended:$.recommended.map((Z)=>({...Z,tags:[...Z.tags]})),free:$.free.map((Z)=>({...Z,tags:[...Z.tags]})),clinePass:$.clinePass.map((Z)=>({...Z,tags:[...Z.tags]}))}}function BJ($){if(!$||typeof $!=="object")return null;let Z=$;if(typeof Z.id!=="string"||Z.id.length===0)return null;return{id:Z.id,name:typeof Z.name==="string"&&Z.name.length>0?Z.name:Z.id,description:typeof Z.description==="string"?Z.description:"",tags:Array.isArray(Z.tags)?Z.tags.filter((Q)=>typeof Q==="string"):[]}}function YI($){if(!$||typeof $!=="object")return null;let Z=$,Q=Array.isArray(Z.recommended)?Z.recommended:[],W=Array.isArray(Z.free)?Z.free:[],J=Array.isArray(Z.clinePass)?Z.clinePass:[],X=Q.map(BJ).filter((V)=>V!==null),Y=W.map(BJ).filter((V)=>V!==null),j=J.map(BJ).filter((V)=>V!==null);if(X.length===0&&Y.length===0&&j.length===0)return null;return{recommended:X,free:Y,clinePass:j}}function jI($){let Z=$.baseUrl?.trim();if(Z)return Z;let Q=WI().apiBaseUrl;try{return($.providerSettingsManager??new Y$).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function VI($,Z,Q){let W=new AbortController,J=setTimeout(()=>W.abort(),Q);try{return await $(Z,{signal:W.signal})}finally{clearTimeout(J)}}async function HI($={}){try{let Z=jI($),Q=$.fetchImpl??fetch,W=await VI(Q,`${Z}/api/v1/ai/cline/recommended-models`,$.timeoutMs??JI);if(!W.ok)throw Error(`HTTP ${W.status}`);let J=await W.json(),X=YI(J);if(X)return X}catch{}return XI(UA)}import{readFile as BI}from"node:fs/promises";import GI from"node:path";function KI($){return $}async function FI($){let Z=GI.resolve($),Q=await BI(Z,"utf8"),W;try{W=JSON.parse(Q)}catch(J){let X=J instanceof Error?J.message:String(J);throw Error(`Failed to parse JSON config at "${Z}": ${X}`)}return AI(W,Z)}function AI($,Z){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${Z}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${Z}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${Z}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as _A,createHandler as DI,createHandlerAsync as LI,getProviderCollection as _I,hasProvider as zA,registerAsyncHandler as zI,registerHandler as TI,registerModel as OI,registerProvider as TA}from"@cline/llms";function DA($){return $?{...$}:{}}function fI($,Z){if($)return $;if(!Z)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[Z]}function UI($,Z){if(!Z.length)throw Error(`Provider "${$}" must include at least one model.`)}function LA($){let Z=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:Z,defaultModel:$.collection.provider.defaultModelId,modelCount:Z.length}}class GJ{providers=new Map;register($){UI($.id,$.models);let Z=$.defaultModel??$.models[0];if(!Z)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(Z))throw Error(`Default model "${Z}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:Z,defaults:{...Q?.defaults??{},...DA($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:fI($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...DA($.settings)}})}registerModel($,Z){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([Z]),defaultModel:Z,defaults:{}});return}Q.models.add(Z)}createHandlerConfig($){let Z=this.require($.providerId),Q=$.modelId??Z.defaultModel;if(!Z.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...Z.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($,Z){return this.providers.get($)?.models.has(Z)??!1}require($){let Z=this.providers.get($);if(!Z)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return Z}}class KJ{configuredProviders=new GJ;constructor($){this.applyConfig($)}createHandler($){return DI(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return LI(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(TA($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)TI($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)zI($.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 Z=$.exposeModels??Object.keys($.models),Q=$.defaultModel??Z[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);TA({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:Z,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){OI($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[..._A]}async getBuiltInProviders(){return(await Promise.all(_A.map((Z)=>_I(Z)))).filter((Z)=>Z!==void 0).map((Z)=>LA({collection:Z}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,Z){return this.configuredProviders.hasModel($,Z)}applyConfig($){for(let Z of $.providers)this.configuredProviders.registerSelectionConfig(Z);for(let Z of $.models??[])this.registerModel(Z);for(let Z of $.customProviders??[])this.registerProvider(Z);for(let Z of this.configuredProviders.list()){let Q=zA(Z.id),W=this.configuredProviders.createHandlerConfig({providerId:Z.id,modelId:Z.defaultModel}).routingProviderId,J=typeof W==="string"&&zA(W);if(!Q&&!J)throw Error(`Provider "${Z.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function qI($){return new KJ($)}V3();async function l00(){return Promise.resolve().then(() => (S9(),LF))}export{qH as writeHubDiscovery,G1 as writeGlobalSettings,MH as withHubStartupLock,o1 as verifyHubConnection,U1 as updateMcpSettingsFileSync,Y5 as updateMcpSettingsFile,eQ as updateMcpServerOAuthStateAsync,h8 as updateMcpServerOAuthState,jA as updateLocalProvider,n3 as uninstallPlugin,IF as uninstallMarketplaceSkill,xF as uninstallMarketplacePlugin,hF as uninstallMarketplaceMcpServerFromSettings,Ch as uninstallMarketplaceEntry,F3 as truncateNotificationBody,U8 as truncateCommandOutput,cZ as toggleDisabledTool,g5 as toTeamProgressLifecycleEvent,B1 as toProviderConfig,vM as toHubStatusUrl,RH as toHubHealthUrl,SW as toHookConfigFileName,m3 as syncPluginMcpServersToSettings,l5 as summarizeUsageFromMessages,nR as stopLocalHubServerGracefully,H1 as startLocalOAuthServer,y3 as startHubWebSocketServer,Ve as startHubServer,oA as startClineDeviceAuth,j7 as splitCoreSessionConfig,R5 as spawnDetachedHubServerWithRetry,RR as spawnDetachedHubServer,gU as setTelemetryOptOutGlobally,b8 as setMcpServerDisabled,LX as setDisabledTools,pU as setDisabledPlugin,uU as setCompactionStrategyGlobally,vU as setAutoUpdateEnabledGlobally,ls as sendHubCommand,X8 as saveProviderOAuthCredentials,yk as saveLocalProviderSettings,xk as saveLocalProviderOAuthCredentials,s8 as sanitizeSessionToken,HX as safeParseSettings,fU as safeCreateProviderConfig,F9 as runSubprocessEvent,f9 as runHook,yj as reviveTeamStateDates,uH as restartLocalHubIfIdleAfterStartupTimeout,vd as resolveWorkspaceHubOwnerContext,LQ as resolveWorkflowsConfigSearchPaths,UQ as resolveSkillsConfigSearchPaths,_1 as resolveSharedHubOwnerContext,MP as resolveSessionBackend,DQ as resolveRulesConfigSearchPaths,kZ as resolveProviderConfig,bf as resolveProviderApiKeyFromSettings,s1 as resolveProductionHubOwnerContext,T$ as resolvePluginSkillDirectoriesFromPaths,WQ as resolvePluginConfigSearchPaths,$1 as resolveMcpServerRegistrations,o3 as resolveMarketplaceMcpServerName,mk as resolveLocalClineAuthToken,bS as resolveHubUrl,x$ as resolveHubOwnerContext,a1 as resolveHubEndpointOptions,OH as resolveHubBuildId,CW as resolveHooksConfigSearchPaths,K1 as resolveDisabledToolNames,B6 as resolveDisabledPluginPaths,Z0 as resolveDefaultMcpSettingsPath,q5 as resolveDefaultHubPort,oM as resolveDefaultHubPathname,sM as resolveDefaultHubHost,xj as resolveCoreSelectedToolIds,m0 as resolveCoreDistinctId,a7 as resolveCompatibleLocalHubUrl,Pd as resolveClineDir,W4 as resolveClineDataDir,L6 as resolveAndLoadAgentPlugins,z$ as resolveAgentPluginPaths,l7 as requestHubShutdown,My as requestDesktopToolApproval,v3 as removePluginMcpServersFromSettings,k2 as rememberRecoverableLocalHubUrl,TF as registerRemoteConfigSessionBlobUpload,k8 as registerMcpServersFromSettingsFile,z10 as registerDisposable,hk as refreshProviderModelsFromSource,bJ as refreshOpenAICodexToken,vJ as refreshOcaToken,PJ as refreshClineToken,O4 as readSessionCheckpointHistory,Ay as readRemoteConfigSessionBlobUploadMetadata,A0 as readHubDiscovery,D0 as readGlobalSettings,cU as readCompactionStrategyGlobally,FF as readBearerToken,g$ as probeHubServer,ds as probeHubConnection,hY as prewarmFileIndex,bH as prewarmDetachedHubServer,Dy as prepareRemoteConfigCoreIntegration,fQ as parseWorkflowConfigFromMarkdown,_10 as parseUserCommandEnvelope,FQ as parseSkillConfigFromMarkdown,VX as parseSettings,AQ as parseRuleConfigFromMarkdown,aF as parsePluginSource,k3 as parseMcpInstallArgs,A9 as parseHookEventPayload,WW as parseConfiguredAgentConfig,b$ as normalizeWorkspacePath,L10 as normalizeUserInput,D10 as normalizeSdkError,O0 as normalizeRuntimeCapabilities,X6 as normalizeProviderId,kk as normalizeOAuthProvider,I2 as normalizeHubWebSocketUrl,U10 as noopBasicLogger,cW as migrateLegacyProviderSettings,R6 as mergeRulesForSystemPrompt,_4 as mergeAgentHooks,Nh as marketplaceEntryKey,C7 as makeTeamTaskSubSessionId,L5 as makeSubSessionId,_Z as loginOpenAICodex,RZ as loginOcaOAuth,Ik as loginLocalProvider,DZ as loginClineOAuth,wZ as loginAndSaveProviderOAuthCredentials,gk as loginAndSaveLocalProviderOAuthCredentials,l00 as loadOpenTelemetryAdapter,S8 as loadMcpSettingsFile,FI as loadLlmsConfigFromFile,h5 as loadConfiguredAgentConfigs,B8 as loadAgentPluginsFromPathsWithDiagnostics,yX as loadAgentPluginsFromPaths,oZ as loadAgentPluginFromPath,RM as listSessionHistoryFromBackend,qV as listPluginToolsWithDiagnostics,X7 as listPluginTools,$7 as listMcpServerOAuthStatuses,Sk as listLocalProviders,c2 as listHookConfigFiles,dU as isToolDisabledGlobally,vZ as isTelemetryOptedOutGlobally,S$ as isSessionNotFoundError,tX as isRuleEnabled,lU as isPluginDisabledGlobally,nF as isOfficialPluginSlug,J8 as isOAuthProvider,kF as isMarketplaceSkillInstalled,jy as isLocalHubOrigin,AF as isLocalHubHostName,cR as isHubReconnectableTransportError,vH as isHubCommandTimeoutError,yd as isDiscoveryFilePresent,Q10 as isClineOrgIndividualInferenceSubscriptionMessage,Z10 as isClineOrgIndividualInferenceSubscriptionError,$10 as isClineNotSubscribedMessage,e00 as isClineNotSubscribedError,DJ as isClineAccountActionRequest,GU as isBuiltInProviderId,mU as isAutoUpdateEnabledGlobally,fk as installPlugin,Sy as installMcpServer,b1 as identifyAccount,C$ as hasMcpSettingsFile,zZ as getValidOpenAICodexCredentials,EZ as getValidOcaCredentials,LZ as getValidClineCredentials,CZ as getProviderOAuthCredentialsFromSettings,rk as getProviderConfigFields,oJ as getProviderConfig,Sf as getProviderAuthStorageId,B0 as getProviderAuthHandler,s4 as getPersistedProviderApiKey,y8 as getMcpServerOAuthState,t3 as getMarketplaceSkillCandidates,bk as getLocalProviderModels,J6 as getLiveModelsCatalog,e3 as getGlobalMarketplaceSkillPaths,M$ as getFileIndex,Zw as getCurrentContextSize,pQ as getCoreHeadlessToolNames,Ij as getCoreDefaultEnabledToolIds,N8 as getCoreBuiltinToolCatalog,gj as getCoreAcpToolNames,t00 as getClinePassSubscriptionUrl,s00 as getClineOrgIndividualInferenceSubscriptionMessage,o00 as getClineNotSubscribedMessage,J10 as getClineDefaultSystemPrompt,K7 as generateWorkspaceInfoWithDiagnostics,U5 as generateWorkspaceInfo,M6 as formatRulesForSystemPrompt,yf as formatProviderOAuthApiKey,f10 as formatDisplayUserInput,$J as findInstalledGlobalMarketplaceSkillName,J9 as findCheckpointForRun,dZ as filterExtensionToolRegistrations,k1 as filterDisabledTools,uZ as filterDisabledPluginPaths,HI as fetchClineRecommendedModels,LJ as executeClineAccountAction,fF as ensureHubWebSocketServer,He as ensureHubServer,od as ensureDetachedHubServer,qG as ensureCustomProvidersLoaded,X4 as ensureCompatibleLocalHubUrl,l6 as enrichPromptWithMentions,K10 as emptyWorkspaceManifest,u2 as emptyStoredProviderSettings,JQ as discoverPluginModulePaths,vy as disablePluginMcpServersInSettings,P7 as deriveSubsessionStatus,VA as deleteLocalProvider,KI as defineLlmsConfig,TQ as createWorkflowsConfigDefinition,w2 as createUserInstructionConfigService,mY as createToolPoliciesWithPreset,G10 as createTool,cG as createTeamName,VK as createSubprocessHooks,N2 as createSpawnAgentTool,_Q as createSkillsConfigDefinition,MQ as createShellTool,D8 as createShellExecutor,G9 as createSessionHost,G9 as createRuntimeHost,zQ as createRulesConfigDefinition,Uy as createRemoteConfigSessionMessagesArtifactUploader,AU as createProviderConfig,T9 as createOpenTelemetryTelemetryService,m4 as createOAuthClientCallbacks,F5 as createMcpTools,Qo as createLocalHubScheduleRuntimeHandlers,qI as createLlmsSdk,_0 as createInitialAccumulatedUsage,bd as createInMemoryHubOwnerContext,L1 as createHubServerUrl,TH as createHubAuthToken,kW as createHookConfigFileHooks,s5 as createHookConfigFileExtension,a5 as createHookAuditHooks,J7 as createDisabledMcpToolPolicy,zV as createDisabledMcpToolPolicies,R2 as createDelegatedAgentConfigProvider,E2 as createDelegatedAgent,vY as createDefaultToolsWithPreset,T2 as createDefaultTools,CQ as createDefaultShellExecutor,G5 as createDefaultMcpServerClientFactory,n6 as createDefaultExecutors,v8 as createCoreSettingsService,t1 as createCoreSessionSnapshot,B10 as createContributionRegistry,EW as createContextCompactionPrepareTurn,s$ as createConfiguredTelemetryService,O9 as createConfiguredTelemetryHandle,I5 as createConfiguredAgentTools,H10 as createClineTelemetryServiceMetadata,V10 as createClineTelemetryServiceConfig,$K as createCheckpointComparePlan,w8 as createBuiltinTools,E8 as createAgentTeamsTools,C$0 as createAgentRuntime,p5 as createAgentHooksExtension,FK as connectToHub,tA as completeClineDeviceAuth,J3 as compareCheckpointToWorkspace,eF as collectPluginMcpOAuthCandidates,VU as clearPrivateModelsCatalogCache,jU as clearLiveModelsCatalogCache,a0 as clearHubDiscovery,IA as captureWorkspacePathResolved,o9 as captureWorkspaceInitialized,t9 as captureWorkspaceInitError,Q8 as captureToolUsage,ZZ as captureTokenUsage,$Z as captureTaskRestarted,e9 as captureTaskCreated,c4 as captureTaskCompleted,d4 as captureSubagentExecution,WZ as captureSkillUsed,j10 as captureSdkError,xA as captureProviderConfigured,u4 as captureProviderApiError,QZ as captureModeSwitch,XZ as captureMentionUsed,jZ as captureMentionSearchResults,YZ as captureMentionFailed,HZ as captureHookDiscovery,kA as captureExtensionActivated,JZ as captureDiffEditFailure,Z8 as captureConversationTurnEvent,GZ as captureCompactionSkipped,BZ as captureCompactionExecuted,P1 as captureAuthSucceeded,C1 as captureAuthStarted,A$ as captureAuthLoggedOut,S1 as captureAuthFailed,PA as captureAgentUnexpectedReasoningTokens,VZ as captureAgentTeamCreated,f$ as captureAgentCreated,F7 as buildWorkspaceMetadata,x5 as buildTeamProgressSummary,X10 as buildSdkErrorProperties,_F as buildRemoteConfigSessionBlobUploadMetadata,MF as buildMcpInstallTransport,M8 as buildDelegatedAgentConfig,XW as buildConfiguredAgentToolName,YW as buildConfiguredAgentToolDescriptors,ZK as buildCheckpointWorkspaceDiff,Q5 as bootstrapAgentTeams,VV as authorizeMcpServerOAuth,Pk as addLocalProvider,f0 as accumulateUsageTotals,HQ as WORKFLOWS_CONFIG_DIRECTORY_NAME,j8 as UnifiedConfigFileWatcher,e0 as ToolPresets,P4 as TelemetryService,z9 as TelemetryLoggerSink,Z5 as TEAM_TOOL_NAMES,K6 as SubprocessSandbox,f8 as StructuredCommandInputSchema,o5 as StoredProviderSettingsSchema,WG as StoredProviderSettingsEntrySchema,q4 as SqliteTeamStore,Z$ as SqliteSessionStore,r2 as SessionVersioningService,s0 as SessionVersioningError,T0 as SessionSource,P$ as SessionNotFoundError,XX as SapSettingsSchema,VQ as SKILLS_CONFIG_DIRECTORY_NAME,gZ as SESSION_STATUSES,c8 as SESSION_NOT_FOUND_ERROR_CODE,T10 as SDK_ERROR_TELEMETRY_EVENT,s9 as RpcClineAccountService,C5 as RemoteRuntimeHost,ZX as ReasoningSettingsSchema,pX as RULES_CONFIG_DIRECTORY_NAME,zF as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,H2 as ProviderSettingsSchema,Y$ as ProviderSettingsManager,tJ as ProviderProtocolSchema,xZ as ProviderIdSchema,eJ as ProviderClientSchema,S4 as OpenTelemetryProvider,YX as OcaSettingsSchema,hZ as OPENAI_COMPATIBLE_PROVIDERS,z1 as NodeHubClient,w4 as NoOpFeatureFlagsProvider,w3 as NativeHubTransportAdapter,jX as ModelCatalogSettingsSchema,J5 as McpSettingsUpdateSkippedError,C2 as McpSettingsMutatorPurityError,P2 as McpSettingsLockTimeoutError,q$ as MAX_COMMAND_OUTPUT_CHARS,j$ as LocalRuntimeHost,r00 as Llms,t5 as InMemoryWorkspaceManager,I8 as InMemoryMcpManager,xS as HubUIClient,g0 as HubTransportError,IS as HubSessionClient,P9 as HubServerTransport,_9 as HubScheduleService,U9 as HubScheduleCommandService,u$ as HubRuntimeHost,E5 as HubCommandError,YK as HookEventPayloadSchema,XK as HookEventNameSchema,r5 as HookConfigFileName,PW as HOOK_CONFIG_FILE_EVENT_MAP,nB as HOOKS_CONFIG_DIRECTORY_NAME,H6 as GlobalSettingsSchema,WX as GcpSettingsSchema,BA as FileTeamPersistenceStore,N4 as FeatureFlagsService,A10 as FeatureFlagDefaultValue,F10 as FEATURE_FLAGS,UA as FALLBACK_CLINE_RECOMMENDED_MODELS,L0 as DefaultToolNames,V9 as DefaultRuntimeBuilder,KJ as DefaultLlmsSdk,nJ as DEFAULT_MODELS_CATALOG_URL,nM as DEFAULT_HUB_PORT,aM as DEFAULT_HUB_PATHNAME,iM as DEFAULT_HUB_HOST,h2 as CoreSettingsService,Q$ as CoreSessionService,Y10 as ContributionRegistry,a00 as ClineOrgIndividualInferenceSubscriptionError,n00 as ClineNotSubscribedError,Y3 as ClineCore,a9 as ClineAccountService,ZI as ChatViewStateSchema,fA as ChatSummarySchema,KA as ChatSessionStatusSchema,GA as ChatSessionConfigSchema,AA as ChatMessageSchema,FA as ChatMessageRoleSchema,I as CORE_TELEMETRY_EVENTS,QI as CORE_BUILD_VERSION,N3 as BrowserWebSocketHubAdapter,BU as BUILT_IN_PROVIDER_IDS,IZ as BUILT_IN_PROVIDER,JX as AzureSettingsSchema,QX as AwsSettingsSchema,$X as AuthSettingsSchema,B4 as AgentTeamsRuntime,VW as AgentTeam,w$0 as Agent,U2 as ALL_DEFAULT_TOOL_NAMES};