@cline/core 0.0.43-nightly.1780975055 → 0.0.44

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,15 +1,15 @@
1
- import{createRequire as wK}from"node:module";var{defineProperty:K9,getOwnPropertyNames:MK}=Object;var u7=Object.prototype.hasOwnProperty;function c7($){return this[$]}var M=($,f,J)=>{var W=MK(f);for(let Z of W)if(!u7.call($,Z)&&Z!=="default")K9($,Z,{get:c7.bind(f,Z),enumerable:!0});if(J){for(let Z of W)if(!u7.call(J,Z)&&Z!=="default")K9(J,Z,{get:c7.bind(f,Z),enumerable:!0});return J}};var yK=($)=>$;function qK($,f){this[$]=yK.bind(null,f)}var w=($,f)=>{for(var J in f)K9($,J,{get:f[J],enumerable:!0,configurable:!0,set:qK.bind(f,J)})};var M1=($,f)=>()=>($&&(f=$($=0)),f);var d7=wK(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as SK}from"@cline/shared";function d($,f,J){$?.capture({event:f,properties:J})}function Y4($){if(!$)return;return $.substring(0,hK)}function CK($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function EK($){return typeof $==="string"?$:$.message}function l7($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function p7($){d($,x.CLIENT.EXTENSION_ACTIVATED)}function A4($,f){let J=[...f.vcs_types],W={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:l7(J,new Set(["git"])),has_mercurial:l7(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)W.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)W.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)W.is_remote_workspace=f.is_remote_workspace;d($,x.WORKSPACE.INITIALIZED,W)}function V4($,f,J){d($,x.WORKSPACE.INIT_ERROR,{error_type:CK(f),error_message:Y4(EK(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function r7($,f){d($,x.WORKSPACE.PATH_RESOLVED,{...f})}function L$($,f){d($,x.USER.AUTH_STARTED,{provider:f})}function z$($,f){d($,x.USER.AUTH_SUCCEEDED,{provider:f})}function O$($,f,J){d($,x.USER.AUTH_FAILED,{provider:f,errorMessage:Y4(J)})}function p$($,f,J){d($,x.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function i7($,f){d($,x.USER.PROVIDER_CONFIGURED,{provider:f})}function n7($,f){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,f)}function _$($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function B4($,f){d($,x.TASK.CREATED,f)}function K4($,f){d($,x.TASK.RESTARTED,f)}function r2($,f){d($,x.TASK.COMPLETED,f)}function Nf($,f){d($,x.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function G4($,f){d($,x.TASK.TOKEN_USAGE,f)}function P4($,f,J){d($,x.TASK.MODE_SWITCH,{ulid:f,mode:J})}function U4($,f){d($,x.TASK.TOOL_USED,f)}function F4($,f){d($,x.TASK.SKILL_USED,f)}function R4($,f){d($,x.TASK.DIFF_EDIT_FAILED,f)}function i2($,f){d($,x.TASK.PROVIDER_API_ERROR,{...f,errorMessage:Y4(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function a7($,f){d($,x.SDK.TOOL_TIMEOUT,bK(f))}function bK($){let f={};for(let[J,W]of Object.entries($))if(W!==void 0)f[J]=W;return f}function D4($,f,J){d($,x.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function L4($,f,J,W){d($,x.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:Y4(W),timestamp:new Date().toISOString()})}function z4($,f,J,W,Z){d($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:W,isEmpty:Z,timestamp:new Date().toISOString()})}function r$($,f){d($,x.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function O4($,f){d($,x.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function n2($,f){d($,f.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function _4($,f,J,W){d($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}function T4($,f){d($,x.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function N4($,f){d($,x.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var hK=500,x;var L0=M1(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},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:SK,TOOL_TIMEOUT:"sdk.tool_timeout"}}});var jj={};w(jj,{normalizeUserMessage:()=>uP,buildInitialUserContent:()=>vP});async function vP($,f,J,W){let Z=cP(f),Q=await lP(J,W);if(Z.length===0&&!Q)return $;let j=[{type:"text",text:$},...Z];if(Q)j.push(...Q);return j}function uP($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let W of f)if(W&&typeof W==="object"&&W.type==="text"){let Z=W.text;if(typeof Z==="string")J.push(Z)}return J.join(`
1
+ import{createRequire as wK}from"node:module";var{defineProperty:KW,getOwnPropertyNames:MK}=Object;var u7=Object.prototype.hasOwnProperty;function c7($){return this[$]}var M=($,f,J)=>{var W=MK(f);for(let Z of W)if(!u7.call($,Z)&&Z!=="default")KW($,Z,{get:c7.bind(f,Z),enumerable:!0});if(J){for(let Z of W)if(!u7.call(J,Z)&&Z!=="default")KW(J,Z,{get:c7.bind(f,Z),enumerable:!0});return J}};var yK=($)=>$;function qK($,f){this[$]=yK.bind(null,f)}var w=($,f)=>{for(var J in f)KW($,J,{get:f[J],enumerable:!0,configurable:!0,set:qK.bind(f,J)})};var M1=($,f)=>()=>($&&(f=$($=0)),f);var d7=wK(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as SK}from"@cline/shared";function d($,f,J){$?.capture({event:f,properties:J})}function Y4($){if(!$)return;return $.substring(0,hK)}function CK($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function EK($){return typeof $==="string"?$:$.message}function l7($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function p7($){d($,x.CLIENT.EXTENSION_ACTIVATED)}function A4($,f){let J=[...f.vcs_types],W={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:l7(J,new Set(["git"])),has_mercurial:l7(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)W.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)W.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)W.is_remote_workspace=f.is_remote_workspace;d($,x.WORKSPACE.INITIALIZED,W)}function V4($,f,J){d($,x.WORKSPACE.INIT_ERROR,{error_type:CK(f),error_message:Y4(EK(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function r7($,f){d($,x.WORKSPACE.PATH_RESOLVED,{...f})}function L$($,f){d($,x.USER.AUTH_STARTED,{provider:f})}function z$($,f){d($,x.USER.AUTH_SUCCEEDED,{provider:f})}function O$($,f,J){d($,x.USER.AUTH_FAILED,{provider:f,errorMessage:Y4(J)})}function p$($,f,J){d($,x.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function i7($,f){d($,x.USER.PROVIDER_CONFIGURED,{provider:f})}function n7($,f){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,f)}function _$($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function B4($,f){d($,x.TASK.CREATED,f)}function K4($,f){d($,x.TASK.RESTARTED,f)}function r2($,f){d($,x.TASK.COMPLETED,f)}function Nf($,f){d($,x.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function G4($,f){d($,x.TASK.TOKEN_USAGE,f)}function P4($,f,J){d($,x.TASK.MODE_SWITCH,{ulid:f,mode:J})}function U4($,f){d($,x.TASK.TOOL_USED,f)}function F4($,f){d($,x.TASK.SKILL_USED,f)}function R4($,f){d($,x.TASK.DIFF_EDIT_FAILED,f)}function i2($,f){d($,x.TASK.PROVIDER_API_ERROR,{...f,errorMessage:Y4(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function a7($,f){d($,x.SDK.TOOL_TIMEOUT,bK(f))}function bK($){let f={};for(let[J,W]of Object.entries($))if(W!==void 0)f[J]=W;return f}function D4($,f,J){d($,x.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function L4($,f,J,W){d($,x.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:Y4(W),timestamp:new Date().toISOString()})}function z4($,f,J,W,Z){d($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:W,isEmpty:Z,timestamp:new Date().toISOString()})}function r$($,f){d($,x.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function O4($,f){d($,x.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function n2($,f){d($,f.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function _4($,f,J,W){d($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:W,totalCount:J+W,timestamp:new Date().toISOString()})}function T4($,f){d($,x.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function N4($,f){d($,x.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var hK=500,x;var L0=M1(()=>{x={CLIENT:{EXTENSION_ACTIVATED:"user.extension_activated"},SESSION:{STARTED:"session.started",ENDED:"session.ended"},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:SK,TOOL_TIMEOUT:"sdk.tool_timeout"}}});var jj={};w(jj,{normalizeUserMessage:()=>uP,buildInitialUserContent:()=>vP});async function vP($,f,J,W){let Z=cP(f),Q=await lP(J,W);if(Z.length===0&&!Q)return $;let j=[{type:"text",text:$},...Z];if(Q)j.push(...Q);return j}function uP($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let W of f)if(W&&typeof W==="object"&&W.type==="text"){let Z=W.text;if(typeof Z==="string")J.push(Z)}return J.join(`
2
2
  `)}function cP($){if(!$||$.length===0)return[];let f=[];for(let J of $){let W=dP(J);if(W)f.push(W)}return f}function dP($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let W=J[1],Z=J[2];if(!W||!Z)return;return{type:"image",mediaType:W,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function lP($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),W=await Promise.all($.map(async(Z)=>{let Q=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:Q,content:j}}catch(j){let X=j instanceof Error?j.message:String(j);return{type:"file",path:Q,content:`Error fetching content: ${X}`}}}));if(W.length===0)return;return W}import{mkdirSync as vU,readFileSync as uU,statSync as cU,writeFileSync as dU}from"node:fs";import{dirname as lU}from"node:path";import{resolveGlobalSettingsPath as aj}from"@cline/shared/storage";import{z as lf}from"zod";function p4(){return y8.parse({})}function pU(){r4=void 0}function rU($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function iU($){let f;try{f=uU($,"utf8")}catch{return p4()}try{let J=y8.safeParse(JSON.parse(f));return J.success?J.data:p4()}catch{return p4()}}function nU(){let $=aj(),f=cU($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,W=f?.size??0,Z=r4;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===W)return Z;let Q=rU(f?iU($):p4());return r4={path:$,mtimeMs:J,size:W,value:Q},r4}function O0(){return nU().value}function h$($,f={}){let J=aj(),W=O0();vU(lU(J),{recursive:!0});let Z=y8.parse($);if(!W.telemetryOptOut&&Z.telemetryOptOut)n7(f.telemetry);dU(J,`${JSON.stringify(Z,null,2)}
3
- `,"utf8"),pU()}function i4(){return O0().telemetryOptOut}function tj($,f={}){h$({...O0(),telemetryOptOut:$},f)}function sj(){return O0().autoUpdateEnabled}function oj($,f={}){h$({...O0(),autoUpdateEnabled:$},f)}function j$($){return new Set($??O0().disabledTools??[])}function q8($){return new Set($??O0().disabledPlugins??[])}function ej($){return j$().has($)}function n4($){let f=O0(),J=new Set(f.disabledTools??[]),W=J.has($);if(W)J.delete($);else J.add($);return h$({...f,disabledTools:[...J]}),!W}function WW($,f){let J=[...new Set($.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=O0(),Z=j$(W.disabledTools);for(let Q of J)if(f)Z.add(Q);else Z.delete(Q);h$({...W,disabledTools:[...Z]})}function $X($,f){return WW([$],f),f}function fX($){return q8().has($)}function JX($,f){let J=$.trim();if(!J)return;let W=O0(),Z=q8(W.disabledPlugins);if(f)Z.add(J);else Z.delete(J);h$({...W,disabledPlugins:[...Z]})}function a4($,f){let J=q8(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W))}function c1($,f){let J=j$(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W.name))}function t4($,f){if(!$||$.length===0)return $;let J=j$(f);if(J.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(Z,Q)=>W.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},Q)}})}var nj,y8,r4;var X$=M1(()=>{L0();nj=lf.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,lf.array(lf.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,W)=>J.localeCompare(W));return f.length>0?f:void 0}),y8=lf.object({telemetryOptOut:lf.boolean().default(!1).catch(!1),autoUpdateEnabled:lf.boolean().default(!0).catch(!0),disabledTools:nj.optional(),disabledPlugins:nj.optional()}).strip().transform(($)=>{let f={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});var YY={};w(YY,{updateMcpServerOAuthState:()=>Jf,setMcpServerDisabled:()=>$f,resolveMcpServerRegistrations:()=>H$,resolveDefaultMcpSettingsPath:()=>_0,registerMcpServersFromSettingsFile:()=>Wf,normalizeMcpServerOAuthState:()=>G2,loadMcpSettingsFile:()=>e1,listMcpServerOAuthStatuses:()=>DJ,hasMcpSettingsFile:()=>b$,getMcpServerOAuthState:()=>ff});import{existsSync as TL,mkdirSync as WY,readFileSync as QZ,writeFileSync as ZY}from"node:fs";import{dirname as QY}from"node:path";import{resolveMcpSettingsPath as NL}from"@cline/shared/storage";import{z as S}from"zod";function ZZ($){if(!$)return;if($==="http")return"streamableHttp";return $}function _0(){return NL()}function IL($){let f=QZ($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let Z=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function HY($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function xL($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function e1($={}){let f=$.filePath??_0(),J=QZ(f,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=kL.safeParse(W);if(!Z.success){let Q=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${Q}`)}return Z.data}function mL($){let f=QZ($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let W=J,Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return W}function G2($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function gL($){if($===void 0)return;let f=jZ.safeParse($);if(!f.success)return;return G2(f.data)}function b$($={}){let f=$.filePath??_0();return TL(f)}function H$($={}){let f=e1($);return Object.entries(f.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function $f($){let f=$.filePath??_0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let W=IL(f),Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let Q={...Z},j=HY(Q,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;xL(Q,J,X),WY(QY(f),{recursive:!0}),ZY(f,`${JSON.stringify({...W,mcpServers:Q},null,2)}
3
+ `,"utf8"),pU()}function i4(){return O0().telemetryOptOut}function tj($,f={}){h$({...O0(),telemetryOptOut:$},f)}function sj(){return O0().autoUpdateEnabled}function oj($,f={}){h$({...O0(),autoUpdateEnabled:$},f)}function j$($){return new Set($??O0().disabledTools??[])}function q8($){return new Set($??O0().disabledPlugins??[])}function ej($){return j$().has($)}function n4($){let f=O0(),J=new Set(f.disabledTools??[]),W=J.has($);if(W)J.delete($);else J.add($);return h$({...f,disabledTools:[...J]}),!W}function WZ($,f){let J=[...new Set($.map((Q)=>Q.trim()).filter(Boolean))];if(J.length===0)return;let W=O0(),Z=j$(W.disabledTools);for(let Q of J)if(f)Z.add(Q);else Z.delete(Q);h$({...W,disabledTools:[...Z]})}function $X($,f){return WZ([$],f),f}function fX($){return q8().has($)}function JX($,f){let J=$.trim();if(!J)return;let W=O0(),Z=q8(W.disabledPlugins);if(f)Z.add(J);else Z.delete(J);h$({...W,disabledPlugins:[...Z]})}function a4($,f){let J=q8(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W))}function c1($,f){let J=j$(f);if(J.size===0)return[...$];return $.filter((W)=>!J.has(W.name))}function t4($,f){if(!$||$.length===0)return $;let J=j$(f);if(J.size===0)return $;return $.map((W)=>{if(!W.setup)return W;return{...W,setup:(Z,Q)=>W.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},Q)}})}var nj,y8,r4;var X$=M1(()=>{L0();nj=lf.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,lf.array(lf.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,W)=>J.localeCompare(W));return f.length>0?f:void 0}),y8=lf.object({telemetryOptOut:lf.boolean().default(!1).catch(!1),autoUpdateEnabled:lf.boolean().default(!0).catch(!0),disabledTools:nj.optional(),disabledPlugins:nj.optional()}).strip().transform(($)=>{let f={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});var YY={};w(YY,{updateMcpServerOAuthState:()=>Jf,setMcpServerDisabled:()=>$f,resolveMcpServerRegistrations:()=>H$,resolveDefaultMcpSettingsPath:()=>_0,registerMcpServersFromSettingsFile:()=>Wf,normalizeMcpServerOAuthState:()=>G2,loadMcpSettingsFile:()=>e1,listMcpServerOAuthStatuses:()=>DJ,hasMcpSettingsFile:()=>b$,getMcpServerOAuthState:()=>ff});import{existsSync as TL,mkdirSync as WY,readFileSync as Q9,writeFileSync as ZY}from"node:fs";import{dirname as QY}from"node:path";import{resolveMcpSettingsPath as NL}from"@cline/shared/storage";import{z as S}from"zod";function Z9($){if(!$)return;if($==="http")return"streamableHttp";return $}function _0(){return NL()}function IL($){let f=Q9($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let Z=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function HY($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function xL($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function e1($={}){let f=$.filePath??_0(),J=Q9(f,"utf8"),W;try{W=JSON.parse(J)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=kL.safeParse(W);if(!Z.success){let Q=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${Q}`)}return Z.data}function mL($){let f=Q9($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let j=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let W=J,Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return W}function G2($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function gL($){if($===void 0)return;let f=j9.safeParse($);if(!f.success)return;return G2(f.data)}function b$($={}){let f=$.filePath??_0();return TL(f)}function H$($={}){let f=e1($);return Object.entries(f.mcpServers).map(([J,W])=>({name:J,transport:W.transport,disabled:W.disabled,metadata:W.metadata,oauth:W.oauth}))}function $f($){let f=$.filePath??_0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let W=IL(f),Z=W.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let Q={...Z},j=HY(Q,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;xL(Q,J,X),WY(QY(f),{recursive:!0}),ZY(f,`${JSON.stringify({...W,mcpServers:Q},null,2)}
4
4
  `)}function ff($,f={}){let J=e1(f);if(!Object.hasOwn(J.mcpServers,$))return;return G2(J.mcpServers[$]?.oauth)}function Jf($,f,J={}){let W=J.filePath??_0(),Z=mL(W),Q=Z.mcpServers,j=HY(Q,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let X=gL(j.oauth)??{},H=G2(f(X));if(H)j.oauth=H;else delete j.oauth;return WY(QY(W),{recursive:!0}),ZY(W,`${JSON.stringify(Z,null,2)}
5
- `,"utf8"),H??{}}function DJ($={}){return H$($).map((J)=>{let W=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:W,oauthConfigured:W&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,W)=>J.serverName.localeCompare(W.serverName))}async function Wf($,f={}){let J=H$(f);for(let W of J)await $.registerServer(W);return J}var RJ,jY,jZ,ML,yL,qL,wL,SL,hL,XY,CL,EL,bL,kL;var s6=M1(()=>{RJ=S.record(S.string(),S.string()),jY=S.record(S.string(),S.unknown()),jZ=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),ML=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:RJ.optional()}),yL=S.object({type:S.literal("sse"),url:S.string().url(),headers:RJ.optional()}),qL=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:RJ.optional()}),wL=S.discriminatedUnion("type",[ML,yL,qL]),SL=S.object({transport:wL,disabled:S.boolean().optional(),metadata:jY.optional(),oauth:jZ.optional()}),hL=S.enum(["stdio","sse","http","streamableHttp"]).optional(),XY=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:hL,disabled:S.boolean().optional(),metadata:jY.optional(),oauth:jZ.optional()});CL=XY.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:RJ.optional()}).superRefine(($,f)=>{let J=$.type??ZZ($.transportType);if(J&&J!=="stdio")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),EL=XY.extend({url:S.string().url(),headers:RJ.optional()}).superRefine(($,f)=>{let J=$.type??ZZ($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??ZZ($.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}}),bL=S.union([SL,CL,EL]),kL=S.object({mcpServers:S.record(S.string(),bL)}).passthrough()});import{existsSync as ET,mkdirSync as bT,readFileSync as kT,writeFileSync as IT}from"node:fs";import{resolve as xT}from"node:path";import{resolveSessionDataDir as mT}from"@cline/shared/storage";import{nanoid as gT}from"nanoid";import*as vT from"node-machine-id";function Kf($){let f=$?.trim();if(f)return f;let J=dT();if(J)return J;return lT()}function cT(){let $=vT;return $.machineIdSync??$.default?.machineIdSync}function dT(){try{let $=cT();if(!$)return;return $().trim()||void 0}catch{return}}function lT(){let $=mT(),f=xT($,uT);try{if(ET(f)){let W=kT(f,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${gT()}`;try{bT($,{recursive:!0}),IT(f,J,"utf8")}catch{}return J}var uT="machine-id";var z5=()=>{};class nJ{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($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.counters.get($);if(!Q)Q=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,Q);Q.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.histograms.get($);if(!Q)Q=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,Q);Q.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.buildAttributes(J),j=JSON.stringify(Q),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let H=X;if(!H)H=new Map,this.gaugeValues.set($,H);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,W?{description:W}:void 0);Y.addCallback((A)=>{for(let V of this.snapshotGaugeSeries($))A.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set($,Y)}H.set(j,{value:f,attributes:Q})}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($,f,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,W=0){if(!$)return{};let Z={},Q=100,j=10;for(let[X,H]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let Y=f?`${f}.${X}`:X;if(H===null||H===void 0){Z[Y]=String(H);continue}if(Array.isArray(H)){let A=H.length>Q?H.slice(0,Q):H;try{Z[Y]=JSON.stringify(A)}catch{Z[Y]="[UnserializableArray]"}if(H.length>Q)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=H.length;continue}if(typeof H==="object"){if(H instanceof Date){Z[Y]=H.toISOString();continue}if(H instanceof Error){Z[Y]=H.message;continue}if(J.has(H)){Z[Y]="[Circular]";continue}if(W>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(H),Object.assign(Z,this.flattenProperties(H,Y,J,W+1));continue}if(mN(H)){Z[Y]=H;continue}try{Z[Y]=JSON.stringify(H)}catch{Z[Y]=String(H)}}return Z}}function mN($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class aJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordHistogram($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordGauge($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:W,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class E2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new aJ({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 f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let W of this.adapters)W.emitRequired($,J)}recordCounter($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,Q,W,Z)}recordHistogram($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,Q,W,Z)}recordGauge($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,Q,W,Z)}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 GQ=()=>{};import{metrics as gN,trace as vN}from"@opentelemetry/api";import{logs as uN}from"@opentelemetry/api-logs";import{OTLPLogExporter as cN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as dN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as lN}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as pN}from"@opentelemetry/resources";import{BatchLogRecordProcessor as rN,ConsoleLogRecordExporter as iN,LoggerProvider as nN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as aN,MeterProvider as tN,PeriodicExportingMetricReader as PV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as sN,ConsoleSpanExporter as oN,SimpleSpanProcessor as eN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as $M}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as fM,ATTR_SERVICE_VERSION as JM}from"@opentelemetry/semantic-conventions";class UV{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($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class b2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=pN({[fM]:$.serviceName??"cline",...$.serviceVersion?{[JM]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)gN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)uN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return vN.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new nJ({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new E2({...$,adapters:[f],distinctId:Kf($.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 f=PQ(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),Z=f.map((Q)=>QM(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(Z.length===0)return null;return new tN({resource:$,readers:Z})}createTracerProvider($){let f=PQ(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let Q of f){let j=ZM(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new $M({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=PQ(this.options.logsExporter);if(f.length===0)return null;let J=f.map((W)=>{let Z=WM(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new rN(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new nN({resource:$,processors:J})}}function tJ($){let f=new b2($),J=f.createTelemetryService($);return J.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:f,telemetry:J}}function c$($){if(i4())return{telemetry:new UV($)};if($.enabled!==!0)return{telemetry:new E2({...$,distinctId:Kf($.distinctId)})};return tJ($)}function k2($){let{telemetry:f,provider:J}=c$($);return{telemetry:f,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function PQ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function WM($,f){if($==="console")return new iN;if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/logs");return new cN({url:J,headers:f.headers})}function ZM($,f){if($==="console")return new eN(new oN);if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/traces");return new sN(new lN({url:J,headers:f.headers}))}function QM($,f){if($==="console")return new PV({exporter:new aN,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/metrics");return new PV({exporter:new dN({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function UQ($,f){let J=new URL($),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith(f)?W:`${W}${f}`,J.toString()}var w5=M1(()=>{X$();z5();GQ()});var UB={};w(UB,{createOpenTelemetryTelemetryService:()=>tJ,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,OpenTelemetryProvider:()=>b2,OpenTelemetryAdapter:()=>nJ});var IQ=M1(()=>{w5()});import{AgentRuntimeAbortError as cS}from"@cline/agents";import{initVcr as dS}from"@cline/shared";import{normalizeProviderId as gS}from"@cline/llms";var UK={};w(UK,{LocalRuntimeHost:()=>F$});import{readdirSync as SS}from"node:fs";import{homedir as hS}from"node:os";import{isAbsolute as CS,join as x7,resolve as m7}from"node:path";import{captureSdkError as Of,createSessionId as ES,isLikelyAuthError as bS,normalizeUserInput as kS}from"@cline/shared";import{setHomeDirIfUnset as IS}from"@cline/shared/storage";L0();var z3={};w(z3,{createContextCompactionPrepareTurn:()=>$8});import{createHandlerAsync as gK}from"@cline/llms";import{estimateTokens as G9}from"@cline/shared";var o7=200000,P9=0.9,e7=16384,U9=20000,t7=1024,s7=2000,$3=2000,f3=8;function i$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
6
- ...[truncated ${$.length-f} chars]`}function kK($){let f=F9($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
5
+ `,"utf8"),H??{}}function DJ($={}){return H$($).map((J)=>{let W=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:W,oauthConfigured:W&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,W)=>J.serverName.localeCompare(W.serverName))}async function Wf($,f={}){let J=H$(f);for(let W of J)await $.registerServer(W);return J}var RJ,jY,j9,ML,yL,qL,wL,SL,hL,XY,CL,EL,bL,kL;var s6=M1(()=>{RJ=S.record(S.string(),S.string()),jY=S.record(S.string(),S.unknown()),j9=S.object({clientInformation:S.record(S.string(),S.unknown()).optional(),tokens:S.record(S.string(),S.unknown()).optional(),codeVerifier:S.string().optional(),discoveryState:S.record(S.string(),S.unknown()).optional(),redirectUrl:S.string().url().optional(),lastError:S.string().optional(),lastAuthenticatedAt:S.number().int().positive().optional()}).strip(),ML=S.object({type:S.literal("stdio"),command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:RJ.optional()}),yL=S.object({type:S.literal("sse"),url:S.string().url(),headers:RJ.optional()}),qL=S.object({type:S.literal("streamableHttp"),url:S.string().url(),headers:RJ.optional()}),wL=S.discriminatedUnion("type",[ML,yL,qL]),SL=S.object({transport:wL,disabled:S.boolean().optional(),metadata:jY.optional(),oauth:j9.optional()}),hL=S.enum(["stdio","sse","http","streamableHttp"]).optional(),XY=S.object({type:S.enum(["stdio","sse","streamableHttp"]).optional(),transportType:hL,disabled:S.boolean().optional(),metadata:jY.optional(),oauth:j9.optional()});CL=XY.extend({command:S.string().min(1),args:S.array(S.string()).optional(),cwd:S.string().min(1).optional(),env:RJ.optional()}).superRefine(($,f)=>{let J=$.type??Z9($.transportType);if(J&&J!=="stdio")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "stdio" for command-based MCP server',path:["type"]})}).transform(($)=>({transport:{type:"stdio",command:$.command,args:$.args,cwd:$.cwd,env:$.env},disabled:$.disabled,metadata:$.metadata,oauth:$.oauth})),EL=XY.extend({url:S.string().url(),headers:RJ.optional()}).superRefine(($,f)=>{let J=$.type??Z9($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:S.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??Z9($.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}}),bL=S.union([SL,CL,EL]),kL=S.object({mcpServers:S.record(S.string(),bL)}).passthrough()});import{existsSync as ET,mkdirSync as bT,readFileSync as kT,writeFileSync as IT}from"node:fs";import{resolve as xT}from"node:path";import{resolveSessionDataDir as mT}from"@cline/shared/storage";import{nanoid as gT}from"nanoid";import*as vT from"node-machine-id";function Kf($){let f=$?.trim();if(f)return f;let J=dT();if(J)return J;return lT()}function cT(){let $=vT;return $.machineIdSync??$.default?.machineIdSync}function dT(){try{let $=cT();if(!$)return;return $().trim()||void 0}catch{return}}function lT(){let $=mT(),f=xT($,uT);try{if(ET(f)){let W=kT(f,"utf8").trim();if(W.length>0)return W}}catch{}let J=`cl-${gT()}`;try{bT($,{recursive:!0}),IT(f,J,"utf8")}catch{}return J}var uT="machine-id";var z5=()=>{};class nJ{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($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.counters.get($);if(!Q)Q=this.meter.createCounter($,W?{description:W}:void 0),this.counters.set($,Q);Q.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.histograms.get($);if(!Q)Q=this.meter.createHistogram($,W?{description:W}:void 0),this.histograms.set($,Q);Q.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,W,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let Q=this.buildAttributes(J),j=JSON.stringify(Q),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let H=X;if(!H)H=new Map,this.gaugeValues.set($,H);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,W?{description:W}:void 0);Y.addCallback((A)=>{for(let V of this.snapshotGaugeSeries($))A.observe(V.value,this.flattenProperties(V.attributes))}),this.gauges.set($,Y)}H.set(j,{value:f,attributes:Q})}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($,f,J){if(!this.logger)return;let W=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:W})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,W=0){if(!$)return{};let Z={},Q=100,j=10;for(let[X,H]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let Y=f?`${f}.${X}`:X;if(H===null||H===void 0){Z[Y]=String(H);continue}if(Array.isArray(H)){let A=H.length>Q?H.slice(0,Q):H;try{Z[Y]=JSON.stringify(A)}catch{Z[Y]="[UnserializableArray]"}if(H.length>Q)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=H.length;continue}if(typeof H==="object"){if(H instanceof Date){Z[Y]=H.toISOString();continue}if(H instanceof Error){Z[Y]=H.message;continue}if(J.has(H)){Z[Y]="[Circular]";continue}if(W>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(H),Object.assign(Z,this.flattenProperties(H,Y,J,W+1));continue}if(mN(H)){Z[Y]=H;continue}try{Z[Y]=JSON.stringify(H)}catch{Z[Y]=String(H)}}return Z}}function mN($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class aJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordHistogram($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:W,required:Z===!0})}recordGauge($,f,J,W,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:W,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class E2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new aJ({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 f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let W of this.adapters)W.emitRequired($,J)}recordCounter($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,Q,W,Z)}recordHistogram($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,Q,W,Z)}recordGauge($,f,J,W,Z=!1){let Q=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,Q,W,Z)}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 GQ=()=>{};import{metrics as gN,trace as vN}from"@opentelemetry/api";import{logs as uN}from"@opentelemetry/api-logs";import{OTLPLogExporter as cN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as dN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as lN}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as pN}from"@opentelemetry/resources";import{BatchLogRecordProcessor as rN,ConsoleLogRecordExporter as iN,LoggerProvider as nN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as aN,MeterProvider as tN,PeriodicExportingMetricReader as PV}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as sN,ConsoleSpanExporter as oN,SimpleSpanProcessor as eN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as $M}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as fM,ATTR_SERVICE_VERSION as JM}from"@opentelemetry/semantic-conventions";class UV{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($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class b2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=pN({[fM]:$.serviceName??"cline",...$.serviceVersion?{[JM]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)gN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)uN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return vN.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new nJ({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new E2({...$,adapters:[f],distinctId:Kf($.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 f=PQ(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),W=Math.min(30000,Math.floor(J*0.8)),Z=f.map((Q)=>QM(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:W})).filter((Q)=>Q!==null);if(Z.length===0)return null;return new tN({resource:$,readers:Z})}createTracerProvider($){let f=PQ(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,W=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let Q of f){let j=ZM(Q,{endpoint:J,headers:W,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new $M({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=PQ(this.options.logsExporter);if(f.length===0)return null;let J=f.map((W)=>{let Z=WM(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new rN(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((W)=>W!==null);if(J.length===0)return null;return new nN({resource:$,processors:J})}}function tJ($){let f=new b2($),J=f.createTelemetryService($);return J.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:f,telemetry:J}}function c$($){if(i4())return{telemetry:new UV($)};if($.enabled!==!0)return{telemetry:new E2({...$,distinctId:Kf($.distinctId)})};return tJ($)}function k2($){let{telemetry:f,provider:J}=c$($);return{telemetry:f,provider:J,flush:async()=>{let Q=J;if(Q&&typeof Q.forceFlush==="function")try{await Q.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function PQ($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function WM($,f){if($==="console")return new iN;if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/logs");return new cN({url:J,headers:f.headers})}function ZM($,f){if($==="console")return new eN(new oN);if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/traces");return new sN(new lN({url:J,headers:f.headers}))}function QM($,f){if($==="console")return new PV({exporter:new aN,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=UQ(f.endpoint,"/v1/metrics");return new PV({exporter:new dN({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function UQ($,f){let J=new URL($),W=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=W.endsWith(f)?W:`${W}${f}`,J.toString()}var w5=M1(()=>{X$();z5();GQ()});var UB={};w(UB,{createOpenTelemetryTelemetryService:()=>tJ,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,OpenTelemetryProvider:()=>b2,OpenTelemetryAdapter:()=>nJ});var IQ=M1(()=>{w5()});import{AgentRuntimeAbortError as cS}from"@cline/agents";import{initVcr as dS}from"@cline/shared";import{normalizeProviderId as gS}from"@cline/llms";var UK={};w(UK,{LocalRuntimeHost:()=>F$});import{readdirSync as SS}from"node:fs";import{homedir as hS}from"node:os";import{isAbsolute as CS,join as x7,resolve as m7}from"node:path";import{captureSdkError as Of,createSessionId as ES,isLikelyAuthError as bS,normalizeUserInput as kS}from"@cline/shared";import{setHomeDirIfUnset as IS}from"@cline/shared/storage";L0();var z3={};w(z3,{createContextCompactionPrepareTurn:()=>$8});import{createHandlerAsync as gK}from"@cline/llms";import{estimateTokens as GW}from"@cline/shared";var o7=200000,PW=0.9,e7=16384,UW=20000,t7=1024,s7=2000,$3=2000,f3=8;function i$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
6
+ ...[truncated ${$.length-f} chars]`}function kK($){let f=FW($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
7
7
  ${J.content}
8
8
  </file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
9
- `)}function F9($){if(typeof $==="string")return i$($,s7);return $.map((f)=>{switch(f.type){case"text":return{...f,text:i$(f.text,s7)};case"file":return{...f,content:i$(f.content,$3)};case"image":return f;default:return f}})}function IK($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function J3($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${i$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${IK(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${kK(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${i$(J.content,$3)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
9
+ `)}function FW($){if(typeof $==="string")return i$($,s7);return $.map((f)=>{switch(f.type){case"text":return{...f,text:i$(f.text,s7)};case"file":return{...f,content:i$(f.content,$3)};case"image":return f;default:return f}})}function IK($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function J3($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${i$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${IK(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${kK(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${i$(J.content,$3)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
10
10
  `)}function W3($){return $.map(J3).join(`
11
11
 
12
- `).trim()}function Z3(){let $=new WeakMap;return(f)=>{let J=f,W=$.get(J);if(typeof W==="number")return W;let Z;try{Z=JSON.stringify(f)}catch{Z=J3(f)}let Q=G9(Z.length);return $.set(J,Q),Q}}function s2($){return $.metadata?.kind==="compaction_summary"}function R9($){if(!s2($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function xK($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function o2($){return $.role==="user"&&!xK($)&&!s2($)}function Q3($){for(let f=0;f<$.length;f+=1)if(o2($[f]))return f;return-1}function M4($){for(let f=$.length-1;f>=0;f-=1)if(o2($[f]))return f;return 0}function j3($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function X3($){for(let f=$.length-1;f>=0;f-=1)if(s2($[f]))return f;return-1}function H3($,f,J){let W=M4($);if(W<=0)return 0;let Z=0,Q=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),Q=X,Z>=f)break;if(Q<=0)return 0;let j=Math.min(Q,W);while(j>0&&!o2($[j]))j-=1;return j}function t2($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>t2(f));if($&&typeof $==="object"){let f=$,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...t2(f[W]));if(Array.isArray(f.files)){for(let W of f.files)if(W&&typeof W==="object")J.push(...t2(W.path))}if(Array.isArray(f.file_paths))J.push(...t2(f.file_paths));return J}return[]}function a2($,f){let J=new Set($);for(let W of f){let Z=W.trim();if(!Z)continue;J.add(Z)}return[...J].sort((W,Z)=>W.localeCompare(Z))}function Y3($){let f=[],J=[];for(let W of $){let Z=R9(W);if(Z){f=a2(f,Z.details.readFiles),J=a2(J,Z.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){f=a2(f,[Q.path]);continue}if(Q.type!=="tool_use")continue;let j=t2(Q.input);if(Q.name==="read_files"){f=a2(f,j);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=a2(J,j)}}return{readFiles:f,modifiedFiles:J}}function mK($){let f=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
12
+ `).trim()}function Z3(){let $=new WeakMap;return(f)=>{let J=f,W=$.get(J);if(typeof W==="number")return W;let Z;try{Z=JSON.stringify(f)}catch{Z=J3(f)}let Q=GW(Z.length);return $.set(J,Q),Q}}function s2($){return $.metadata?.kind==="compaction_summary"}function RW($){if(!s2($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((W)=>typeof W==="string").map((W)=>W.trim()).filter((W)=>W.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function xK($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function o2($){return $.role==="user"&&!xK($)&&!s2($)}function Q3($){for(let f=0;f<$.length;f+=1)if(o2($[f]))return f;return-1}function M4($){for(let f=$.length-1;f>=0;f-=1)if(o2($[f]))return f;return 0}function j3($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function X3($){for(let f=$.length-1;f>=0;f-=1)if(s2($[f]))return f;return-1}function H3($,f,J){let W=M4($);if(W<=0)return 0;let Z=0,Q=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),Q=X,Z>=f)break;if(Q<=0)return 0;let j=Math.min(Q,W);while(j>0&&!o2($[j]))j-=1;return j}function t2($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>t2(f));if($&&typeof $==="object"){let f=$,J=[];for(let W of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...t2(f[W]));if(Array.isArray(f.files)){for(let W of f.files)if(W&&typeof W==="object")J.push(...t2(W.path))}if(Array.isArray(f.file_paths))J.push(...t2(f.file_paths));return J}return[]}function a2($,f){let J=new Set($);for(let W of f){let Z=W.trim();if(!Z)continue;J.add(Z)}return[...J].sort((W,Z)=>W.localeCompare(Z))}function Y3($){let f=[],J=[];for(let W of $){let Z=RW(W);if(Z){f=a2(f,Z.details.readFiles),J=a2(J,Z.details.modifiedFiles);continue}if(!Array.isArray(W.content))continue;for(let Q of W.content){if(Q.type==="file"){f=a2(f,[Q.path]);continue}if(Q.type!=="tool_use")continue;let j=t2(Q.input);if(Q.name==="read_files"){f=a2(f,j);continue}if(Q.name==="editor"||Q.name==="apply_patch")J=a2(J,j)}}return{readFiles:f,modifiedFiles:J}}function mK($){let f=$.readFiles.length>0?$.readFiles.map((W)=>`- ${W}`).join(`
13
13
  `):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((W)=>`- ${W}`).join(`
14
14
  `):"- none";return`## Files
15
15
  Read:
@@ -41,9 +41,9 @@ ${$.conversationText||"(empty)"}`),f.join(`
41
41
 
42
42
  `)}function B3($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:Q,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??t7,thinking:!1}};if(!f)return J($.activeProviderConfig);let W=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...W??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??W?.apiKey,baseUrl:f.baseUrl??W?.baseUrl,headers:f.headers??W?.headers,knownModels:f.knownModels??W?.knownModels,maxOutputTokens:f.maxOutputTokens??t7})}function K3($){return{role:"user",content:`Context summary:
43
43
 
44
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function vK($){let f=await gK($.providerConfig),J="";for await(let W of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function uK($){try{return JSON.stringify($).length}catch{return String($).length}}async function G3($){let f=$.context.messages;if(f.length<2)return;let J=H3(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let W=f.slice(0,J),Z=X3(W),Q=Z>=0?R9(W[Z])?.summary:void 0,j=Z>=0?W.slice(Z+1):W;if(j.length===0)return;let X=Y3(W),H=W3(j),Y=V3({previousSummary:Q,conversationText:H,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:Q?.length??0,conversationTextChars:H.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:G9(Y.length),newMessagesJsonChars:uK(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let A=await vK({providerConfig:B3({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!A.trim())return;let V=A3(A,X),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[K3({summary:V,fileOps:X,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function F3($){if(s2($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:F9(J.content)}:J)}}function e2($,f){return $.reduce((J,W)=>J+f(W),0)}function P3($,f){let J=Math.max(1,f),W=Math.max(16,J*4);if(typeof $.content==="string"){let j=i$($.content,W).trim();return{...$,content:j||"..."}}let Z=W,Q=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=i$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:Q}}function cK($,f){let J=Q3($),W=M4($),Z=j3($),Q=[];for(let j=0;j<$.length;j+=1){let X=F3($[j]);if(!X)continue;Q.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===W,isLastAssistant:j===Z})}return Q}function U3($,f,J,W){let Z=$[f];Z.message=J,Z.estimatedTokens=W(J)}function dK($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function lK($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function R3($){return new Set([...dK($.message),...lK($.message)])}function pK($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let W of R3($[J])){let Z=f.get(W);if(Z)Z.add(J);else f.set(W,new Set([J]))}return f}function rK($,f){let J=pK($),W=new Set,Z=[f];while(Z.length>0){let Q=Z.shift();if(Q===void 0||W.has(Q))continue;W.add(Q);for(let j of R3($[Q]))for(let X of J.get(j)??[])if(!W.has(X))Z.push(X)}return W}function y4($,f,J,W){let Z=e2($.map((Q)=>Q.message),W);for(let Q=0;Q<$.length&&Z>J;){if(!f($[Q])){Q+=1;continue}let j=rK($,Q);Z-=Array.from(j).reduce((X,H)=>X+$[H].estimatedTokens,0);for(let X of Array.from(j).sort((H,Y)=>Y-H))$.splice(X,1)}}function iK($,f,J){let W=e2($.map((Q)=>Q.message),J);if(W<=f)return;for(let Q=$.length-1;Q>=0&&W>f;Q-=1){let j=$[Q];if(j.isFirstUser)continue;let X=Math.max(f3,j.estimatedTokens-(W-f));if(X>=j.estimatedTokens)continue;U3($,Q,P3(j.message,X),J),W=e2($.map((H)=>H.message),J)}if(W<=f)return;let Z=$.findIndex((Q)=>Q.isFirstUser);if(Z>=0){let Q=Math.max(1,$[Z].estimatedTokens-(W-f));U3($,Z,P3($[Z].message,Q),J)}}function nK($,f){return JSON.stringify($)!==JSON.stringify(f)}function aK($){let f=M4($);if(f<0||f===0&&!o2($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function D3($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:W}=aK($.context.messages);if(J.length===0)return;let Z=cK(J,$.estimateMessageTokens);if(Z.length===0)return;y4(Z,(H)=>H.message.role==="assistant"&&!H.isLastAssistant,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="user"&&!H.isFirstUser&&!H.isLastUser,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="assistant"&&H.isLastAssistant,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="user"&&H.isLastUser&&!H.isFirstUser,f,$.estimateMessageTokens),iK(Z,f,$.estimateMessageTokens);let Q=[...Z.map((H)=>H.message),...W];if(!nK($.context.messages,Q))return;let j=e2([...J.map((H)=>F3(H)??H),...W],$.estimateMessageTokens),X=e2(Q,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:Q.length,messagesRemoved:$.context.messages.length-Q.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:Q}}function L3($){try{return JSON.stringify($).length}catch{return String($).length}}function tK($){let f=0,J=0,W=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;let j=L3(Q.content);f+=1,J+=j,W=Math.max(W,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:W}}var sK={basic:({context:$,estimateMessageTokens:f,logger:J})=>D3({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:W,estimateMessageTokens:Z,logger:Q})=>G3({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??U9,$.triggerTokens):J?.preserveRecentTokens??U9,estimateMessageTokens:Z,logger:Q})};function oK($){if(typeof $.config.reserveTokens==="number"){let W=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-W);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let W=Math.max(0,Math.min($.maxInputTokens-e7,$.maxInputTokens*P9));return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}let f=$.config.thresholdRatio??P9,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function eK($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function $8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=Z3(),Q=J?.strategy??"basic",j=sK[Q],X=f.mode??"auto",H=J?.compact?"custom":Q;return async(Y)=>{let A=Y.apiMessages.reduce((z,N)=>z+Z(N),0),V=J?.maxInputTokens??Y.model.info?.maxInputTokens??Y.model.info?.contextWindow??o7;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=oK({inputTokens:A,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:Q,iteration:Y.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:A,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:Y.messages.length,apiMessageCount:Y.apiMessages.length,apiMessagesJsonChars:L3(Y.apiMessages),...tK(Y.apiMessages)}),X==="auto"&&!B.shouldCompact)return;let K=X==="manual"?eK({inputTokens:A,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId,iteration:Y.iteration,messages:Y.messages,model:Y.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?A/V:0},R=X==="manual"?"manual_compaction":"auto_compaction";Y.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:Y.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let P=Y.messages.length,U=Date.now(),F=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...W,abortSignal:Y.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),O=Date.now()-U,_=$.sessionId??Y.conversationId,D={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((N,q)=>N+Z(q),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:Q,maxInputTokens:V,inputTokens:A,afterTokens:z,tokensSaved:A-z,utilizationBefore:`${(A/V*100).toFixed(1)}%`,utilizationAfter:`${(z/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length}),T4($.telemetry,{ulid:_,strategy:H,mode:X,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length,tokensBefore:A,tokensAfter:z,tokensSaved:A-z,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...D})}else N4($.telemetry,{ulid:_,strategy:H,mode:X,reason:"no_result",tokensBefore:A,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...D});return F}}var Ij={};w(Ij,{zodToJsonSchema:()=>TU,validateWithZod:()=>_U,resolveToolRoutingConfig:()=>hf,resolveToolPresetName:()=>q$,resolveCoreSelectedToolIds:()=>g4,getCoreHeadlessToolNames:()=>D8,getCoreDefaultEnabledToolIds:()=>m4,getCoreBuiltinToolCatalog:()=>I1,getCoreAcpToolNames:()=>v4,createWindowsShellTool:()=>M9,createWebFetchTool:()=>y9,createWebFetchExecutor:()=>U8,createToolPoliciesWithPreset:()=>C4,createSubmitAndExitTool:()=>h9,createSkillsTool:()=>w1,createSearchTool:()=>T9,createSearchExecutor:()=>P8,createReadFilesTool:()=>_9,createFileReadExecutor:()=>G8,createEditorTool:()=>w9,createEditorExecutor:()=>B8,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>s$,createDefaultExecutors:()=>wf,createBuiltinTools:()=>x1,createBashTool:()=>N9,createBashExecutor:()=>V8,createAskQuestionTool:()=>S9,createApplyPatchTool:()=>q9,createApplyPatchExecutor:()=>A8,WebFetchRequestSchema:()=>z9,ToolPresets:()=>I0,TEAM_TOOL_NAMES:()=>kf,SubmitInputSchema:()=>Y8,SkillsInputSchema:()=>X8,SearchCodebaseInputSchema:()=>W8,RunCommandsInputSchema:()=>Mf,ReadFilesInputSchema:()=>J8,ReadFileRequestSchema:()=>T$,FetchWebContentInputSchema:()=>Z8,EditFileInputSchema:()=>Q8,DefaultToolNames:()=>J0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>Sf,AskQuestionInputSchema:()=>H8,ApplyPatchInputSchema:()=>j8,ALL_DEFAULT_TOOL_NAMES:()=>n$});import{validateWithZod as _U,zodToJsonSchema as TU}from"@cline/shared";var J0={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"},n$=[J0.READ_FILES,J0.SEARCH_CODEBASE,J0.RUN_COMMANDS,J0.FETCH_WEB_CONTENT,J0.APPLY_PATCH,J0.EDITOR,J0.SKILLS,J0.ASK,J0.SUBMIT_AND_EXIT];L0();import{createTool as N$,validateWithZod as M$,zodToJsonSchema as Q$}from"@cline/shared";var O3="__clineInternalTelemetry";function _3($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as $G}from"@cline/shared";import{z as L}from"zod";var a$=6000,f8=L.string().describe("The absolute file path of a text file to read content from"),T3=L.object({start_line:L.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:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),T$=L.object({path:f8,start_line:T3.shape.start_line,end_line:T3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),J8=L.object({files:L.array(T$).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),N3=L.union([J8,T$,L.array(T$),L.array(L.string()),L.string(),L.object({files:L.array(L.union([f8,T$]))}),L.object({files:T$}),L.object({files:f8}),L.object({file_paths:L.array(f8)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([f8,T$]))}),L.object({paths:T$}),L.object({paths:L.string()})]),W8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),M3=L.union([W8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),y1=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${a$*2} characters) to avoid timeouts.`),Mf=L.object({commands:L.array(y1).describe("Array of shell commands to execute")}),y3=L.union([Mf,L.object({commands:y1}),L.object({command:y1}),L.object({cmd:y1}),L.array(L.string()),L.string()]),D9=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),q3=L.union([y1,D9]),L9=L.object({commands:L.array(q3).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.")}),w3=L.union([Mf,L9,L.object({commands:q3}),L.array(D9),D9,L.object({command:y1}),L.object({cmd:y1}),L.array(L.string()),L.string()]),z9=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),Z8=L.object({requests:L.array(z9).describe("Array of the URLs for the web fetch requests")}),Q8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.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 ${a$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.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 ${a$} 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:L.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."),j8=L.object({input:L.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."),S3=L.union([j8,L.string()]),X8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),H8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),Y8=L.object({summary:L.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:L.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.
44
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function vK($){let f=await gK($.providerConfig),J="";for await(let W of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(W.type==="text"){J+=W.text;continue}if(W.type==="done"&&!W.success&&W.error)throw Error(W.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function uK($){try{return JSON.stringify($).length}catch{return String($).length}}async function G3($){let f=$.context.messages;if(f.length<2)return;let J=H3(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let W=f.slice(0,J),Z=X3(W),Q=Z>=0?RW(W[Z])?.summary:void 0,j=Z>=0?W.slice(Z+1):W;if(j.length===0)return;let X=Y3(W),H=W3(j),Y=V3({previousSummary:Q,conversationText:H,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:W.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:Q?.length??0,conversationTextChars:H.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:GW(Y.length),newMessagesJsonChars:uK(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let A=await vK({providerConfig:B3({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!A.trim())return;let V=A3(A,X),B=f.reduce((R,P)=>R+$.estimateMessageTokens(P),0),K=[K3({summary:V,fileOps:X,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,P)=>R+$.estimateMessageTokens(P),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function F3($){if(s2($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:FW(J.content)}:J)}}function e2($,f){return $.reduce((J,W)=>J+f(W),0)}function P3($,f){let J=Math.max(1,f),W=Math.max(16,J*4);if(typeof $.content==="string"){let j=i$($.content,W).trim();return{...$,content:j||"..."}}let Z=W,Q=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=i$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:Q}}function cK($,f){let J=Q3($),W=M4($),Z=j3($),Q=[];for(let j=0;j<$.length;j+=1){let X=F3($[j]);if(!X)continue;Q.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===W,isLastAssistant:j===Z})}return Q}function U3($,f,J,W){let Z=$[f];Z.message=J,Z.estimatedTokens=W(J)}function dK($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function lK($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function R3($){return new Set([...dK($.message),...lK($.message)])}function pK($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let W of R3($[J])){let Z=f.get(W);if(Z)Z.add(J);else f.set(W,new Set([J]))}return f}function rK($,f){let J=pK($),W=new Set,Z=[f];while(Z.length>0){let Q=Z.shift();if(Q===void 0||W.has(Q))continue;W.add(Q);for(let j of R3($[Q]))for(let X of J.get(j)??[])if(!W.has(X))Z.push(X)}return W}function y4($,f,J,W){let Z=e2($.map((Q)=>Q.message),W);for(let Q=0;Q<$.length&&Z>J;){if(!f($[Q])){Q+=1;continue}let j=rK($,Q);Z-=Array.from(j).reduce((X,H)=>X+$[H].estimatedTokens,0);for(let X of Array.from(j).sort((H,Y)=>Y-H))$.splice(X,1)}}function iK($,f,J){let W=e2($.map((Q)=>Q.message),J);if(W<=f)return;for(let Q=$.length-1;Q>=0&&W>f;Q-=1){let j=$[Q];if(j.isFirstUser)continue;let X=Math.max(f3,j.estimatedTokens-(W-f));if(X>=j.estimatedTokens)continue;U3($,Q,P3(j.message,X),J),W=e2($.map((H)=>H.message),J)}if(W<=f)return;let Z=$.findIndex((Q)=>Q.isFirstUser);if(Z>=0){let Q=Math.max(1,$[Z].estimatedTokens-(W-f));U3($,Z,P3($[Z].message,Q),J)}}function nK($,f){return JSON.stringify($)!==JSON.stringify(f)}function aK($){let f=M4($);if(f<0||f===0&&!o2($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function D3($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:W}=aK($.context.messages);if(J.length===0)return;let Z=cK(J,$.estimateMessageTokens);if(Z.length===0)return;y4(Z,(H)=>H.message.role==="assistant"&&!H.isLastAssistant,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="user"&&!H.isFirstUser&&!H.isLastUser,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="assistant"&&H.isLastAssistant,f,$.estimateMessageTokens),y4(Z,(H)=>H.message.role==="user"&&H.isLastUser&&!H.isFirstUser,f,$.estimateMessageTokens),iK(Z,f,$.estimateMessageTokens);let Q=[...Z.map((H)=>H.message),...W];if(!nK($.context.messages,Q))return;let j=e2([...J.map((H)=>F3(H)??H),...W],$.estimateMessageTokens),X=e2(Q,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:Q.length,messagesRemoved:$.context.messages.length-Q.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:Q}}function L3($){try{return JSON.stringify($).length}catch{return String($).length}}function tK($){let f=0,J=0,W=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let Q of Z.content){if(Q.type!=="tool_result")continue;let j=L3(Q.content);f+=1,J+=j,W=Math.max(W,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:W}}var sK={basic:({context:$,estimateMessageTokens:f,logger:J})=>D3({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:W,estimateMessageTokens:Z,logger:Q})=>G3({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:W==="manual"?Math.min(J?.preserveRecentTokens??UW,$.triggerTokens):J?.preserveRecentTokens??UW,estimateMessageTokens:Z,logger:Q})};function oK($){if(typeof $.config.reserveTokens==="number"){let W=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-W);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let W=Math.max(0,Math.min($.maxInputTokens-e7,$.maxInputTokens*PW));return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}let f=$.config.thresholdRatio??PW,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function eK($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),W=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}function $8($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let W=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=Z3(),Q=J?.strategy??"basic",j=sK[Q],X=f.mode??"auto",H=J?.compact?"custom":Q;return async(Y)=>{let A=Y.apiMessages.reduce((z,N)=>z+Z(N),0),V=J?.maxInputTokens??Y.model.info?.maxInputTokens??Y.model.info?.contextWindow??o7;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let B=oK({inputTokens:A,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:Q,iteration:Y.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:A,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:Y.messages.length,apiMessageCount:Y.apiMessages.length,apiMessagesJsonChars:L3(Y.apiMessages),...tK(Y.apiMessages)}),X==="auto"&&!B.shouldCompact)return;let K=X==="manual"?eK({inputTokens:A,maxInputTokens:V,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,G={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId,iteration:Y.iteration,messages:Y.messages,model:Y.model,maxInputTokens:V,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:V>0?A/V:0},R=X==="manual"?"manual_compaction":"auto_compaction";Y.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:Y.iteration,triggerTokens:K.triggerTokens,maxInputTokens:V});let P=Y.messages.length,U=Date.now(),F=J?.compact?await J.compact(G):await j({context:G,providerConfig:{...W,abortSignal:Y.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),O=Date.now()-U,_=$.sessionId??Y.conversationId,D={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((N,q)=>N+Z(q),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:Q,maxInputTokens:V,inputTokens:A,afterTokens:z,tokensSaved:A-z,utilizationBefore:`${(A/V*100).toFixed(1)}%`,utilizationAfter:`${(z/V*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length}),T4($.telemetry,{ulid:_,strategy:H,mode:X,messagesBefore:P,messagesAfter:F.messages.length,messagesRemoved:P-F.messages.length,tokensBefore:A,tokensAfter:z,tokensSaved:A-z,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...D})}else N4($.telemetry,{ulid:_,strategy:H,mode:X,reason:"no_result",tokensBefore:A,triggerTokens:K.triggerTokens,maxInputTokens:V,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...D});return F}}var Ij={};w(Ij,{zodToJsonSchema:()=>TU,validateWithZod:()=>_U,resolveToolRoutingConfig:()=>hf,resolveToolPresetName:()=>q$,resolveCoreSelectedToolIds:()=>g4,getCoreHeadlessToolNames:()=>D8,getCoreDefaultEnabledToolIds:()=>m4,getCoreBuiltinToolCatalog:()=>I1,getCoreAcpToolNames:()=>v4,createWindowsShellTool:()=>MW,createWebFetchTool:()=>yW,createWebFetchExecutor:()=>U8,createToolPoliciesWithPreset:()=>C4,createSubmitAndExitTool:()=>hW,createSkillsTool:()=>w1,createSearchTool:()=>TW,createSearchExecutor:()=>P8,createReadFilesTool:()=>_W,createFileReadExecutor:()=>G8,createEditorTool:()=>wW,createEditorExecutor:()=>B8,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>s$,createDefaultExecutors:()=>wf,createBuiltinTools:()=>x1,createBashTool:()=>NW,createBashExecutor:()=>V8,createAskQuestionTool:()=>SW,createApplyPatchTool:()=>qW,createApplyPatchExecutor:()=>A8,WebFetchRequestSchema:()=>zW,ToolPresets:()=>I0,TEAM_TOOL_NAMES:()=>kf,SubmitInputSchema:()=>Y8,SkillsInputSchema:()=>X8,SearchCodebaseInputSchema:()=>W8,RunCommandsInputSchema:()=>Mf,ReadFilesInputSchema:()=>J8,ReadFileRequestSchema:()=>T$,FetchWebContentInputSchema:()=>Z8,EditFileInputSchema:()=>Q8,DefaultToolNames:()=>J0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>Sf,AskQuestionInputSchema:()=>H8,ApplyPatchInputSchema:()=>j8,ALL_DEFAULT_TOOL_NAMES:()=>n$});import{validateWithZod as _U,zodToJsonSchema as TU}from"@cline/shared";var J0={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"},n$=[J0.READ_FILES,J0.SEARCH_CODEBASE,J0.RUN_COMMANDS,J0.FETCH_WEB_CONTENT,J0.APPLY_PATCH,J0.EDITOR,J0.SKILLS,J0.ASK,J0.SUBMIT_AND_EXIT];L0();import{createTool as N$,validateWithZod as M$,zodToJsonSchema as Q$}from"@cline/shared";var O3="__clineInternalTelemetry";function _3($){let f=$?.__clineInternalTelemetry;return f&&typeof f==="object"&&"capture"in f&&typeof f.capture==="function"?f:void 0}import{validateWithZod as $G}from"@cline/shared";import{z as L}from"zod";var a$=6000,f8=L.string().describe("The absolute file path of a text file to read content from"),T3=L.object({start_line:L.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:L.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),T$=L.object({path:f8,start_line:T3.shape.start_line,end_line:T3.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),J8=L.object({files:L.array(T$).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),N3=L.union([J8,T$,L.array(T$),L.array(L.string()),L.string(),L.object({files:L.array(L.union([f8,T$]))}),L.object({files:T$}),L.object({files:f8}),L.object({file_paths:L.array(f8)}),L.object({file_paths:L.string()}),L.object({paths:L.array(L.union([f8,T$]))}),L.object({paths:T$}),L.object({paths:L.string()})]),W8=L.object({queries:L.array(L.string()).describe("Array of regex search queries to execute")}),M3=L.union([W8,L.array(L.string()),L.string(),L.object({queries:L.string()})]),y1=L.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${a$*2} characters) to avoid timeouts.`),Mf=L.object({commands:L.array(y1).describe("Array of shell commands to execute")}),y3=L.union([Mf,L.object({commands:y1}),L.object({command:y1}),L.object({cmd:y1}),L.array(L.string()),L.string()]),DW=L.object({command:L.string().min(1).describe("The executable to run directly without shell parsing."),args:L.array(L.string()).optional().describe("Optional argv list passed directly to the executable.")}),q3=L.union([y1,DW]),LW=L.object({commands:L.array(q3).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.")}),w3=L.union([Mf,LW,L.object({commands:q3}),L.array(DW),DW,L.object({command:y1}),L.object({cmd:y1}),L.array(L.string()),L.string()]),zW=L.object({url:L.string().describe("The URL to fetch"),prompt:L.string().min(2).describe("Analysis prompt for the fetched content")}),Z8=L.object({requests:L.array(zW).describe("Array of the URLs for the web fetch requests")}),Q8=L.object({path:L.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:L.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 ${a$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:L.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 ${a$} 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:L.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."),j8=L.object({input:L.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."),S3=L.union([j8,L.string()]),X8=L.object({skill:L.string().min(1).describe("Name of the skill to execute."),args:L.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),H8=L.object({question:L.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:L.array(L.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),Y8=L.object({summary:L.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:L.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.
45
45
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
46
- 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 h3($){if(typeof $.old_text==="string"&&$.old_text.length>a$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${a$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>a$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${a$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class q1 extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function Z$($,f,J){return Promise.race([$,new Promise((W,Z)=>{setTimeout(()=>Z(new q1(J,f)),f)})])}function q4($){let{path:f,start_line:J,end_line:W}=$;if(J==null&&W==null)return f;return`${f}:${J??1}-${W??"EOF"}`}function C3($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function E3($){let f=$G(w3,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function O9($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${J.join(" ")}`}function b3($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function k3($,f){a7(_3($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:b3($,"mode"),source:b3($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function _9($,f={}){let J=f.fileReadTimeoutMs??1e4;return N$({name:"read_files",description:"Read the full 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. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:Q$(J8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Z)=>{let Q=M$(N3,W),j;if(typeof Q==="string")j=[{path:Q}];else if(Array.isArray(Q))j=Q.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in Q)j=(Array.isArray(Q.files)?Q.files:[Q.files]).map((H)=>typeof H==="string"?{path:H}:H);else if("file_paths"in Q)j=(Array.isArray(Q.file_paths)?Q.file_paths:[Q.file_paths]).map((H)=>({path:H}));else if("paths"in Q)j=(Array.isArray(Q.paths)?Q.paths:[Q.paths]).map((H)=>typeof H==="string"?{path:H}:H);else j=[Q];return Promise.all(j.map(async(X)=>{let H=C3(X);if(H)return{query:q4(X),result:"",error:`Invalid file range: ${H}`,success:!1};try{let Y=await Z$($(X,Z),J,`File read timed out after ${J}ms`);return{query:q4(X),result:Y,success:!0}}catch(Y){let A=t$(Y);return{query:q4(X),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function T9($,f={}){let J=f.searchTimeoutMs??30000,W=f.cwd??process.cwd();return N$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:Q$(W8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,Q)=>{let j=M$(M3,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(H)=>{try{let Y=await Z$($(H,W,Q),J,`Search timed out after ${J}ms`),A=Y.length>0&&!Y.includes("No results found");return{query:H,result:Y,success:A}}catch(Y){let A=t$(Y);return{query:H,result:"",error:`Search failed: ${A}`,success:!1}}}))}})}function N9($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return N$({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:Q$(Mf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=M$(y3,Q),H;if(typeof X==="string")H=[X];else if(Array.isArray(X))H=X;else if("commands"in X)H=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)H=[X.command];else H=[X.cmd];return Promise.all(H.map(async(Y)=>{let A=Date.now();try{let V=await Z$($(Y,Z,j),J,`Command timed out after ${J}ms`);return{query:Y,result:V,success:!0}}catch(V){if(V instanceof q1)k3(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:W,commandCount:H.length,durationMs:Date.now()-A});let B=t$(V);return{query:Y,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function M9($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return N$({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:Q$(L9),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=E3(Q);return Promise.all(X.map(async(H)=>{let Y=Date.now();try{let A=await Z$($(H,Z,j),J,`Command timed out after ${J}ms`);return{query:O9(H),result:A,success:!0}}catch(A){if(A instanceof q1)k3(j,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:W,commandCount:X.length,durationMs:Date.now()-Y});let V=t$(A);return{query:O9(H),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function y9($,f={}){let J=f.webFetchTimeoutMs??30000;return N$({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.",inputSchema:Q$(Z8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,Z)=>{let Q=M$(Z8,W);return Promise.all(Q.requests.map(async(j)=>{try{let X=await Z$($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let H=t$(X);return{query:j.url,result:"",error:`Error fetching web content: ${H}`,success:!1}}}))}})}var fG=`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:
46
+ 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 h3($){if(typeof $.old_text==="string"&&$.old_text.length>a$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${a$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>a$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${a$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class q1 extends Error{timeoutMs;constructor($,f){super($);this.name="TimeoutError",this.timeoutMs=f}}function Z$($,f,J){return Promise.race([$,new Promise((W,Z)=>{setTimeout(()=>Z(new q1(J,f)),f)})])}function q4($){let{path:f,start_line:J,end_line:W}=$;if(J==null&&W==null)return f;return`${f}:${J??1}-${W??"EOF"}`}function C3($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function E3($){let f=$G(w3,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function OW($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((W)=>/[\s"]/u.test(W)?JSON.stringify(W):W);return`${$.command} ${J.join(" ")}`}function b3($,f){let J=$.metadata?.[f];return typeof J==="string"?J:void 0}function k3($,f){a7(_3($.metadata),{tool_name:"run_commands",effective_timeout_ms:f.effectiveTimeoutMs,timeout_source:f.timeoutSource,command_count:f.commandCount,duration_ms:f.durationMs,ulid:$.sessionId,mode:b3($,"mode"),source:b3($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function _W($,f={}){let J=f.fileReadTimeoutMs??1e4;return N$({name:"read_files",description:"Read the full 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. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:Q$(J8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(W,Z)=>{let Q=M$(N3,W),j;if(typeof Q==="string")j=[{path:Q}];else if(Array.isArray(Q))j=Q.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in Q)j=(Array.isArray(Q.files)?Q.files:[Q.files]).map((H)=>typeof H==="string"?{path:H}:H);else if("file_paths"in Q)j=(Array.isArray(Q.file_paths)?Q.file_paths:[Q.file_paths]).map((H)=>({path:H}));else if("paths"in Q)j=(Array.isArray(Q.paths)?Q.paths:[Q.paths]).map((H)=>typeof H==="string"?{path:H}:H);else j=[Q];return Promise.all(j.map(async(X)=>{let H=C3(X);if(H)return{query:q4(X),result:"",error:`Invalid file range: ${H}`,success:!1};try{let Y=await Z$($(X,Z),J,`File read timed out after ${J}ms`);return{query:q4(X),result:Y,success:!0}}catch(Y){let A=t$(Y);return{query:q4(X),result:"",error:`Error reading file: ${A}`,success:!1}}}))}})}function TW($,f={}){let J=f.searchTimeoutMs??30000,W=f.cwd??process.cwd();return N$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:Q$(W8),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,Q)=>{let j=M$(M3,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(H)=>{try{let Y=await Z$($(H,W,Q),J,`Search timed out after ${J}ms`),A=Y.length>0&&!Y.includes("No results found");return{query:H,result:Y,success:A}}catch(Y){let A=t$(Y);return{query:H,result:"",error:`Search failed: ${A}`,success:!1}}}))}})}function NW($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return N$({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:Q$(Mf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=M$(y3,Q),H;if(typeof X==="string")H=[X];else if(Array.isArray(X))H=X;else if("commands"in X)H=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)H=[X.command];else H=[X.cmd];return Promise.all(H.map(async(Y)=>{let A=Date.now();try{let V=await Z$($(Y,Z,j),J,`Command timed out after ${J}ms`);return{query:Y,result:V,success:!0}}catch(V){if(V instanceof q1)k3(j,{effectiveTimeoutMs:V.timeoutMs,timeoutSource:W,commandCount:H.length,durationMs:Date.now()-A});let B=t$(V);return{query:Y,result:"",error:`Command failed: ${B}`,success:!1}}}))}})}function MW($,f={}){let J=f.bashTimeoutMs??30000,W=f.bashTimeoutMs===void 0?"default_setting":"configured_setting",Z=f.cwd??process.cwd();return N$({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:Q$(LW),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=E3(Q);return Promise.all(X.map(async(H)=>{let Y=Date.now();try{let A=await Z$($(H,Z,j),J,`Command timed out after ${J}ms`);return{query:OW(H),result:A,success:!0}}catch(A){if(A instanceof q1)k3(j,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:W,commandCount:X.length,durationMs:Date.now()-Y});let V=t$(A);return{query:OW(H),result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function yW($,f={}){let J=f.webFetchTimeoutMs??30000;return N$({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.",inputSchema:Q$(Z8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(W,Z)=>{let Q=M$(Z8,W);return Promise.all(Q.requests.map(async(j)=>{try{let X=await Z$($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let H=t$(X);return{query:j.url,result:"",error:`Error fetching web content: ${H}`,success:!1}}}))}})}var fG=`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:
47
47
 
48
48
  *** Begin Patch
49
49
  *** Update File: path/to/file.ts
@@ -79,7 +79,7 @@ Example:
79
79
  </div>
80
80
  );
81
81
  }
82
- *** End Patch`;function q9($,f={}){let J=f.applyPatchTimeoutMs??30000,W=f.cwd??process.cwd();return N$({name:"apply_patch",description:fG,inputSchema:Q$(j8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=M$(S3,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await Z$($({input:X},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(H){return{query:"apply_patch",result:"",error:`apply_patch failed: ${t$(H)}`,success:!1}}}})}function w9($,f={}){let J=f.editorTimeoutMs??30000,W=f.cwd??process.cwd();return N$({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 tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:Q$(Q8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=M$(Q8,Z),X=j.insert_line==null?"edit":"insert",H=h3(j);if(H)return{query:`${X}:${j.path}`,result:"",error:H,success:!1};try{let Y=await Z$($(j,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:Y,success:!0}}catch(Y){let A=t$(Y);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${A}`,success:!1}}}})}function w1($,f={}){let J=f.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.',Z=N$({name:"skills",description:W,inputSchema:Q$(X8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=M$(X8,Q);return Z$($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let Q=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),Z}function S9($){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:Q$(H8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let W=M$(H8,f);return $(W.question,W.options,J)}}}function h9($,f={}){let J=f.submitTimeoutMs??15000;return N$({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:Q$(Y8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=M$(Y8,W);return Z$($(Q.summary,Q.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function s$($){let{executors:f,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:Z=!0,enableWebFetch:Q=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:H=!0,enableAskQuestion:Y=!0,enableSubmitAndExit:A=!1,...V}=$,B=[];if(J&&f.readFile)B.push(_9(f.readFile,V));if(W&&f.search)B.push(T9(f.search,V));if(Z&&f.bash)if(process.platform==="win32")B.push(M9(f.bash,V));else B.push(N9(f.bash,V));if(Q&&f.webFetch)B.push(y9(f.webFetch,V));if(X&&f.editor)B.push(w9(f.editor,V));else if(j&&f.applyPatch)B.push(q9(f.applyPatch,V));if(H&&f.skills)B.push(w1(f.skills,V));let K=A?f.submit:void 0;if(Y&&f.askQuestion&&!K)B.push(S9(f.askQuestion));if(K)B.push(h9(K,V));return B}import*as b0 from"node:fs/promises";import*as k0 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"},x3=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor($){super($);this.name="DiffError"}}function E0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class C9{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}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 Z0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new Z0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",W=this.parseUpdateFile(J,$);W.movePath=f,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},W=$.split(`
82
+ *** End Patch`;function qW($,f={}){let J=f.applyPatchTimeoutMs??30000,W=f.cwd??process.cwd();return N$({name:"apply_patch",description:fG,inputSchema:Q$(j8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=M$(S3,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await Z$($({input:X},W,Q),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(H){return{query:"apply_patch",result:"",error:`apply_patch failed: ${t$(H)}`,success:!1}}}})}function wW($,f={}){let J=f.editorTimeoutMs??30000,W=f.cwd??process.cwd();return N$({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 tools for making small, precise edits to existing files or creating new files over shell commands.",inputSchema:Q$(Q8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,Q)=>{let j=M$(Q8,Z),X=j.insert_line==null?"edit":"insert",H=h3(j);if(H)return{query:`${X}:${j.path}`,result:"",error:H,success:!1};try{let Y=await Z$($(j,W,Q),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:Y,success:!0}}catch(Y){let A=t$(Y);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${A}`,success:!1}}}})}function w1($,f={}){let J=f.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.',Z=N$({name:"skills",description:W,inputSchema:Q$(X8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,j)=>{let X=M$(X8,Q);return Z$($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let Q=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(Q&&Q.length>0)return`${W} Available skills: ${Q.join(", ")}.`;return W},enumerable:!0,configurable:!0}),Z}function SW($){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:Q$(H8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let W=M$(H8,f);return $(W.question,W.options,J)}}}function hW($,f={}){let J=f.submitTimeoutMs??15000;return N$({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:Q$(Y8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,Z)=>{let Q=M$(Y8,W);return Z$($(Q.summary,Q.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function s$($){let{executors:f,enableReadFiles:J=!0,enableSearch:W=!0,enableBash:Z=!0,enableWebFetch:Q=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:H=!0,enableAskQuestion:Y=!0,enableSubmitAndExit:A=!1,...V}=$,B=[];if(J&&f.readFile)B.push(_W(f.readFile,V));if(W&&f.search)B.push(TW(f.search,V));if(Z&&f.bash)if(process.platform==="win32")B.push(MW(f.bash,V));else B.push(NW(f.bash,V));if(Q&&f.webFetch)B.push(yW(f.webFetch,V));if(X&&f.editor)B.push(wW(f.editor,V));else if(j&&f.applyPatch)B.push(qW(f.applyPatch,V));if(H&&f.skills)B.push(w1(f.skills,V));let K=A?f.submit:void 0;if(Y&&f.askQuestion&&!K)B.push(SW(f.askQuestion));if(K)B.push(hW(K,V));return B}import*as b0 from"node:fs/promises";import*as k0 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"},x3=["%%bash","apply_patch","EOF","```"];class Z0 extends Error{constructor($){super($);this.name="DiffError"}}function E0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class CW{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}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 Z0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new Z0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(v.MOVE)?(this.lines[this.index++]??"").substring(v.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new Z0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",W=this.parseUpdateFile(J,$);W.movePath=f,this.patch.actions[$]=W,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},W=$.split(`
83
83
  `),Z=0,Q=[v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(!Q.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],X=j?.startsWith("@@ ")?j.substring(3):void 0;if(X!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new Z0(`Invalid Line:
84
84
  ${this.lines[this.index]}`);if(X?.trim()){let P=E0(X.trim());for(let U=Z;U<W.length;U++){let F=W[U];if(F&&(E0(F)===P||E0(F.trim())===P)){if(Z=U+1,E0(F.trim())===P&&E0(F)!==P)this.fuzz++;break}}}let[Y,A,V,B]=ZG(this.lines,this.index),[K,G,R]=WG(W,Y,Z,B);if(K===-1){let P=Y.join(`
85
85
  `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:P.length>200?`${P.substring(0,200)}...`:P}),this.index=V}else{this.fuzz+=G;for(let P of A)P.origIndex+=K,J.chunks.push(P);Z=K+Y.length,this.index=V}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new Z0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new Z0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[v.END,v.UPDATE,v.DELETE,v.ADD];while(this.hasMoreLines()&&!J.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 Z0(`Invalid Add File line (missing '+'): ${W}`);f.push(W.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
@@ -90,11 +90,11 @@ ${this.lines[this.index]}`);if(X?.trim()){let P=E0(X.trim());for(let U=Z;U<W.len
90
90
  `));if(A===V)return[Y,1,1]}for(let Y=j;Y<$.length;Y++){let A=E0($.slice(Y,Y+f.length).map((B)=>B.trim()).join(`
91
91
  `)),V=E0(f.map((B)=>B.trim()).join(`
92
92
  `));if(A===V)return[Y,100,1]}let H=0.66;for(let Y=j;Y<$.length;Y++){let A=E0($.slice(Y,Y+f.length).join(`
93
- `)),V=I3(A,X);if(V>=H)return[Y,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(W){let[j,X,H]=Q($.length-f.length);if(j!==-1)return[j,X,H];return[j,X,H]=Q(J),[j,X+1e4,H]}return Q(J)}function ZG($,f){let J=f,W=[],Z=[],Q=[],j=[],X="keep",H=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(J<$.length){let Y=$[J];if(!Y||H.some((B)=>Y.startsWith(B.trim())))break;if(Y==="***")break;if(Y.startsWith("***"))throw new Z0(`Invalid line: ${Y}`);J++;let A=X,V=Y;if(V[0]==="+")X="add";else if(V[0]==="-")X="delete";else if(V[0]===" ")X="keep";else X="keep",V=` ${V}`;if(V=V.slice(1),X==="keep"&&A!==X){if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});Z=[],Q=[]}if(X==="delete")Z.push(V),W.push(V);else if(X==="add")Q.push(V);else W.push(V)}if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});if(J<$.length&&$[J]===v.END_FILE)return J++,[W,j,J,!0];return[W,j,J,!1]}function E9($,f,J){let W=k0.isAbsolute(f),Z=W?k0.normalize(f):k0.resolve($,f);if(!J||W)return Z;let Q=k0.relative($,Z);if(Q.startsWith("..")||k0.isAbsolute(Q))throw new Z0(`Path must stay within cwd: ${f}`);return Z}function QG($){return $.split(`
93
+ `)),V=I3(A,X);if(V>=H)return[Y,1000,V];if(V>Z)Z=V}return[-1,0,Z]};if(W){let[j,X,H]=Q($.length-f.length);if(j!==-1)return[j,X,H];return[j,X,H]=Q(J),[j,X+1e4,H]}return Q(J)}function ZG($,f){let J=f,W=[],Z=[],Q=[],j=[],X="keep",H=["@@",v.END,v.UPDATE,v.DELETE,v.ADD,v.END_FILE];while(J<$.length){let Y=$[J];if(!Y||H.some((B)=>Y.startsWith(B.trim())))break;if(Y==="***")break;if(Y.startsWith("***"))throw new Z0(`Invalid line: ${Y}`);J++;let A=X,V=Y;if(V[0]==="+")X="add";else if(V[0]==="-")X="delete";else if(V[0]===" ")X="keep";else X="keep",V=` ${V}`;if(V=V.slice(1),X==="keep"&&A!==X){if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});Z=[],Q=[]}if(X==="delete")Z.push(V),W.push(V);else if(X==="add")Q.push(V);else W.push(V)}if(Q.length||Z.length)j.push({origIndex:W.length-Z.length,delLines:Z,insLines:Q});if(J<$.length&&$[J]===v.END_FILE)return J++,[W,j,J,!0];return[W,j,J,!1]}function EW($,f,J){let W=k0.isAbsolute(f),Z=W?k0.normalize(f):k0.resolve($,f);if(!J||W)return Z;let Q=k0.relative($,Z);if(Q.startsWith("..")||k0.isAbsolute(Q))throw new Z0(`Path must stay within cwd: ${f}`);return Z}function QG($){return $.split(`
94
94
  `).map((f)=>f.replace(/\r$/,""))}function m3($){if($.trim()==="")return!1;return x3.some((f)=>$.startsWith(f))}function jG($){let f=0,J=$.length;while(f<J&&m3($[f]??""))f++;while(J>f&&m3($[J-1]??""))J--;return $.slice(f,J)}function XG($){let f=QG($),J=f.findIndex((j)=>j.startsWith(v.BEGIN)),W=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(v.END)){W=j;break}if(J!==-1||W!==-1){if(J===-1||W===-1||W<J)throw new Z0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,W+1)}}let Z=jG(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[v.BEGIN,...Z,v.END]}}function HG($,f){let J=new Set;for(let W of $)for(let Z of f)if(W.startsWith(Z)){J.add(W.substring(Z.length).trim());break}return[...J]}function YG($,f,J){if(f.length===0)return $;let W=$.split(`
95
95
  `),Z=[],Q=0;for(let j of f){if(j.origIndex>W.length)throw new Z0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${W.length}`);if(Q>j.origIndex)throw new Z0(`${J}: currentIndex ${Q} > chunk.origIndex ${j.origIndex}`);Z.push(...W.slice(Q,j.origIndex)),Z.push(...j.insLines),Q=j.origIndex+j.delLines.length}return Z.push(...W.slice(Q)),Z.join(`
96
- `)}async function AG($,f,J,W){let Z=HG($,[v.UPDATE,v.DELETE]),Q={};for(let j of Z){let X=E9(f,j,W),H;try{H=await b0.readFile(X,J)}catch{throw new Z0(`File not found: ${j}`)}Q[j]=H.replace(/\r\n/g,`
97
- `)}return Q}function VG($,f){let J={};for(let[W,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[W]={type:"delete",oldContent:f[W]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[W]={type:"add",newContent:Z.newFile};break;case"update":J[W]={type:"update",oldContent:f[W],newContent:YG(f[W]??"",Z.chunks,W),movePath:Z.movePath};break}return J}async function BG($,f,J,W){let Z=[];for(let[Q,j]of Object.entries($)){let X=E9(f,Q,W);switch(j.type){case"delete":await b0.rm(X,{force:!0}),Z.push(`${Q}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${Q} with no content`);await b0.mkdir(k0.dirname(X),{recursive:!0}),await b0.writeFile(X,j.newContent,{encoding:J}),Z.push(Q);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${Q} has no new content`);if(j.movePath){let H=E9(f,j.movePath,W);await b0.mkdir(k0.dirname(H),{recursive:!0}),await b0.writeFile(H,j.newContent,{encoding:J}),await b0.rm(X,{force:!0}),Z.push(`${Q} -> ${j.movePath}`)}else await b0.writeFile(X,j.newContent,{encoding:J}),Z.push(Q);break}}}return Z}function A8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(W,Z,Q)=>{let j=XG(W.input),X=await AG(j.lines,Z,f,J),H=new C9(j.lines,X),{patch:Y,fuzz:A}=H.parse(),V=VG(Y,X),B=await BG(V,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(A>0)K.push(`Note: Patch applied with fuzz factor ${A}`);if(Y.warnings&&Y.warnings.length>0)for(let G of Y.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
96
+ `)}async function AG($,f,J,W){let Z=HG($,[v.UPDATE,v.DELETE]),Q={};for(let j of Z){let X=EW(f,j,W),H;try{H=await b0.readFile(X,J)}catch{throw new Z0(`File not found: ${j}`)}Q[j]=H.replace(/\r\n/g,`
97
+ `)}return Q}function VG($,f){let J={};for(let[W,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[W]={type:"delete",oldContent:f[W]};break;case"add":if(Z.newFile===void 0)throw new Z0("ADD action without file content");J[W]={type:"add",newContent:Z.newFile};break;case"update":J[W]={type:"update",oldContent:f[W],newContent:YG(f[W]??"",Z.chunks,W),movePath:Z.movePath};break}return J}async function BG($,f,J,W){let Z=[];for(let[Q,j]of Object.entries($)){let X=EW(f,Q,W);switch(j.type){case"delete":await b0.rm(X,{force:!0}),Z.push(`${Q}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new Z0(`Cannot create ${Q} with no content`);await b0.mkdir(k0.dirname(X),{recursive:!0}),await b0.writeFile(X,j.newContent,{encoding:J}),Z.push(Q);break;case"update":{if(j.newContent===void 0)throw new Z0(`UPDATE change for ${Q} has no new content`);if(j.movePath){let H=EW(f,j.movePath,W);await b0.mkdir(k0.dirname(H),{recursive:!0}),await b0.writeFile(H,j.newContent,{encoding:J}),await b0.rm(X,{force:!0}),Z.push(`${Q} -> ${j.movePath}`)}else await b0.writeFile(X,j.newContent,{encoding:J}),Z.push(Q);break}}}return Z}function A8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(W,Z,Q)=>{let j=XG(W.input),X=await AG(j.lines,Z,f,J),H=new CW(j.lines,X),{patch:Y,fuzz:A}=H.parse(),V=VG(Y,X),B=await BG(V,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(A>0)K.push(`Note: Patch applied with fuzz factor ${A}`);if(Y.warnings&&Y.warnings.length>0)for(let G of Y.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
98
98
  `)}}import{spawn as g3}from"node:child_process";import{getDefaultShell as KG,getShellArgs as GG}from"@cline/shared";function PG($,f,J,W,Z){return new Promise((Q,j)=>{let X=process.platform==="win32",H=g3($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X}),Y=H.pid,A="",V="",B=0,K=!1,G=!1,R=(D)=>{if(G)return;G=!0,D()},P=()=>{if(!Y)return;if(X){g3("taskkill",["/pid",String(Y),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-Y,"SIGKILL")}catch{H.kill("SIGKILL")}},U=(D)=>{K=!0,P(),R(()=>j(D))},F=setTimeout(()=>U(new q1(`Command timed out after ${J}ms`,J)),J),O=()=>U(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",O);let _=()=>{clearTimeout(F),f.signal?.removeEventListener("abort",O)};H.stdout?.on("data",(D)=>{if(B+=D.length,B<=W)A+=D.toString()}),H.stderr?.on("data",(D)=>{if(B+=D.length,B<=W)V+=D.toString()}),H.on("close",(D)=>{if(_(),K)return;let z=Z?A+(V?`
99
99
  [stderr]
100
100
  ${V}`:""):A;if(B>W)z+=`
@@ -109,7 +109,7 @@ ${H}`}async function OG($,f,J,W){let Q=(await o0.readFile($,W)).split(`
109
109
  `),{encoding:W}),`Inserted content at line ${f} in ${$}.`}function B8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:W=200}=$;return async(Z,Q,j)=>{let X=UG(Q,Z.path,J);if(Z.insert_line!=null)return OG(X,Z.insert_line,Z.new_text,f);if(!await LG(X))return DG(X,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return zG(X,Z.old_text,Z.new_text,f,W)}}import*as K8 from"node:fs/promises";import*as o$ from"node:path";import{resolveExistingFilePath as _G}from"@cline/shared/storage";var TG=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),NG={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function G8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:W}={...NG,...$};return async(Z,Q)=>{let{path:j,start_line:X,end_line:H}=Z,Y=o$.isAbsolute(j)?o$.normalize(j):o$.resolve(process.cwd(),j),A=_G(Y)??Y,V=o$.extname(A).toLowerCase(),B=TG.get(V),K=await K8.stat(A);if(!K.isFile())throw Error(`Path is not a file: ${A}`);if(K.size>f)throw Error(`File too large: ${K.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(Q.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let O=await K8.readFile(A);return[{type:"text",text:"Successfully read image"},{type:"image",data:O.toString("base64"),mediaType:B}]}let R=(await K8.readFile(A,J)).split(`
110
110
  `),P=Math.max((X??1)-1,0),U=Math.min(H??R.length,R.length),F=R.slice(P,U);if(W){let O=String(R.length).length;return F.map((_,D)=>`${String(P+D+1).padStart(O," ")} | ${_}`).join(`
111
111
  `)}return F.join(`
112
- `)}}import{spawn as r3}from"node:child_process";import*as i3 from"node:fs/promises";import*as h4 from"node:path";var p3={};w(p3,{prewarmFileIndex:()=>S4,getFileIndex:()=>y$,enrichPromptWithMentions:()=>qf});import{spawn as MG}from"node:child_process";import{readdir as yG}from"node:fs/promises";import k9 from"node:path";import{isMainThread as c3,parentPort as v3,Worker as qG}from"node:worker_threads";var wG=15000,SG=600000,hG=1000,CG=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function u3($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var yf=new Map;function EG(){if(!c3)return!1;return!0}function bG($){if(yf.size<=1)return;for(let[f,J]of yf.entries()){if(J.pending)continue;if($-J.lastAccessedAt>SG)yf.delete(f)}}function kG($,f){return k9.relative($,f).split(k9.sep).join("/")}async function IG($){let J=(await new Promise((W,Z)=>{let Q=MG("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",X="";Q.stdout.on("data",(H)=>{j+=H.toString()}),Q.stderr.on("data",(H)=>{X+=H.toString()}),Q.on("error",Z),Q.on("close",(H)=>{if(H===0){W(j);return}Z(Error(X||`rg exited with code ${H}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function d3($,f,J){let W;try{W=await yG(f,{withFileTypes:!0})}catch(Z){if(u3(Z))return;throw Z}for(let Z of W){let Q=k9.join(f,Z.name);if(Z.isDirectory()){if(CG.has(Z.name))continue;try{await d3($,Q,J)}catch(j){if(u3(j))continue;throw j}continue}if(Z.isFile())J.add(kG($,Q))}}async function xG($){let f=new Set;return await d3($,$,f),f}async function w4($){try{return await IG($)}catch{return xG($)}}function mG(){if(c3||!v3)return;let $=v3;$.on("message",(f)=>{if(f.type!=="index")return;w4(f.cwd).then((J)=>{let W={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(W)})})}class l3{worker=new qG(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.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 f=++this.nextRequestId,J=new Promise((Z,Q)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},hG);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),Q(X)}})}),W={type:"index",requestId:f,cwd:$};return this.worker.postMessage(W),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}mG();var b9;function gG(){if(!EG())return null;if(b9===void 0)b9=new l3;return b9}async function vG($){let f=gG();if(!f)return w4($);try{let J=await f.requestIndex($);if(J===null)return w4($);return new Set(J)}catch{return w4($)}}async function y$($,f={}){let J=f.ttlMs??wG,W=Date.now();bG(W);let Z=yf.get($);if(Z&&J>0&&W-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=W,Z.files;if(Z?.pending)return Z.lastAccessedAt=W,Z.pending;let Q=vG($).then((j)=>{return yf.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return yf.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function S4($,f={}){await y$($,{...f,ttlMs:0})}import{stat as uG}from"node:fs/promises";import S1 from"node:path";var cG=/[),.:;!?`'"]+$/,dG=/^[(`'"]+/;function lG($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of f){let Z=(W[2]??"").trim();if(Z.length===0)continue;let Q=Z.replace(dG,"").replace(cG,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function pG($,f){let J=$.replace(/\\/g,"/"),W=S1.isAbsolute(J)?S1.resolve(J):S1.resolve(f,J),Z=S1.relative(f,W);if(Z.startsWith("..")||S1.isAbsolute(Z))return;return Z.split(S1.sep).join("/")}async function qf($,f,J={}){let W=lG($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:Q,maxTotalBytes:j}=J,X=await y$(f,{ttlMs:J.ttlMs}),H=[],Y=[],A=[],V=0;for(let B of W){if(Z&&A.length>=Z){Y.push(B);continue}let K=pG(B,f);if(!K||!X.has(K)){Y.push(B);continue}if(!Q||!j){H.push(K);continue}let G=S1.join(f,K);try{if(!(await uG(G)).isFile()){Y.push(B);continue}let P=V+Q;if(P>j){Y.push(B);continue}V=P,H.push(K)}catch{Y.push(B)}}return{prompt:$,mentions:W,matchedFiles:H,ignoredMentions:Y}}var rG=["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"],iG=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],h1=null;function nG(){if(h1!==null)return Promise.resolve(h1);return new Promise(($)=>{let f=r3("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{h1=J===0,$(h1)}),f.on("error",()=>{h1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(h1===null)h1=!1,$(!1)},1000)})}function aG($,f,J,W,Z=5000,Q){return new Promise((j)=>{let X=r3("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),H="",Y=!1,A=()=>{if(!X.killed)X.kill("SIGTERM")},V=setTimeout(()=>{if(!Y)Y=!0,A(),j(null)},Z),B=(K)=>{if(!Y)Y=!0,clearTimeout(V),A(),j(K)};if(Q?.aborted){A(),j(null);return}Q?.addEventListener("abort",()=>{B(null)}),X.stdout.on("data",(K)=>{H+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=H.split(`
112
+ `)}}import{spawn as r3}from"node:child_process";import*as i3 from"node:fs/promises";import*as h4 from"node:path";var p3={};w(p3,{prewarmFileIndex:()=>S4,getFileIndex:()=>y$,enrichPromptWithMentions:()=>qf});import{spawn as MG}from"node:child_process";import{readdir as yG}from"node:fs/promises";import kW from"node:path";import{isMainThread as c3,parentPort as v3,Worker as qG}from"node:worker_threads";var wG=15000,SG=600000,hG=1000,CG=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function u3($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var yf=new Map;function EG(){if(!c3)return!1;return!0}function bG($){if(yf.size<=1)return;for(let[f,J]of yf.entries()){if(J.pending)continue;if($-J.lastAccessedAt>SG)yf.delete(f)}}function kG($,f){return kW.relative($,f).split(kW.sep).join("/")}async function IG($){let J=(await new Promise((W,Z)=>{let Q=MG("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",X="";Q.stdout.on("data",(H)=>{j+=H.toString()}),Q.stderr.on("data",(H)=>{X+=H.toString()}),Q.on("error",Z),Q.on("close",(H)=>{if(H===0){W(j);return}Z(Error(X||`rg exited with code ${H}`))})})).split(/\r?\n/).map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>W.replace(/\\/g,"/"));return new Set(J)}async function d3($,f,J){let W;try{W=await yG(f,{withFileTypes:!0})}catch(Z){if(u3(Z))return;throw Z}for(let Z of W){let Q=kW.join(f,Z.name);if(Z.isDirectory()){if(CG.has(Z.name))continue;try{await d3($,Q,J)}catch(j){if(u3(j))continue;throw j}continue}if(Z.isFile())J.add(kG($,Q))}}async function xG($){let f=new Set;return await d3($,$,f),f}async function w4($){try{return await IG($)}catch{return xG($)}}function mG(){if(c3||!v3)return;let $=v3;$.on("message",(f)=>{if(f.type!=="index")return;w4(f.cwd).then((J)=>{let W={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(W)}).catch((J)=>{let W={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(W)})})}class l3{worker=new qG(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.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 f=++this.nextRequestId,J=new Promise((Z,Q)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},hG);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),Q(X)}})}),W={type:"index",requestId:f,cwd:$};return this.worker.postMessage(W),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}mG();var bW;function gG(){if(!EG())return null;if(bW===void 0)bW=new l3;return bW}async function vG($){let f=gG();if(!f)return w4($);try{let J=await f.requestIndex($);if(J===null)return w4($);return new Set(J)}catch{return w4($)}}async function y$($,f={}){let J=f.ttlMs??wG,W=Date.now();bG(W);let Z=yf.get($);if(Z&&J>0&&W-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=W,Z.files;if(Z?.pending)return Z.lastAccessedAt=W,Z.pending;let Q=vG($).then((j)=>{return yf.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return yf.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:W,pending:Q}),Q}async function S4($,f={}){await y$($,{...f,ttlMs:0})}import{stat as uG}from"node:fs/promises";import S1 from"node:path";var cG=/[),.:;!?`'"]+$/,dG=/^[(`'"]+/;function lG($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let W of f){let Z=(W[2]??"").trim();if(Z.length===0)continue;let Q=Z.replace(dG,"").replace(cG,"");if(Q.length===0||Q.includes("@"))continue;J.push(Q)}return Array.from(new Set(J))}function pG($,f){let J=$.replace(/\\/g,"/"),W=S1.isAbsolute(J)?S1.resolve(J):S1.resolve(f,J),Z=S1.relative(f,W);if(Z.startsWith("..")||S1.isAbsolute(Z))return;return Z.split(S1.sep).join("/")}async function qf($,f,J={}){let W=lG($);if(W.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:Q,maxTotalBytes:j}=J,X=await y$(f,{ttlMs:J.ttlMs}),H=[],Y=[],A=[],V=0;for(let B of W){if(Z&&A.length>=Z){Y.push(B);continue}let K=pG(B,f);if(!K||!X.has(K)){Y.push(B);continue}if(!Q||!j){H.push(K);continue}let G=S1.join(f,K);try{if(!(await uG(G)).isFile()){Y.push(B);continue}let P=V+Q;if(P>j){Y.push(B);continue}V=P,H.push(K)}catch{Y.push(B)}}return{prompt:$,mentions:W,matchedFiles:H,ignoredMentions:Y}}var rG=["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"],iG=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],h1=null;function nG(){if(h1!==null)return Promise.resolve(h1);return new Promise(($)=>{let f=r3("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{h1=J===0,$(h1)}),f.on("error",()=>{h1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(h1===null)h1=!1,$(!1)},1000)})}function aG($,f,J,W,Z=5000,Q){return new Promise((j)=>{let X=r3("rg",["--json",`--context=${W}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),H="",Y=!1,A=()=>{if(!X.killed)X.kill("SIGTERM")},V=setTimeout(()=>{if(!Y)Y=!0,A(),j(null)},Z),B=(K)=>{if(!Y)Y=!0,clearTimeout(V),A(),j(K)};if(Q?.aborted){A(),j(null);return}Q?.addEventListener("abort",()=>{B(null)}),X.stdout.on("data",(K)=>{H+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=H.split(`
113
113
  `).filter((P)=>P.trim());for(let P of R){if(G.length>=J)break;let U=JSON.parse(P);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let _=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(_?.start??0)+1,match:_?.match?.text??"",context:O})}}else if(U.type==="context"&&G.length>0){let F=G[G.length-1],O=U.data.line_number===F.line?">":" ";F.context.push(`${O} ${U.data.line_number}: ${U.data.lines?.text??U.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),X.on("error",()=>{B(null)})})}function tG($,f,J,W){let Z=$.split("/"),Q=Z[Z.length-1]??"";if(Z.length-1>W)return!1;for(let H=0;H<Z.length-1;H++)if(f.has(Z[H]??""))return!1;let X=h4.posix.extname(Q).slice(1).toLowerCase();return J.has(X)||!X&&!Q.startsWith(".")}function P8($={}){let{includeExtensions:f=rG,excludeDirs:J=iG,maxResults:W=100,contextLines:Z=2,maxDepth:Q=20}=$,j=new Set(J),X=new Set(f.map((H)=>H.toLowerCase()));return async(H,Y,A)=>{if(A.signal?.aborted)throw Error("Search operation aborted");let V=await nG(),B=null;if(V)B=await aG(H,Y,W,Z,5000,A.signal);if(B){let F=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${H}`,""];for(let O of B)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(B.length>=W)F.push(`(Showing first ${W} results. Refine your search for more specific results.)`);return F.join(`
114
114
  `)}let K;try{K=new RegExp(H,"gim")}catch(F){throw Error(`Invalid regex pattern: ${H}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,P=await y$(Y);for(let F of P){if(A.signal?.aborted)throw Error("Search operation aborted");if(!tG(F,j,X,Q))continue;if(G.length>=W)break;R++;let O=h4.join(Y,F);try{let D=(await i3.readFile(O,"utf-8")).split(`
115
115
  `);for(let z=0;z<D.length;z++){let N=D[z];K.lastIndex=0;let q=K.exec(N);while(q!==null){if(G.length>=W)break;let $0=Math.max(0,z-Z),A0=Math.min(D.length-1,z+Z),o=[];for(let V0=$0;V0<=A0;V0++){let i=V0===z?">":" ";o.push(`${i} ${V0+1}: ${D[V0]}`)}if(G.push({file:F,line:z+1,column:q.index+1,match:q[0],context:o}),q.index===K.lastIndex)K.lastIndex++;q=K.exec(N)}}}catch{}}if(G.length===0)return`No results found for pattern: ${H}
@@ -120,7 +120,7 @@ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for
120
120
 
121
121
  `).trim()}function U8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:W="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:Q=!0}=$;return async(j,X,H)=>{let Y;try{Y=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(Y.protocol))throw Error(`Invalid protocol: ${Y.protocol}. Only http and https are supported.`);let A=new AbortController,V=setTimeout(()=>A.abort(),f),B;if(H.signal)B=()=>A.abort(),H.signal.addEventListener("abort",B);try{let K=await fetch(j,{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",...Z},redirect:Q?"follow":"manual",signal:A.signal});if(clearTimeout(V),!Q&&K.status>=300&&K.status<400)return`Redirect to: ${K.headers.get("location")}`;if(!K.ok)throw Error(`HTTP ${K.status}: ${K.statusText}`);let G=K.headers.get("content-type")||"",R=K.body?.getReader();if(!R)throw Error("Failed to read response body");let P=[],U=0;while(!0){let{done:N,value:q}=await R.read();if(N)break;if(U+=q.length,U>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);P.push(q)}let F=new Uint8Array(U),O=0;for(let N of P)F.set(N,O),O+=N.length;let _=new TextDecoder("utf-8").decode(F),D;if(G.includes("text/html")||G.includes("application/xhtml"))D=sG(_);else if(G.includes("application/json"))try{let N=JSON.parse(_);D=JSON.stringify(N,null,2)}catch{D=_}else D=_;let z=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",D.slice(0,50000)];if(D.length>50000)z.push(`
122
122
  [Content truncated: showing first 50000 of ${D.length} characters]`);return z.push("","--- Analysis Request ---",`Prompt: ${X}`),z.join(`
123
- `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(H.signal&&B)H.signal.removeEventListener("abort",B)}}}function wf($={}){return{readFile:G8($.fileRead),search:P8($.search),bash:V8($.bash),webFetch:U8($.webFetch),applyPatch:A8($.applyPatch),editor:B8($.editor)}}var oG={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"},Sf=[{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 n3($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((W)=>J.includes(W.toLowerCase()))}function eG($,f,J,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return n3(f,$.providerIdIncludes)&&n3(J,$.modelIdIncludes)}function hf($,f,J,W){if(!W||W.length===0)return{};let Z=new Map;for(let j of W){if(!eG(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let Q={};for(let[j,X]of Z.entries())Q[oG[j]]=X;return Q}var I0={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 q$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function C4($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let W of n$)J[W]=f;return J}function E4($,f){let J=I0[$],{enableSpawnAgent:W,enableAgentTeams:Z,...Q}=J;return s$({...Q,...f})}import{createTool as $U,zodToJsonSchema as fU}from"@cline/shared";import{z as p9}from"zod";import{createAgentRuntime as pP}from"@cline/agents";import{createContributionRegistry as rP}from"@cline/shared";import{createGateway as YP,createHandlerAsync as AP,hasRegisteredHandler as VP,MODEL_COLLECTIONS_BY_PROVIDER_ID as BP,normalizeProviderId as KP}from"@cline/llms";import{EMPTY_CONTENT_TEXT as $P}from"@cline/shared";function fP($){let f=WP($.content),J=[],W=$.id??jP(),Z=0,Q=[],j=()=>{if(Q.length===0)return;let X=Z===0?W:`${W}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:Q.map(ZP),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:a3($.metrics)}),Q=[]};if(f.length===0)return J.push({id:W,role:$.role,content:[{type:"text",text:$P}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:a3($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){Q.push(X);continue}j(),J.push({id:`${W}_tool_${X.tool_use_id}`,role:"tool",content:[s3(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function b4($){return $.flatMap(fP)}function JP($){let f=$.content.map(o3).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:QP($.metrics)}}function Cf($){return $.map(JP)}function k4($){let f=[];for(let J of $){let W=J.content.map(o3).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,Q=f[f.length-1];if(Z==="user"&&W.length>0&&W.every((j)=>j.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((j)=>j.type==="tool_result")){Q.content.push(...W);continue}f.push({role:Z,content:W})}return f}function WP($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function ZP($){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 s3($)}}function s3($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function o3($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.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 f=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:f?.thoughtSignature??f?.signature}}case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function a3($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function QP($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var t3=0;function jP(){return t3+=1,`msg_${Date.now().toString(36)}_${t3.toString(36)}`}function XP($){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 f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:HP($),error:$.error}];default:return[]}}function HP($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function e3($){return{async*stream(f){let J=!1,W=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let Q=k4(f.messages),j=f.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of Z.createMessage(f.systemPrompt??"",Q,j))for(let H of XP(X)){if(H.type==="finish")J=!0;else if(H.type==="tool-call-delta")W=!0;yield H}if(!J)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function GP($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function PP($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{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 J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return GP(f)}function I9($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return BP[$.providerId]?.models??void 0}function UP($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function FP($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:UP(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function $j($,f,J){let W=$.providerConfig,Z=W?.providerId===$.providerId?W:void 0,Q={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:I9($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(VP(KP(Q.providerId)))return e3(()=>AP(Q));return YP({providerConfigs:[{providerId:Q.providerId,apiKey:Q.apiKey,baseUrl:Q.baseUrl,headers:Q.headers,options:PP(Q),models:Q.knownModels?Object.entries(Q.knownModels).map(([j,X])=>FP(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:Q.providerId,modelId:Q.modelId},{maxTokens:Q.maxOutputTokens})}import{normalizeUserInput as fj}from"@cline/shared";var RP=50000,DP=6000000,Jj=8000,LP=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),zP=new Set(["read","read_files"]),C1="[outdated - see the latest file content]",Wj="Tool execution was interrupted before a result was produced.",OP=($)=>`
123
+ `)}catch(K){if(clearTimeout(V),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(H.signal&&B)H.signal.removeEventListener("abort",B)}}}function wf($={}){return{readFile:G8($.fileRead),search:P8($.search),bash:V8($.bash),webFetch:U8($.webFetch),applyPatch:A8($.applyPatch),editor:B8($.editor)}}var oG={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"},Sf=[{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 n3($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((W)=>J.includes(W.toLowerCase()))}function eG($,f,J,W){if($.mode&&$.mode!=="any"&&$.mode!==W)return!1;return n3(f,$.providerIdIncludes)&&n3(J,$.modelIdIncludes)}function hf($,f,J,W){if(!W||W.length===0)return{};let Z=new Map;for(let j of W){if(!eG(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let Q={};for(let[j,X]of Z.entries())Q[oG[j]]=X;return Q}var I0={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 q$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function C4($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let W of n$)J[W]=f;return J}function E4($,f){let J=I0[$],{enableSpawnAgent:W,enableAgentTeams:Z,...Q}=J;return s$({...Q,...f})}import{createTool as $U,zodToJsonSchema as fU}from"@cline/shared";import{z as pW}from"zod";import{createAgentRuntime as pP}from"@cline/agents";import{createContributionRegistry as rP}from"@cline/shared";import{createGateway as YP,createHandlerAsync as AP,hasRegisteredHandler as VP,MODEL_COLLECTIONS_BY_PROVIDER_ID as BP,normalizeProviderId as KP}from"@cline/llms";import{EMPTY_CONTENT_TEXT as $P}from"@cline/shared";function fP($){let f=WP($.content),J=[],W=$.id??jP(),Z=0,Q=[],j=()=>{if(Q.length===0)return;let X=Z===0?W:`${W}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:Q.map(ZP),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:a3($.metrics)}),Q=[]};if(f.length===0)return J.push({id:W,role:$.role,content:[{type:"text",text:$P}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:a3($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){Q.push(X);continue}j(),J.push({id:`${W}_tool_${X.tool_use_id}`,role:"tool",content:[s3(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function b4($){return $.flatMap(fP)}function JP($){let f=$.content.map(o3).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:QP($.metrics)}}function Cf($){return $.map(JP)}function k4($){let f=[];for(let J of $){let W=J.content.map(o3).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,Q=f[f.length-1];if(Z==="user"&&W.length>0&&W.every((j)=>j.type==="tool_result")&&Q?.role==="user"&&Array.isArray(Q.content)&&Q.content.every((j)=>j.type==="tool_result")){Q.content.push(...W);continue}f.push({role:Z,content:W})}return f}function WP($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function ZP($){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 s3($)}}function s3($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function o3($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.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 f=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:f?.thoughtSignature??f?.signature}}case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function a3($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function QP($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var t3=0;function jP(){return t3+=1,`msg_${Date.now().toString(36)}_${t3.toString(36)}`}function XP($){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 f=$.tool_call.function,J=f.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??f.id,toolName:f.name,inputText:typeof J==="string"?J:void 0,input:typeof J==="string"?void 0:J,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:HP($),error:$.error}];default:return[]}}function HP($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function e3($){return{async*stream(f){let J=!1,W=!1;try{let Z=typeof $==="function"?await $():$;Z.setAbortSignal?.(f.signal);let Q=k4(f.messages),j=f.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of Z.createMessage(f.systemPrompt??"",Q,j))for(let H of XP(X)){if(H.type==="finish")J=!0;else if(H.type==="tool-call-delta")W=!0;yield H}if(!J)yield{type:"finish",reason:W?"tool-calls":"stop"}}catch(Z){if(!J)yield{type:"finish",reason:f.signal?.aborted?"aborted":"error",error:Z instanceof Error?Z.message:String(Z)}}}}}function GP($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function PP($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{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 J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return GP(f)}function IW($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return BP[$.providerId]?.models??void 0}function UP($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function FP($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:UP(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function $j($,f,J){let W=$.providerConfig,Z=W?.providerId===$.providerId?W:void 0,Q={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:IW($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};if(VP(KP(Q.providerId)))return e3(()=>AP(Q));return YP({providerConfigs:[{providerId:Q.providerId,apiKey:Q.apiKey,baseUrl:Q.baseUrl,headers:Q.headers,options:PP(Q),models:Q.knownModels?Object.entries(Q.knownModels).map(([j,X])=>FP(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:Q.providerId,modelId:Q.modelId},{maxTokens:Q.maxOutputTokens})}import{normalizeUserInput as fj}from"@cline/shared";var RP=50000,DP=6000000,Jj=8000,LP=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),zP=new Set(["read","read_files"]),C1="[outdated - see the latest file content]",Wj="Tool execution was interrupted before a result was produced.",OP=($)=>`
124
124
 
125
125
  ...[truncated ${$} chars]...
126
126
 
@@ -128,19 +128,19 @@ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for
128
128
 
129
129
  ...[truncated ${$} chars to fit provider request budget]...
130
130
 
131
- `;class m9{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=RP,f=LP,J=DP){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let j=fj(W.content);if(j!==W.content)return{...W,content:j}}return W}let Z=!1,Q=W.content.map((j)=>{let X=this.transformBlock(j,W.role);if(X!==j)Z=!0;return X});return Z?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=fj($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),W=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let Q=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===$.content?$:{...$,content:W}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let W=$[J];if(!Array.isArray(W.content))continue;for(let Z=0;Z<W.content.length;Z++){let Q=W.content[Z];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${Z}`);else if(Q.type==="tool_use"){let j=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(Q.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,X)}}else if(Q.type==="tool_result"){let j=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(j)||Q.is_error===!0)continue;let X=this.getReadLocators(Q);for(let H of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(H),Q.tool_use_id),this.isFullFileRead(H))this.latestFullContentOwnerByPathCache.set(H.path,Q.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],W=new Map,Z=!1,Q=()=>{if(W.size===0)return;j(this.createMissingToolResultMessage(W)),W.clear(),Z=!0},j=(X)=>{let H=J.at(-1);if(this.shouldMergeUserAfterToolResults(H,X)){J[J.length-1]={...H,content:[...H.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,W)),W.size>0)W.clear(),Z=!0;continue}if(Array.isArray(X.content)){let H=X.content.filter((A)=>A.type==="tool_result"),Y=X.content.filter((A)=>A.type!=="tool_result");if(H.length>0){let A=this.appendMissingToolResults({...X,role:"user",content:H},W);if(j(A),W.size>0)W.clear();Z=!0}if(Y.length>0||H.length===0){if(H.length===0)Q();let A=H.length>0?{...X,content:Y}:X;if(j(A),A.role==="assistant")this.trackMissingToolCalls(A,f,W)}continue}Q(),j(X)}return Q(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")f.add(W.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||f.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${Wj} Tool: ${$}.`:Wj}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 f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],W=this.extractLocatorFromReadRequest(f);if(W)J.push(W);if(Array.isArray(f.files))for(let Z of f.files){let Q=this.extractLocatorFromReadRequest(Z);if(Q)J.push(Q)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let W of $){let Z=this.extractLocatorFromResultEntry(W);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((Q)=>this.toReadLocatorKey(Q))),W=new Set(f.map((Q)=>Q.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??C1;let Z=0;for(let Q of $)if(Q.type==="text")Z+=this.countOutdatedImageEntries(Q.text,J);return $.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:C1}}if(Q.type==="image"){if(Z===0)return Q;return Z-=1,{type:"text",text:C1}}if(Q.type!=="text")return Q;let j=this.replaceOutdatedInString(Q.text,J);if(j===null)return{...Q,text:C1};return j===Q.text?Q:{...Q,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let W=Array.isArray(J)?J:[J],Z=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let j=Q,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let W=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(W)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let W={...$};if(typeof W.result==="string")W.result=C1;else if(typeof W.content==="string")W.content=C1;else W.result=C1;return W}isReadTool($){return!!$&&zP.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return x9($,this.maxToolResultChars,OP)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((Q)=>NP(Q))}}),W=this.collectTruncationCandidates(J);for(let Z of W){if(f<=this.maxTotalTextBytes)break;let Q=Z.byteLength;if(Q<=Jj)continue;let j=f-this.maxTotalTextBytes,X=Math.max(Jj,Q-j),H=TP(Z.get(),X,_P);Z.set(H),f-=Q-M0(H)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=M0(J.content);continue}for(let W of J.content)if(W.type==="text")f+=M0(W.text);else if(W.type==="thinking")f+=M0(W.thinking);else if(W.type==="file")f+=M0(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")f+=M0(W.content);else for(let Z of W.content)if(Z.type==="text")f+=M0(Z.text);else if(Z.type==="file")f+=M0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof W.content==="string"){f.push({byteLength:M0(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")f.push({byteLength:M0(Q.text),get:()=>Q.text,set:(j)=>{Q.text=j}});else if(Q.type==="file")f.push({byteLength:M0(Q.content),get:()=>Q.content,set:(j)=>{Q.content=j}})}}return f.sort((J,W)=>W.byteLength-J.byteLength)}}function M0($){return Buffer.byteLength($,"utf8")}function x9($,f,J){if($.length<=f)return $;let W=J($.length-f),Z=Math.max(0,Math.floor((f-W.length)/2)),Q=Math.max(0,$.length-Z*2),j=J(Q),X=Math.max(0,Math.floor((f-j.length)/2)),H=$.slice(0,X),Y=X>0?$.slice(-X):"";return`${H}${j}${Y}`}function TP($,f,J){if(M0($)<=f)return $;let W=0,Z=$.length,Q=x9($,0,J);while(W<=Z){let j=W+Z>>>1,X=x9($,j,J);if(M0(X)<=f)Q=X,W=j+1;else Z=j-1}return Q}function NP($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function g9(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class v9{messages=[];conversationId=g9();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=g9(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=g9(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function Zj($){let{agentConfig:f}=$,J=MP(f),W=yP(f),Z=$.hooks,Q=qP(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:Q,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function MP($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function yP($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function qP($){if($===void 0)return;return $>=2?"parallel":"sequential"}function wP(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function SP($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function u9($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(u9);let f={};for(let J of Object.keys($).sort())f[J]=u9($[J]);return f}function hP($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(u9($))}catch{return String($)}}function CP($,f,J,W){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var Qj={softThreshold:3,hardThreshold:5};class c9{config;state=wP();constructor($){this.config={softThreshold:$?.softThreshold??Qj.softThreshold,hardThreshold:$?.hardThreshold??Qj.hardThreshold}}inspect($){let f=hP($.input),J=CP(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){SP(this.state)}}class d9{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;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:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await bP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let Q=Z.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:EP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function EP($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let W=$.stopReason?.trim();if(W)f.push(`Decision: ${W}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function bP($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function kP($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function IP($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function xP($){return $.content.find((f)=>f.type==="tool-result")}function mP($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function gP($){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 l9{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 f=[],J=kP($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let W=IP($);if(W!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return f}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 f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let W=xP($.message),Z=W?.output,Q=gP(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:Q,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,X=($.totalCost??0)-Q;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={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:mP($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function iP($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function nP($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function aP($,f){let J=$.trim(),W=f.map((Z)=>Z.trim()).filter(Boolean).join(`
131
+ `;class mW{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=RP,f=LP,J=DP){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let j=fj(W.content);if(j!==W.content)return{...W,content:j}}return W}let Z=!1,Q=W.content.map((j)=>{let X=this.transformBlock(j,W.role);if(X!==j)Z=!0;return X});return Z?{...W,content:Q}:W});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=fj($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),W=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let Q=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(Q.length>0)W=this.replaceOutdatedReadContent(W,Q)}}if(this.shouldTruncateTool(J))W=this.truncateToolResultContent(W);return W===$.content?$:{...$,content:W}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let W=$[J];if(!Array.isArray(W.content))continue;for(let Z=0;Z<W.content.length;Z++){let Q=W.content[Z];if(Q.type==="file")this.latestFullContentOwnerByPathCache.set(Q.path,`file:${J}:${Z}`);else if(Q.type==="tool_use"){let j=Q.name.toLowerCase();if(this.toolNameByIdCache.set(Q.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(Q.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(Q.id,X)}}else if(Q.type==="tool_result"){let j=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.isReadTool(j)||Q.is_error===!0)continue;let X=this.getReadLocators(Q);for(let H of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(H),Q.tool_use_id),this.isFullFileRead(H))this.latestFullContentOwnerByPathCache.set(H.path,Q.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],W=new Map,Z=!1,Q=()=>{if(W.size===0)return;j(this.createMissingToolResultMessage(W)),W.clear(),Z=!0},j=(X)=>{let H=J.at(-1);if(this.shouldMergeUserAfterToolResults(H,X)){J[J.length-1]={...H,content:[...H.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,W)),W.size>0)W.clear(),Z=!0;continue}if(Array.isArray(X.content)){let H=X.content.filter((A)=>A.type==="tool_result"),Y=X.content.filter((A)=>A.type!=="tool_result");if(H.length>0){let A=this.appendMissingToolResults({...X,role:"user",content:H},W);if(j(A),W.size>0)W.clear();Z=!0}if(Y.length>0||H.length===0){if(H.length===0)Q();let A=H.length>0?{...X,content:Y}:X;if(j(A),A.role==="assistant")this.trackMissingToolCalls(A,f,W)}continue}Q(),j(X)}return Q(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content)if(W.type==="tool_result")f.add(W.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let W of $.content){if(W.type!=="tool_use"||f.has(W.id))continue;J.set(W.id,W.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${Wj} Tool: ${$}.`:Wj}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 f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],W=this.extractLocatorFromReadRequest(f);if(W)J.push(W);if(Array.isArray(f.files))for(let Z of f.files){let Q=this.extractLocatorFromReadRequest(Z);if(Q)J.push(Q)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let W of $){let Z=this.extractLocatorFromResultEntry(W);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((Q)=>this.toReadLocatorKey(Q))),W=new Set(f.map((Q)=>Q.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??C1;let Z=0;for(let Q of $)if(Q.type==="text")Z+=this.countOutdatedImageEntries(Q.text,J);return $.map((Q)=>{if(Q.type==="file"){if(!W.has(Q.path))return Q;return{...Q,content:C1}}if(Q.type==="image"){if(Z===0)return Q;return Z-=1,{type:"text",text:C1}}if(Q.type!=="text")return Q;let j=this.replaceOutdatedInString(Q.text,J);if(j===null)return{...Q,text:C1};return j===Q.text?Q:{...Q,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let W=Array.isArray(J)?J:[J],Z=0;for(let Q of W){if(!Q||typeof Q!=="object")continue;let j=Q,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let W=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(W)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let W={...$};if(typeof W.result==="string")W.result=C1;else if(typeof W.content==="string")W.content=C1;else W.result=C1;return W}isReadTool($){return!!$&&zP.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let W=this.truncateMiddle(f.content);return W===f.content?f:{...f,content:W}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return xW($,this.maxToolResultChars,OP)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((Q)=>NP(Q))}}),W=this.collectTruncationCandidates(J);for(let Z of W){if(f<=this.maxTotalTextBytes)break;let Q=Z.byteLength;if(Q<=Jj)continue;let j=f-this.maxTotalTextBytes,X=Math.max(Jj,Q-j),H=TP(Z.get(),X,_P);Z.set(H),f-=Q-M0(H)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=M0(J.content);continue}for(let W of J.content)if(W.type==="text")f+=M0(W.text);else if(W.type==="thinking")f+=M0(W.thinking);else if(W.type==="file")f+=M0(W.content);else if(W.type==="tool_result"){if(typeof W.content==="string")f+=M0(W.content);else for(let Z of W.content)if(Z.type==="text")f+=M0(Z.text);else if(Z.type==="file")f+=M0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let W of J.content){if(W.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(W.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof W.content==="string"){f.push({byteLength:M0(W.content),get:()=>W.content,set:(Q)=>{W.content=Q}});continue}for(let Q of W.content)if(Q.type==="text")f.push({byteLength:M0(Q.text),get:()=>Q.text,set:(j)=>{Q.text=j}});else if(Q.type==="file")f.push({byteLength:M0(Q.content),get:()=>Q.content,set:(j)=>{Q.content=j}})}}return f.sort((J,W)=>W.byteLength-J.byteLength)}}function M0($){return Buffer.byteLength($,"utf8")}function xW($,f,J){if($.length<=f)return $;let W=J($.length-f),Z=Math.max(0,Math.floor((f-W.length)/2)),Q=Math.max(0,$.length-Z*2),j=J(Q),X=Math.max(0,Math.floor((f-j.length)/2)),H=$.slice(0,X),Y=X>0?$.slice(-X):"";return`${H}${j}${Y}`}function TP($,f,J){if(M0($)<=f)return $;let W=0,Z=$.length,Q=xW($,0,J);while(W<=Z){let j=W+Z>>>1,X=xW($,j,J);if(M0(X)<=f)Q=X,W=j+1;else Z=j-1}return Q}function NP($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function gW(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class vW{messages=[];conversationId=gW();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=gW(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=gW(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function Zj($){let{agentConfig:f}=$,J=MP(f),W=yP(f),Z=$.hooks,Q=qP(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:W,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:Q,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function MP($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function yP($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function qP($){if($===void 0)return;return $>=2?"parallel":"sequential"}function wP(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function SP($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function uW($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(uW);let f={};for(let J of Object.keys($).sort())f[J]=uW($[J]);return f}function hP($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(uW($))}catch{return String($)}}function CP($,f,J,W){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===W.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=W.hardThreshold}}var Qj={softThreshold:3,hardThreshold:5};class cW{config;state=wP();constructor($){this.config={softThreshold:$?.softThreshold??Qj.softThreshold,hardThreshold:$?.hardThreshold??Qj.hardThreshold}}inspect($){let f=hP($.input),J=CP(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){SP(this.state)}}class dW{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;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:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await bP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let Q=Z.guidance?.trim();if(Q)this.options.appendRecoveryNotice(Q,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:Q}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:EP({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function EP($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let W=$.stopReason?.trim();if(W)f.push(`Decision: ${W}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function bP($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function kP($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function IP($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function xP($){return $.content.find((f)=>f.type==="tool-result")}function mP($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function gP($){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 lW{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 f=[],J=kP($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let W=IP($);if(W!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:W.reasoning});return f}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 f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let W=xP($.message),Z=W?.output,Q=gP(W);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:Q,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,W=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,Q=this.lastUsage.totalCost??0,X=($.totalCost??0)-Q;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:W===0?void 0:Math.max(0,W),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={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:mP($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function iP($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function nP($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function aP($,f){let J=$.trim(),W=f.map((Z)=>Z.trim()).filter(Boolean).join(`
132
132
 
133
133
  `);if(J&&W)return`${J}
134
134
 
135
- ${W}`;return J||W}function tP($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let W of f){let Z=await W.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let W of f)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,Z;for(let Q of f){let j=await Q.beforeModel?.({...J,request:W});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},W={...W,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...W.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let W of f){let Z=await W.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let W=J.input,Z;for(let Q of f){let j=await Q.beforeTool?.({...J,input:W});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))W=j.input}return Z},afterTool:async(J)=>{let W=J.result,Z;for(let Q of f){let j=await Q.afterTool?.({...J,result:W});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)W=j.result}return Z},onEvent:async(J)=>{for(let W of f)await W.onEvent?.(J)}}}class e${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new l9;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($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??pP,this.conversation=new v9($.initialMessages),this.messageBuilder=new m9,this.contributionRegistry=rP({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 J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new d9({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,j,X)=>sP(this.logger,Q,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let Z=W===!1||W===void 0?void 0:W;this.loopTracker=new c9(Z)}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 f=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of $)if(!f.has(W.name))J.push(W),f.add(W.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){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($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await nP(f);if(J)$.push(J)}return aP(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}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 f=new Date,J=$.userMessage;if(J!==void 0){let U=await eP(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),Z=$j(this.config,this.logger,this.telemetry),Q=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let U of Q)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let X=this.conversation.getConversationId(),H=Xj(this.config),Y=Array.from(j.values()),A=b4(this.conversation.getMessages()),V=Zj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[O3]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,Y),initialMessages:A,systemPrompt:W}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((U)=>{this.handleRuntimeEvent(U)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(U){R=U instanceof Error?U:Error(String(U))}finally{K();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(G&&G.messages.length>0){let U=Cf(G.messages);this.conversation.replaceMessages(U)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}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 $=tP([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let W=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(W);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let Z=Cf(W.messages),Q=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:Z,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!j)return;return{...j.messages?{messages:b4(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(k4($));return b4(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)f=await W.build(f);return this.messageBuilder.buildForApi(f)}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 f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,W=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((H)=>H.type==="tool-result"),Q=Z?.type==="tool-result"&&Z.isError===!0,j=Q?iP(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),Q){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>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 f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(Cf($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),W=Cf(f).filter((Z)=>!Z.id||!J.has(Z.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:f});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:J,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 f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:W,endedAt:Z}=$,Q=Z.getTime()-W.getTime(),j=J?"error":oP(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",H=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?Cf(f.messages):this.conversation.getMessages(),A=Xj(this.config);if(J)throw J;return{text:X,usage:H,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:A},startedAt:W,endedAt:Z,durationMs:Q}}}function sP($,f,J,W){if(!$)return;if(f==="debug"){$.debug(J,W);return}if(f==="error"&&$.error){$.error(J,W);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...W,severity:Z})}function oP($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function eP($,f,J,W){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => jj);return Z($,f,J,W)}function Xj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=I9($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as Hj}from"@cline/shared";function Yj($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return Hj({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
136
- ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function Aj($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return Hj({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function Ef($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function E1($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?Yj($.prompt,f):Aj($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function bf($){let f=E1($),J=new e$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var JU=p9.object({systemPrompt:p9.string().describe("System prompt defining the sub-agent's behavior"),task:p9.string().describe("Task for the sub-agent to complete")});function $1($){return $U({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:fU(JU),execute:async(f,J)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=bf({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),Q=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:Q,conversationId:j,parentAgentId:X,input:f})}catch{}try{let H=await Z.run(f.task),Y={text:H.text,iterations:H.iterations,finishReason:H.finishReason,usage:{inputTokens:H.usage.inputTokens,outputTokens:H.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:X,input:f,result:Y,agentResult:H})}catch{}return Y}catch(H){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:X,input:f,error:H instanceof Error?H:Error(String(H))})}catch{}throw H}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as WU,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as ZU,TEAM_RUN_TEXT_PREVIEW_LIMIT as QU,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as jU,TeamAttachOutcomeFragmentInputSchema as Vj,TeamAwaitRunsInputSchema as Bj,TeamBroadcastInputSchema as Kj,TeamBroadcastToolResultSchema as XU,TeamCancelRunInputSchema as Gj,TeamCancelRunToolResultSchema as HU,TeamCleanupInputSchema as Pj,TeamCleanupToolResultSchema as YU,TeamCreateOutcomeInputSchema as Uj,TeamCreateOutcomeToolResultSchema as AU,TeamFinalizeOutcomeInputSchema as Fj,TeamFinalizeOutcomeToolResultSchema as VU,TeamListOutcomesInputSchema as Rj,TeamListRunsInputSchema as Dj,TeamMailboxMessageToolResultSchema as BU,TeamMissionLogInputSchema as Lj,TeamMissionLogToolResultSchema as KU,TeamOutcomeFragmentToolResultSchema as zj,TeamOutcomeToolResultSchema as GU,TeamReadMailboxInputSchema as Oj,TeamReviewOutcomeFragmentInputSchema as _j,TeamRunTaskInputSchema as Tj,TeamRunTaskToolResultSchema as r9,TeamRunToolSummarySchema as i9,TeamSendMessageInputSchema as Nj,TeamSendMessageToolResultSchema as PU,TeamShutdownTeammateInputSchema as Mj,TeamSimpleAgentStatusToolResultSchema as yj,TeamSpawnTeammateInputSchema as qj,TeamStatusInputSchema as wj,TeamStatusToolResultSchema as UU,TeamTaskInputSchema as Sj,TeamTaskToolResultSchema as R8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function hj($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function b1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function FU($){let f=$.result;if(!f)return;return{textPreview:hj(f.text,QU),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function I4($){return $?.toISOString()}function n9($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:hj($.message,ZU),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:I4($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:I4($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:I4($.heartbeatAt),lastProgressAt:I4($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:FU($)}}function RU($){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 kf=["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 Cj($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...k1({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:E1({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function If($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,W=k1({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let Q of $.restoredTeammates??[]){if($.runtime.isTeammateActive(Q.agentId))continue;Cj({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Q}),Z.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:Z}}function k1($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(qj),execute:async(j)=>{let X=E(qj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let H={agentId:X.agentId,rolePrompt:X.rolePrompt};if(Cj({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:H}),!W)$.onLeadToolsUnlocked?.(k1({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(yj,{agentId:X.agentId,status:"spawned"})}}));if(!W)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(Mj),execute:async(j)=>{let X=E(Mj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),E(yj,{agentId:X.agentId,status:"stopped"})}})),Z.push(Q0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(wj),execute:async(j)=>{return E(wj,j),E(UU,$.runtime.getSnapshot())}})),Z.push(Q0({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:j0(Sj),execute:async(j)=>{let X=E(Sj,j);switch(X.action){case"create":{let H=new Set(jU.create??[]),Y=Object.entries(j).filter(([V,B])=>H.has(V)&&B!=null).map(([V])=>V),A=$.runtime.createTask({title:b1(X.title,"title"),description:b1(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return E(R8,{action:"create",taskId:A.id,status:A.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return E(R8,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let H=$.runtime.claimTask(b1(X.taskId,"taskId"),$.requesterId);return E(R8,{action:"claim",taskId:H.id,status:H.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 H=$.runtime.completeTask(b1(X.taskId,"taskId"),$.requesterId,b1(X.summary,"summary"));return E(R8,{action:"complete",taskId:H.id,status:H.status})}case"block":{let H=$.runtime.blockTask(b1(X.taskId,"taskId"),$.requesterId,b1(X.reason,"reason"));return E(R8,{action:"block",taskId:H.id,status:H.status})}}}}));let Q=new Map;return Z.push(Q0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(Tj),execute:async(j)=>{let X=E(Tj,j);if(X.runMode==="async"){let A=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return E(r9,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${A.id}.`,runId:A.id})}let H=Q.get(X.agentId);if(H){let A=await H;return E(r9,{...A,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((A)=>E(r9,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:A.text,iterations:A.iterations})).finally(()=>{Q.delete(X.agentId)});return Q.set(X.agentId,Y),await Y}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(Gj),execute:async(j)=>{let X=E(Gj,j),H=$.runtime.cancelRun(X.runId,X.reason);return E(HU,{runId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(Dj),execute:async(j)=>E(i9.array(),$.runtime.listRuns(E(Dj,j)).map(n9))})),Z.push(Q0({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:j0(Bj),timeoutMs:WU,execute:async(j)=>{let X=E(Bj,j);if(X.runId){let A=await $.runtime.awaitRun(X.runId);return RU(A),E(i9,n9(A))}let H=await $.runtime.awaitAllRuns(),Y=H.filter((A)=>["failed","cancelled","interrupted"].includes(A.status));if(Y.length>0){let A=Y.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${A}`)}return E(i9.array(),H.map(n9))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(Nj),execute:async(j)=>{let X=E(Nj,j),H=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return E(PU,{id:H.id,toAgentId:H.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(Kj),execute:async(j)=>{let X=E(Kj,j),H=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return E(XU,{delivered:H.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(Oj),execute:async(j)=>{let X=E(Oj,j);return E(BU.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(Lj),execute:async(j)=>{let X=E(Lj,j),H=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return E(KU,{id:H.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(Pj),execute:async(j)=>{if(E(Pj,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(YU,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(Uj),execute:async(j)=>{let X=E(Uj,j),H=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return E(AU,{outcomeId:H.id,status:H.status,requiredSections:H.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(Vj),execute:async(j)=>{let X=E(Vj,j),H=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return E(zj,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(_j),execute:async(j)=>{let X=E(_j,j),H=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return E(zj,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(Fj),execute:async(j)=>{let X=E(Fj,j),H=$.runtime.finalizeOutcome(X.outcomeId);return E(VU,{outcomeId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(Rj),execute:async(j)=>{return E(Rj,j),E(GU.array(),$.runtime.listOutcomes())}})),Z}function x4($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function Ej($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var DU=[{id:"read_files",description:"Read the full 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.",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:$1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...kf]}],LU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function zU($){return $==="plan"||$==="yolo"?$:"act"}function kj($){let f=zU($.mode),J=I0[q$({mode:f})],W=hf($.providerId??"",$.modelId??"",f,Sf);return{mode:f,flags:{...J,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function bj($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=kj(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=LU[$];return W?J[W]===!0:!1}function OU($,f){if($.id==="editor"){let{flags:J}=kj(f),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:bj($.id,f),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:bj($.id,f)}}function I1($={}){return DU.map((f)=>OU(f,$))}function m4($={}){return I1($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function g4($){if(!$.enabled)return new Set;let f=I1($.availabilityContext),J=new Set(f.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function D8($,f={}){return I1(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function v4($,f={}){return D8($,f)}function x1($={}){let{executorOptions:f={},executors:J,...W}=$,Z={...wf(f),...J??{}};return s$({...W,executors:Z})}import{mkdirSync as qU,writeFileSync as wU}from"node:fs";import{dirname as SU}from"node:path";import{normalizeUserInput as hU}from"@cline/shared";import{nanoid as CU}from"nanoid";var xj={};w(xj,{sanitizeSessionToken:()=>m1,parseTeamTaskSubSessionId:()=>mf,parseSubSessionId:()=>z8,makeTeamTaskSubSessionId:()=>L8,makeSubSessionId:()=>xf,deriveSubsessionStatus:()=>O8});import{nanoid as NU}from"nanoid";function m1($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function xf($,f){let J=m1($),W=m1(f),Z=`${J}__${W}`;return Z.length>180?Z.slice(0,180):Z}function L8($,f){let J=m1($),W=m1(f);return`${J}__teamtask__${W}__${NU(6)}`}function mf($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+12),Q=Z.lastIndexOf("__");if(Q<=0)return null;let j=Z.slice(0,Q),X=Z.slice(Q+2);if(!W||!j||!X)return null;return{rootSessionId:W,agentId:j,teamTaskId:X}}function z8($){if(mf($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+f.length);if(!W||!Z)return null;return{rootSessionId:W,agentId:Z}}function O8($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var vj={};w(vj,{isTerminalSessionStatus:()=>gj,isNonTerminalSessionStatus:()=>W0,SessionSource:()=>G0,SESSION_STATUSES:()=>_8,NON_TERMINAL_SESSION_STATUSES:()=>mj});import{SESSION_STATUS_VALUES as MU}from"@cline/shared";var _8=MU,mj=["idle","running","pending"];function gj($){return!mj.includes($)}function W0($){return!gj($)}var G0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var yU=a.enum(_8),y0=a.object({version:a.literal(1),session_id:a.string().min(1),source:a.string().min(1),pid:a.number().int(),started_at:a.string().min(1),ended_at:a.string().min(1).optional(),exit_code:a.number().int().nullable().optional(),status:yU,interactive:a.boolean(),provider:a.string().min(1),model:a.string().min(1),cwd:a.string().min(1),workspace_root:a.string().min(1),team_name:a.string().min(1).optional(),enable_tools:a.boolean(),enable_spawn:a.boolean(),enable_teams:a.boolean(),prompt:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional(),messages_path:a.string().min(1).optional()});function uj($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function t9($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let W=[],Z=new Set;for(let Q of J){if(Z.has(Q.name))continue;Z.add(Q.name),W.push(Q)}return W}function cj($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function w$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function a9($,f){let J={...$};J.id=w$(J.id)??CU();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:w$(W?.id)??w$(J.modelId)??w$(f?.id),provider:w$(W?.provider)??w$(J.providerId)??w$(f?.provider),family:w$(W?.family)??w$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function u4($){return $.map((f)=>a9(f))}function c4($,f,J=[]){let W=$.map((H,Y)=>{let A=J[Y],B=A?.role===H.role&&JSON.stringify(A.content)===JSON.stringify(H.content)?{...A,...H}:{...H};return a9(B)}),Z=J.length,Q=[];for(let H=Z;H<W.length;H+=1)if(W[H]?.role==="assistant")Q.push(H);if(Q.length===0){let H=[...W].reverse().findIndex((Y)=>Y.role==="assistant");if(H===-1)return W;Q.push(W.length-1-H)}let j=Q[Q.length-1],X=Q.some((H)=>W[H]?.metrics);for(let H of Q){let Y=W[H],A=Y.metrics;if(!A&&H===j&&!X){let V=f.usage;A={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[H]={...a9(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...A?{metrics:A}:{},ts:Y.ts??f.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 EU=120;function g1($){let f=$?.trim();return f?f.slice(0,EU):void 0}function s9($){let f=hU($??"").trim();if(!f)return;return g1(f.split(`
137
- `)[0]?.trim())}function f1($){if(!$)return;let f={...$},J=g1(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function N8($){let f=f1($.metadata)??{},J=$.title!==void 0?g1($.title):s9($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function o9($){let f=mf($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=z8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function e9($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:u4($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function dj($,f,J){qU(SU($),{recursive:!0}),wU($,`${JSON.stringify(e9({updatedAt:f,context:J,messages:[]}),null,2)}
138
- `,"utf8")}function lj($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.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:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function pj($,f,J){let W=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let Q=await f(Z);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}L0();var rj={};w(rj,{summarizeUsageFromMessages:()=>vf,sumUsageTotals:()=>M8,getCurrentContextSize:()=>$W,createInitialAccumulatedUsage:()=>B0,accumulateUsageTotals:()=>X0});function B0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function X0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function M8($){let f=B0();for(let J of $)f=X0(f,J);return f}function gf($){return typeof $==="number"&&Number.isFinite($)?$:0}function vf($){let f=B0();for(let J of $){let W=J.metrics;if(!W)continue;f=X0(f,{inputTokens:gf(W.inputTokens),outputTokens:gf(W.outputTokens),cacheReadTokens:gf(W.cacheReadTokens),cacheWriteTokens:gf(W.cacheWriteTokens),totalCost:gf(W.cost)})}return f}function $W($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let W=gf(J.metrics?.inputTokens);return W>0?W:void 0}return}function bU($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function fW($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function S$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,W=$.teamRole,Z="root";if(W==="teammate")Z="team_teammate";else if(W==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function kU($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function IU($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let W=J?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function JW($,f,J){let{sessionId:W,config:Z,liveSession:Q,emit:j}=$,X=Z.telemetry,H=Q?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,A=fW(f),V=S$({agentId:J?.agentId??A.agentId,conversationId:J?.conversationId??A.conversationId,parentAgentId:J?.parentAgentId??A.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??H?.getTeamId(),teamName:J?.teamName??H?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=bU(f.input);if(B)F4(X,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(U4(X,{ulid:W,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))R4(X,{ulid:W,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...V})}if(f.type==="notice"&&f.reason==="api_error")i2(X,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...V});if(f.type==="error")i2(X,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...V});if(f.type==="usage"&&Q?.turnUsageBaseline){let B=kU(f);if(Y){Q.turnPrimaryUsage=X0(Q.turnPrimaryUsage??B0(),B);let G=X0(Q.turnUsageBaseline,Q.turnPrimaryUsage);$.usageBySession.set(W,G),Nf(X,{ulid:W,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),G4(X,{ulid:W,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...V})}else{let G=IU({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:A}),R=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=R,R.set(G,X0(R.get(G)??B0(),B))}let K=X0(Q.turnPrimaryUsage??B0(),M8(Q.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,X0(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,K))}if(f.type==="iteration_end"&&Y)$.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:W,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:cj(f),ts:Date.now()}})}function J1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as FD}from"@cline/shared";function ij($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function xU($){let J=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function mU($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),ij(f)}async function d4(){let $=mU(),f=ij(await xU($));return{verifier:$,challenge:f}}function l4($){return $.endsWith("/")?$.slice(0,-1):$}function v1($,f){return new URL(f,`${l4($)}/`).toString()}function uf($,f={}){let J=$.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:f.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[W,Z]=J.split("#",2);return{code:W||void 0,state:Z||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:f.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function gU($){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 f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),Z=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=gU(Z);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function cf($){try{let f=JSON.parse($),J=f.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:Z}}catch{return{}}}function u1($,f){return Date.now()>=$.expires-f}async function df($){if(!$.onManualCodeInput){let Q=await $.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let f,J,W=$.onManualCodeInput().then((Q)=>{f=Q,$.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return uf(f,$.parseOptions);if(await W,J)throw J;if(f)return uf(f,$.parseOptions);return{}}X$();import{existsSync as W6,readFileSync as kF,statSync as IF}from"node:fs";import{basename as xF,dirname as f6,join as Z6,resolve as J6}from"node:path";import{discoverPluginModulePaths as mF,resolveConfiguredPluginModulePaths as _X,resolvePluginConfigSearchPaths as gF,SKILLS_CONFIG_DIRECTORY_NAME as vF}from"@cline/shared/storage";import{resolve as GF}from"node:path";import{normalizePluginManifest as PF}from"@cline/shared";import{existsSync as P0,readFileSync as rf}from"node:fs";import{builtinModules as aU,createRequire as XW}from"node:module";import{dirname as W1,extname as S8,isAbsolute as tU,resolve as c}from"node:path";import{fileURLToPath as ZX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as sU}from"@cline/shared";var QX=W1(ZX(import.meta.url)),oU=XW(import.meta.url),eU=c(QX,"..","..","..","..",".."),ZW=JF(eU),$F=["@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"],HW=new Set(aU.flatMap(($)=>[$,$.replace(/^node:/,"")])),w8=new Set(sU),fF=["development","node","import","require","default"];function JF($){let f={},J={"@cline/sdk":c($,"packages/sdk/src/index.ts"),"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[W,Z]of Object.entries(J))if(P0(Z))f[W]=Z;for(let W of["agents","core","llms","shared"]){let Z=c($,"packages",W),Q=c(Z,"package.json");if(!P0(Q))continue;try{let j=JSON.parse(rf(Q,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=c(Z,j.exports);if(P0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,H]of Object.entries(j.exports)){let Y=WF(Z,H);if(!Y)continue;let A=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[A]=Y}}catch{}}return f}function WF($,f){let J=YW(f);if(!J)return null;let W=jX($,J);for(let Z of W)if(P0(Z))return Z;return null}function YW($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let W of fF){let Z=YW(J[W],f);if(Z)return Z}return null}function jX($,f){let J=f.replace(/^\.\//,""),W=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...W]}return W}function ZF($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function s4($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function pf($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function QF($){let f=pf($);if($===f)return".";return`.${$.slice(f.length)}`}function XX($){return pf($).startsWith("@cline/")}function QW($,f){let J=pf(f),W=W1($);while(!0){let Z=c(W,"node_modules",J);if(P0(Z)||P0(c(Z,"package.json")))return!0;let Q=c(W,"..");if(Q===W)return!1;W=Q}}function WX($){return jW($)!==null}function jW($){try{return oU.resolve($)}catch{}return jF($)}function jF($){let f=pf($),J=HX(f);if(!J)return null;let W=c(J,"package.json");try{let Z=JSON.parse(rf(W,"utf8")),Q=QF($),j=Q==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,Q)?Z.exports[Q]:void 0,X=YW(j)??(Q==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let H=c(J,X),Y=[H,...jX(J,X).filter((A)=>A!==H)];for(let A of Y)if(P0(A))return A;return null}catch{return null}}function XF(){let $=[QX],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(W1(W1(f)));let J=process.execPath?.trim();if(J)$.push(W1(J));return[...new Set($.map((W)=>c(W)))]}function HF($,f){let J=$;while(!0){let W=c(J,"package.json");if(P0(W))try{if(JSON.parse(rf(W,"utf8")).name===f)return J}catch{}let Z=c(J,"node_modules",f,"package.json");if(P0(Z))return W1(Z);let Q=c(J,"..");if(Q===J)return null;J=Q}}function HX($){for(let f of XF()){let J=HF(f,$);if(J)return J}return null}function YF($){let J=W1($);for(let W=0;W<4;W++){let Z=c(J,"package.json");if(P0(Z))try{let j=JSON.parse(rf(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let Q=c(J,"..");if(Q===J)return!1;J=Q}return!1}function YX($,f){let J=f.startsWith("file:")?ZX(f):tU(f)?f:c(W1($),f);if(P0(J)&&w8.has(S8(J)))return J;for(let W of w8){let Z=`${J}${W}`;if(P0(Z))return Z}for(let W of w8){let Z=c(J,`index${W}`);if(P0(Z))return Z}return null}function AX($){let f=new Set,J=[/\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 J)for(let Z of $.matchAll(W)){let Q=Z[1];if(Q)f.add(Q)}return[...f]}function AF($){return S8($)!==".ts"}function VX($,f,J=new Set){if(J.has($)||!P0($))return;if(J.add($),!w8.has(S8($)))return;let W=rf($,"utf8"),Z=AF($);for(let Q of AX(W)){if(Q.startsWith("node:")||HW.has(Q))continue;if(s4(Q)){if(!Z)continue;if(Object.hasOwn(ZW,Q)||Object.hasOwn(ZW,pf(Q))||QW($,Q)||XX(Q)&&WX(Q)||f&&WX(Q))continue;throw Error(`Cannot find module '${pf(Q)}'`)}let j=YX($,Q);if(j)VX(j,f,J)}}function BX($,f=new Set,J=new Set){if(f.has($)||!P0($))return J;if(f.add($),!w8.has(S8($)))return J;let W=rf($,"utf8");for(let Z of AX(W)){if(J.add(Z),s4(Z))continue;let Q=YX($,Z);if(Q)BX(Q,f,J)}return J}function VF($,f){let J=XW($),W={},Z=BX($),Q=new Set($F);for(let[j,X]of Object.entries(ZW)){try{J.resolve(j);continue}catch{}W[j]=X}for(let j of Z)if(s4(j)&&(XX(j)||f))Q.add(j);for(let j of Q){if(Object.hasOwn(W,j)||QW($,j))continue;let X=jW(j);if(X)W[j]=X}if(!f)return W;for(let j of Z){if(!s4(j)||Object.hasOwn(W,j)||QW($,j)||j.startsWith("node:")||HW.has(j))continue;let X=jW(j);if(X)W[j]=X}return W}function BF($){let f=S8($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var d1;function KF(){if(d1!==void 0)return d1;let $=HX("jiti");if(!$)return d1=null,null;let f=c($,"dist","babel.cjs");if(!P0(f))return d1=null,null;try{let W=XW(f)(f);d1=typeof W==="function"?W:null}catch{d1=null}return d1}async function KX($,f={}){let J=!YF($);VX($,J);let W=VF($,J),Z=ZF(W),Q=await import("jiti"),j=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,V])=>BF(V)).map(([V])=>V),H=KF(),Y=H?(V)=>H({...V,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...HW],transformModules:X,tryNative:!1,...Y?{transform:Y}:{}}).import($,{})}function GX($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function PX($){return typeof $==="object"&&$!==null}function AW($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function UF($,f){if(!PX($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!AW($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!AW($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!AW($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function FF($,f){if(!PX($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);UF($,f)}async function h8($,f={}){let J=GF(f.cwd??process.cwd(),$),W=await KX(J,{useCache:f.useCache}),Z=f.exportName??"plugin",Q=W.default??W[Z];FF(Q,J);let j=Q,X=j.setup,H=X?(Y,A)=>{let V={...f.session,...A.session},B={...A,session:Object.keys(V).length>0?V:void 0,client:f.client??A.client,user:f.user??A.user,workspaceInfo:f.workspaceInfo??A.workspaceInfo,automation:f.automation??A.automation,logger:f.logger??A.logger,telemetry:f.telemetry??A.telemetry};return X(Y,B)}:void 0;return{...j,manifest:PF(j.manifest),setup:H}}async function o4($,f={}){return(await l1($,f)).plugins}async function l1($,f={}){let J=[],W=[],Z=new Map,Q=0;for(let X of $)try{let H=await h8(X,f);if(!GX(H.manifest,f))continue;let Y=Z.get(H.name);if(Y)W.push({type:"duplicate_plugin_override",pluginName:H.name,pluginPath:X,overriddenPluginPath:Y.pluginPath,message:`Plugin "${H.name}" from ${X} overrides ${Y.pluginPath}`});Z.set(H.name,{plugin:H,pluginPath:X,order:Q++})}catch(H){let Y=H instanceof Error?H.message:String(H);J.push({pluginPath:X,phase:"load",message:Y,stack:H instanceof Error?H.stack:void 0})}let j=[...Z.values()].sort((X,H)=>X.order-H.order);return{plugins:j.map((X)=>X.plugin),pluginPaths:j.map((X)=>X.pluginPath),failures:J,warnings:W}}import{existsSync as GW}from"node:fs";import{createRequire as OX}from"node:module";import{dirname as e4,join as af}from"node:path";import{fileURLToPath as OF}from"node:url";var LX={};w(LX,{resolveSubprocessRuntimeExecutable:()=>VW,buildSubprocessSandboxCommand:()=>DX,SubprocessSandbox:()=>nf,CLINE_JS_RUNTIME_PATH_ENV:()=>RX});import{spawn as RF}from"node:child_process";import{basename as DF}from"node:path";import{augmentNodeCommandForDebug as LF,withResolvedClineBuildEnv as zF}from"@cline/shared";function UX($){if($ instanceof Error)return $;return Error(String($))}var RX="CLINE_JS_RUNTIME_PATH";function FX($){let f=$?.trim();if(!f)return!1;let J=DF(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function VW($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[RX]?.trim();if(J)return J;let W=$.execPath?.trim()||process.execPath;if(FX(W))return W;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let Q=Z?.trim();if(Q&&FX(Q))return Q}return"node"}function DX($,f={}){let J=VW({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return LF([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class nf{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=DX($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=RF(f[0]??VW(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:zF(process.env)});this.process=J;let W="",Z=(Q)=>{let j=W+Q;W=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{Z(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${UX(Q).message}`))}),J.on("exit",(Q,j)=>{this.process=null;let X=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,Q={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let H={resolve:(Y)=>j(Y),reject:X};if((J.timeoutMs??0)>0)H.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,H),W.send(Q,(Y)=>{if(!Y)return;let A=this.clearPendingRequest(Z);if(!A)return;A.reject(Error(`${this.processLabel} failed to send call "${$}": ${UX(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),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 f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function _F($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function C8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function TF(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function NF(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=OX($).resolve(`${TF()}/package.json`),W=af(e4(J),"extensions","plugin-sandbox-bootstrap.js");return GW(W)?W:void 0}catch{return}}function MF(){let $=process.execPath?.trim();if(!$)return;let f=af(e4(e4($)),"extensions","plugin-sandbox-bootstrap.js");return GW(f)?f:void 0}function yF(){let $=e4(OF(import.meta.url)),f=OX(import.meta.url),J=[af($,"plugin-sandbox-bootstrap.js"),af($,"extensions","plugin-sandbox-bootstrap.js"),af($,"agents","plugin-sandbox-bootstrap.js"),NF(),MF()];for(let Q of J.filter((j)=>typeof j==="string"))if(GW(Q))return{file:Q};let W=af($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`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(`
139
- `)}}var BW=yF();function KW($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let W=process.env[J];if(W){let Z=Number(W);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function $6($){let f=new nf({name:"plugin-sandbox",..."file"in BW?{bootstrapFile:BW.file}:{bootstrapScript:BW.script},onEvent:$.onEvent}),J=KW($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=KW($.hookTimeoutMs,3000),Z=KW($.contributionTimeoutMs,60000),Q={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",Q,{timeoutMs:J}).finally(()=>{j=void 0}),j},H;try{H=await f.call("initialize",Q,{timeoutMs:J})}catch(V){throw await f.shutdown().catch(()=>{}),V}let Y=H.plugins.map(_F);return{extensions:Y.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{qF(K,f,V,Z,X),wF(K,f,V,Z,X),SF(K,f,V,Z,X),CF(K,f,V,Z,X),hF(K,V)}};return B.hooks=bF(f,V,W,X),B}),failures:H.failures,pluginPaths:Y.map((V)=>V.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:H.warnings}}function qF($,f,J,W,Z){for(let Q of J.contributions?.tools??[]){let j={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(X,H)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:X,context:H},{timeoutMs:W})}catch(Y){if(!C8(Y))throw Y;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:X,context:H},{timeoutMs:W})}}};$.registerTool(j)}}function wF($,f,J,W,Z){for(let Q of J.contributions?.commands??[])$.registerCommand({name:Q.name,description:Q.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}catch(X){if(!C8(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}}})}function SF($,f,J,W,Z){for(let Q of J.contributions?.rules??[])$.registerRule({id:Q.ruleId,source:Q.source,content:Q.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}catch(j){if(!C8(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}}:Q.content??""})}function hF($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function CF($,f,J,W,Z){for(let Q of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:Q.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return zX(X)?X:j}catch(X){if(!C8(X))throw X;await Z();let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return zX(H)?H:j}}})}function zX($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function EF($,f,J,W,Z){return async(Q)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}catch(j){if(!C8(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}}}function bF($,f,J,W){let Z={};for(let Q of f.hooks??[])Z[Q]=EF($,f.pluginId,Q,J,W);return Object.keys(Z).length>0?Z:void 0}var UW="package.json",uF="package";function E8($){return gF($)}function b8($){return mF($)}function cF($){try{return W6($)&&IF($).isDirectory()}catch{return!1}}function FW($){let f=[],J=new Set;for(let W of $){let Z=J6(W);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function TX($){let f=FW($);return a4(f)}function NX($){return E8($).flatMap((f)=>b8(f)).filter((f)=>W6(f))}function dF($,f){let J=[];for(let W of $)try{J.push(..._X([W],f))}catch{}return J}function PW($){return typeof $==="object"&&$!==null}function lF($){try{let f=JSON.parse(kF(Z6($,UW),"utf8"));if(!PW(f)||!PW(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let W=[];for(let Z of J){if(typeof Z==="string"){W.push(Z);continue}if(!PW(Z)||!Array.isArray(Z.paths))continue;for(let Q of Z.paths)if(typeof Q==="string")W.push(Q)}return W}catch{return[]}}function MX($,f){let J=J6(f);return lF($).some((W)=>J6($,W)===J)}function pF($,f){return xF($)===uF&&W6(Z6(f6($),UW))&&MX(f6($),f)}function rF($){let f=J6($),J=[],W=f6(f);while(!0){if(pF(W,f)){J.push(W);break}if(W6(Z6(W,UW))){if(MX(W,f))J.push(W);break}let Z=f6(W);if(Z===W)break;W=Z}return FW(J)}function p1($={}){let f=$.cwd??process.cwd(),J=NX($.workspacePath),W=_X($.pluginPaths??[],f);return TX([...W,...J])}function iF($={}){let f=$.cwd??process.cwd(),J=NX($.workspacePath),W=dF($.pluginPaths??[],f);return TX([...W,...J])}function r1($){let f=[];for(let J of $)for(let W of rF(J)){let Z=Z6(W,vF);if(cF(Z))f.push(Z)}return FW(f)}function yX($={}){return r1(iF($))}async function tf($={}){let f=p1($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await l1(f,{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 J=await $6({pluginPaths:f,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:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as nF}from"node:child_process";import{promisify as aF}from"node:util";var tF=aF(nF);function RW($,f){$?.log(f,{severity:"warn"})}function sF($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,Z=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:Z}}async function i1($,f){let J=await tF("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function DW($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:W}=await i1($,["for-each-ref","--format=%(refname)",J]),Z=W.trim().split(`
140
- `).filter(Boolean);await Promise.allSettled(Z.map((Q)=>i1($,["update-ref","-d",Q])))}catch{}}async function qX($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((W)=>i1($,["update-ref",`refs/cline/checkpoints/${f}/${W.runCount}`,W.ref])))}function oF($,f){let J=$.findIndex((W)=>W.runCount===f.runCount);if(J<0)return[...$,f];return $.map((W,Z)=>Z===J?f:W)}function wX($){let f=$.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await i1($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await W())return;let Q=async(Y)=>{try{let V=(await i1($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(A){RW($.logger,`${Y}: ${A instanceof Error?A.message:String(A)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await i1($.cwd,["stash","create",j])).stdout.trim()}catch(Y){return RW($.logger,`Checkpoint snapshot failed: ${Y instanceof Error?Y.message:String(Y)}`),Q("Checkpoint HEAD fallback failed")}if(!X)return Q("Checkpoint HEAD fallback failed");let H=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await i1($.cwd,["update-ref",H,X])}catch(Y){RW($.logger,`Checkpoint store failed: ${Y instanceof Error?Y.message:String(Y)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),H=sF(X);if(H?.latest.ref===j.ref)return;let Y=oF(H?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:Y}});return}}}import{spawn as XR}from"node:child_process";import{appendFileSync as HR,readFileSync as YR}from"node:fs";import{join as AR}from"node:path";import{augmentNodeCommandForDebug as CX,withResolvedClineBuildEnv as OW}from"@cline/shared";import{ensureHookLogDir as SX}from"@cline/shared/storage";function sf($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as eF,readdirSync as $R}from"node:fs";import{basename as fR,extname as JR,join as WR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as Q6,resolveHooksConfigSearchPaths as ZR}from"@cline/shared/storage";function k8($){return ZR($)}var of;((A)=>{A.TaskStart="TaskStart";A.TaskResume="TaskResume";A.TaskCancel="TaskCancel";A.TaskComplete="TaskComplete";A.TaskError="TaskError";A.PreToolUse="PreToolUse";A.PostToolUse="PostToolUse";A.UserPromptSubmit="UserPromptSubmit";A.PreCompact="PreCompact";A.SessionShutdown="SessionShutdown"})(of||={});var I8={["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"},QR=new Map(Object.values(of).map(($)=>[$.toLowerCase(),$])),jR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function x8($){let f=JR($).toLowerCase();if(!jR.has(f))return;let J=fR($,f).trim().toLowerCase();return QR.get(J)}function Z1($){let f=[],J=new Set,W=k8($).filter((Z)=>eF(Z));for(let Z of W)try{for(let Q of $R(Z,{withFileTypes:!0})){if(!Q.isFile())continue;let j=x8(Q.name);if(!j)continue;let X=WR(Z,Q.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:I8[j],path:X})}}catch{}return f.sort((Z,Q)=>Z.path.localeCompare(Q.path))}function X6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))f[J]=typeof W==="string"?W:JSON.stringify(W);return f}function j6($,f,J){let W=J instanceof Error?`: ${J.message}`:"",Z=`${f}${W}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function VR($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
141
- `),W=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function BR($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function LW($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function U0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function KR($){let f=$.trim();if(!f)return{};let W=f.split(`
142
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function GR($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,Z)=>{let Q=!1,j=()=>{J.off("error",H),J.off("finish",Y),$.off("close",A)},X=(V)=>{if(Q)return;if(Q=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}Z(V);return}W()},H=(V)=>X(V),Y=()=>X(),A=()=>X();J.on("error",H),J.once("finish",Y),$.once("close",A);try{J.end(f)}catch(V){X(V)}})}async function EX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await hX($,f)}catch(J){let W=FR(f.command,process.platform,J);if(!W)throw J;return await hX($,{...f,command:W})}}async function hX($,f){let J=CX(f.command,{env:f.env,debugRole:"hook"}),W=XR(J[0],J.slice(1),{cwd:f.cwd,env:OW(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,K)=>{W.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,Q]),await GR(W,j),f.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let X="",H="",Y=!1,A;W.stdout.on("data",(B)=>{X+=B.toString()}),W.stderr.on("data",(B)=>{H+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,W.kill("SIGKILL")},f.timeoutMs);W.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=KR(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,Q])}function PR($){try{let J=YR($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let Z=W.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function UR($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function FR($,f=process.platform,J){if(f!=="win32"||!UR(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function bX($){if($.length===0)return;let[f,...J]=$,W=f.replace(/\\/g,"/").toLowerCase(),Z=W.split("/").at(-1)??W;if(Z==="env")return bX(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function RR($){let f=PR($);if(f&&f.length>0)return[...bX(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return CX(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function DR($){let f={};for(let J of Z1($)){if(!J.hookEventName)continue;let W=J.hookEventName,Z=f[W]??[];Z.push(RR(J.path)),f[W]=Z}return f}async function LR($){let f;for(let J of $.commands){let W=J.join(" ");try{let Z=await EX($.payload,{command:J,cwd:$.cwd,env:OW(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){j6($.logger,`hook command timed out: ${W}`);continue}if(Z?.parseError){j6($.logger,`hook command returned invalid JSON control output: ${W} (${Z.parseError})`);continue}f=VR(f,BR(Z?.parsedJson))}catch(Z){j6($.logger,`hook command failed: ${W}`,Z)}}return f}function n1($){for(let f of $.commands){let J=f.join(" ");EX($.payload,{command:f,cwd:$.cwd,env:OW(process.env),detached:!0}).catch((W)=>{j6($.logger,`hook command failed: ${J}`,W)})}}function Q1($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function zW($,f){return{...Q1($.snapshot),userMessage:f}}function kX($){return{...Q1($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function IX($){return{...Q1($.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 xX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function zR($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function ef($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(W)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...W})}
143
- `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??AR(SX(),"hooks.jsonl");SX(j),HR(j,Z,"utf8")};return{beforeRun:async(W)=>{let Z=zW(W,"");J({...U0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let Z=kX(W);J({...U0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:X6(Z.call.input)}});return},afterTool:async(W)=>{let Z=IX(W);J({...U0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:X6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:W,result:Z})=>{let Q=Q1(W);if(Z.status==="completed"){J({...U0(Q,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||LW(Z.error?.message)){J({...U0(Q,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...U0(Q,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let Z=zW({snapshot:W.snapshot},xX(W.message.content));J({...U0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function m8($){let f=DR($.workspacePath);if(!Object.values(f).some((V)=>V.length>0))return;let W=async(V,B)=>{let K=f[B]??[];if(K.length===0)return;n1({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...U0(V,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(V,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=f.prompt_submit??[];if(B.length>0)n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},Q=async(V)=>{let B=f.tool_call??[];if(B.length===0)return;return LR({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(V,$),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:X6(V.call.input)}}})},j=async(V)=>{let B=f.tool_result??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:X6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},X=async(V)=>{let B=f.agent_end??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},H=async(V)=>{let B=f.agent_error??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},Y=async(V)=>{if(LW(V.reason)){let K=f.agent_abort??[];if(K.length>0)n1({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"session_shutdown",reason:V.reason}})},A={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)A.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(Q1(V.snapshot),B);return};if((f.prompt_submit?.length??0)>0)A.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(zW({snapshot:V.snapshot},xX(V.message.content)))}}if((f.tool_call?.length??0)>0)A.beforeTool=async(V)=>{let B=await Q(kX(V));return zR(B)};if((f.tool_result?.length??0)>0)A.afterTool=async(V)=>{await j(IX(V));return};if((f.agent_end?.length??0)>0)A.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await X({...Q1(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let V=A.afterRun;A.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||LW(G.error?.message)){await Y({...Q1(K),reason:G.error?.message});return}if(G.error)await H({...Q1(K),iteration:G.iterations,error:G.error})}}return A}function $2($){return sf("core.hook_config_files",m8($))}function a1($,f){let J=$.map((W)=>W[f]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let Z;for(let Q of J){let j=await Q(W);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function t1($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:a1(f,"beforeRun"),afterRun:a1(f,"afterRun"),beforeModel:a1(f,"beforeModel"),afterModel:a1(f,"afterModel"),beforeTool:a1(f,"beforeTool"),afterTool:a1(f,"afterTool"),onEvent:a1(f,"onEvent")}}var mX={};w(mX,{normalizeRuntimeCapabilities:()=>F0});function F0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let W=f&&Object.keys(f).length>0;if(!W&&!J)return;return{...W?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var YH={};w(YH,{toProviderConfig:()=>m0,emptyStoredProviderSettings:()=>Y1,StoredProviderSettingsSchema:()=>Z2,StoredProviderSettingsEntrySchema:()=>b6,ProviderSettingsSchemaTyped:()=>i8});import{z as H1}from"zod";var HH={};w(HH,{toProviderConfig:()=>m0,safeParseSettings:()=>E6,safeCreateProviderConfig:()=>IW,parseSettings:()=>C6,normalizeProviderId:()=>W2,isBuiltInProviderId:()=>bW,createProviderConfig:()=>kW,SapSettingsSchema:()=>w6,ReasoningSettingsSchema:()=>N6,ProviderSettingsSchema:()=>X1,ProviderProtocolSchema:()=>O6,ProviderIdSchema:()=>r8,ProviderClientSchema:()=>_6,OcaSettingsSchema:()=>S6,ModelCatalogSettingsSchema:()=>h6,GcpSettingsSchema:()=>y6,BUILT_IN_PROVIDER_IDS:()=>EW,BUILT_IN_PROVIDER:()=>p8,AzureSettingsSchema:()=>q6,AwsSettingsSchema:()=>M6,AuthSettingsSchema:()=>T6});import*as x0 from"@cline/llms";import{z as y}from"zod";L0();var $H={};w($H,{refreshOcaToken:()=>v8,loginOcaOAuth:()=>f2,getValidOcaCredentials:()=>u8,generateOcaOpcRequestId:()=>V6,createOcaRequestHeaders:()=>MW,createOcaOAuthProvider:()=>NW,OCI_HEADER_OPC_REQUEST_ID:()=>iX,DEFAULT_INTERNAL_OCA_BASE_URL:()=>H6,DEFAULT_INTERNAL_IDCS_URL:()=>cX,DEFAULT_INTERNAL_IDCS_SCOPES:()=>dX,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>uX,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>Y6,DEFAULT_EXTERNAL_IDCS_URL:()=>pX,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>rX,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>lX});import{nanoid as vX}from"nanoid";class _W{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+W})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var gX={};w(gX,{startLocalOAuthServer:()=>e0});function OR(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function e0($){let f=await import("node:http"),J=$.host??"127.0.0.1",W=$.timeoutMs??300000,Z=$.successHtml??_R,Q=OR(),j=!1,X=null,H=null,Y=null,A=(K)=>{if(j)return;j=!0,Q.resolve(K)},V=()=>{if(X)clearTimeout(X),X=null;let K=Y;if(Y=null,H)H.close(),H=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{V(),A(null)},W),Q.promise};for(let K of $.ports){let G=f.createServer((P,U)=>{try{let F=new URL(P.url||"",`http://${J}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let O={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(O.error){U.statusCode=400,U.end(`Authentication failed: ${O.error}`),V(),A(O);return}if(!O.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(Z),V(),A(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((P)=>{let U=(F)=>{G.off("error",U),P({bound:!1,error:F})};G.once("error",U),G.listen(K,J,()=>{G.off("error",U),H=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){Y=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{V(),A(null)},close:()=>{V(),A(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var _R=`<!DOCTYPE html>
135
+ ${W}`;return J||W}function tP($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let W of f){let Z=await W.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let W of f)await W.afterRun?.(J)},beforeModel:async(J)=>{let W=J.request,Z;for(let Q of f){let j=await Q.beforeModel?.({...J,request:W});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},W={...W,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...W.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let W of f){let Z=await W.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let W=J.input,Z;for(let Q of f){let j=await Q.beforeTool?.({...J,input:W});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))W=j.input}return Z},afterTool:async(J)=>{let W=J.result,Z;for(let Q of f){let j=await Q.afterTool?.({...J,result:W});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)W=j.result}return Z},onEvent:async(J)=>{for(let W of f)await W.onEvent?.(J)}}}class e${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new lW;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($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??pP,this.conversation=new vW($.initialMessages),this.messageBuilder=new mW,this.contributionRegistry=rP({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 J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new dW({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(Q)=>this.emitLegacyEvent(Q),log:(Q,j,X)=>sP(this.logger,Q,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(Q,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q}]})}});let W=$.execution?.loopDetection;this.loopDetectionDisabled=W===!1;let Z=W===!1||W===void 0?void 0:W;this.loopTracker=new cW(Z)}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 f=new Set(this.config.tools.map((W)=>W.name)),J=[...this.config.tools];for(let W of $)if(!f.has(W.name))J.push(W),f.add(W.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){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($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await nP(f);if(J)$.push(J)}return aP(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}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 f=new Date,J=$.userMessage;if(J!==void 0){let U=await eP(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:U})}let W=await this.composeSystemPrompt(),Z=$j(this.config,this.logger,this.telemetry),Q=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let U of Q)j.set(U.name,U);for(let U of this.config.tools)j.set(U.name,U);let X=this.conversation.getConversationId(),H=Xj(this.config),Y=Array.from(j.values()),A=b4(this.conversation.getMessages()),V=Zj({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[O3]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,Y),initialMessages:A,systemPrompt:W}),B=this.createAgentRuntimeImpl(V);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((U)=>{this.handleRuntimeEvent(U)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(U){R=U instanceof Error?U:Error(String(U))}finally{K();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(G&&G.messages.length>0){let U=Cf(G.messages);this.conversation.replaceMessages(U)}let P=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:P})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}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 $=tP([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let W=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(W);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(W)=>{let Z=Cf(W.messages),Q=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:W.agentId,conversationId:W.conversationId??this.conversation.getConversationId(),parentAgentId:W.parentAgentId??null,iteration:W.iteration,messages:Z,apiMessages:Q,abortSignal:W.signal??new AbortController().signal,systemPrompt:W.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:W.emitStatusNotice});if(!j)return;return{...j.messages?{messages:b4(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(k4($));return b4(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let W of J)f=await W.build(f);return this.messageBuilder.buildForApi(f)}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 f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,W=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((H)=>H.type==="tool-result"),Q=Z?.type==="tool-result"&&Z.isError===!0,j=Q?iP(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:W,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),Q){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let W=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${W?`: ${W}`:""}`})}else if(J>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 f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(Cf($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),W=Cf(f).filter((Z)=>!Z.id||!J.has(Z.id));if(W.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...W])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let W=this.loopTracker.inspect({name:$,input:f});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:J,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 f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:W,endedAt:Z}=$,Q=Z.getTime()-W.getTime(),j=J?"error":oP(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",H=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?Cf(f.messages):this.conversation.getMessages(),A=Xj(this.config);if(J)throw J;return{text:X,usage:H,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:A},startedAt:W,endedAt:Z,durationMs:Q}}}function sP($,f,J,W){if(!$)return;if(f==="debug"){$.debug(J,W);return}if(f==="error"&&$.error){$.error(J,W);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...W,severity:Z})}function oP($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function eP($,f,J,W){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => jj);return Z($,f,J,W)}function Xj($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=IW($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as Hj}from"@cline/shared";function Yj($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return Hj({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
136
+ ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function Aj($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return Hj({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function Ef($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function E1($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?Yj($.prompt,f):Aj($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function bf($){let f=E1($),J=new e$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var JU=pW.object({systemPrompt:pW.string().describe("System prompt defining the sub-agent's behavior"),task:pW.string().describe("Task for the sub-agent to complete")});function $1($){return $U({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:fU(JU),execute:async(f,J)=>{let W=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=bf({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:W,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),Q=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:Q,conversationId:j,parentAgentId:X,input:f})}catch{}try{let H=await Z.run(f.task),Y={text:H.text,iterations:H.iterations,finishReason:H.finishReason,usage:{inputTokens:H.usage.inputTokens,outputTokens:H.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:X,input:f,result:Y,agentResult:H})}catch{}return Y}catch(H){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:Q,conversationId:j,parentAgentId:X,input:f,error:H instanceof Error?H:Error(String(H))})}catch{}throw H}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as WU,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as ZU,TEAM_RUN_TEXT_PREVIEW_LIMIT as QU,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as jU,TeamAttachOutcomeFragmentInputSchema as Vj,TeamAwaitRunsInputSchema as Bj,TeamBroadcastInputSchema as Kj,TeamBroadcastToolResultSchema as XU,TeamCancelRunInputSchema as Gj,TeamCancelRunToolResultSchema as HU,TeamCleanupInputSchema as Pj,TeamCleanupToolResultSchema as YU,TeamCreateOutcomeInputSchema as Uj,TeamCreateOutcomeToolResultSchema as AU,TeamFinalizeOutcomeInputSchema as Fj,TeamFinalizeOutcomeToolResultSchema as VU,TeamListOutcomesInputSchema as Rj,TeamListRunsInputSchema as Dj,TeamMailboxMessageToolResultSchema as BU,TeamMissionLogInputSchema as Lj,TeamMissionLogToolResultSchema as KU,TeamOutcomeFragmentToolResultSchema as zj,TeamOutcomeToolResultSchema as GU,TeamReadMailboxInputSchema as Oj,TeamReviewOutcomeFragmentInputSchema as _j,TeamRunTaskInputSchema as Tj,TeamRunTaskToolResultSchema as rW,TeamRunToolSummarySchema as iW,TeamSendMessageInputSchema as Nj,TeamSendMessageToolResultSchema as PU,TeamShutdownTeammateInputSchema as Mj,TeamSimpleAgentStatusToolResultSchema as yj,TeamSpawnTeammateInputSchema as qj,TeamStatusInputSchema as wj,TeamStatusToolResultSchema as UU,TeamTaskInputSchema as Sj,TeamTaskToolResultSchema as R8,validateWithZod as E,zodToJsonSchema as j0}from"@cline/shared";function hj($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function b1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function FU($){let f=$.result;if(!f)return;return{textPreview:hj(f.text,QU),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function I4($){return $?.toISOString()}function nW($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:hj($.message,ZU),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:I4($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:I4($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:I4($.heartbeatAt),lastProgressAt:I4($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:FU($)}}function RU($){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 kf=["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 Cj($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...k1({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:E1({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function If($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,W=k1({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let Q of $.restoredTeammates??[]){if($.runtime.isTeammateActive(Q.agentId))continue;Cj({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Q}),Z.push(Q.agentId)}return{tools:W,restoredFromPersistence:J,restoredTeammates:Z}}function k1($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,W=$.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:j0(qj),execute:async(j)=>{let X=E(qj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let H={agentId:X.agentId,rolePrompt:X.rolePrompt};if(Cj({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:H}),!W)$.onLeadToolsUnlocked?.(k1({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return E(yj,{agentId:X.agentId,status:"spawned"})}}));if(!W)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:j0(Mj),execute:async(j)=>{let X=E(Mj,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),E(yj,{agentId:X.agentId,status:"stopped"})}})),Z.push(Q0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:j0(wj),execute:async(j)=>{return E(wj,j),E(UU,$.runtime.getSnapshot())}})),Z.push(Q0({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:j0(Sj),execute:async(j)=>{let X=E(Sj,j);switch(X.action){case"create":{let H=new Set(jU.create??[]),Y=Object.entries(j).filter(([V,B])=>H.has(V)&&B!=null).map(([V])=>V),A=$.runtime.createTask({title:b1(X.title,"title"),description:b1(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return E(R8,{action:"create",taskId:A.id,status:A.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return E(R8,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let H=$.runtime.claimTask(b1(X.taskId,"taskId"),$.requesterId);return E(R8,{action:"claim",taskId:H.id,status:H.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 H=$.runtime.completeTask(b1(X.taskId,"taskId"),$.requesterId,b1(X.summary,"summary"));return E(R8,{action:"complete",taskId:H.id,status:H.status})}case"block":{let H=$.runtime.blockTask(b1(X.taskId,"taskId"),$.requesterId,b1(X.reason,"reason"));return E(R8,{action:"block",taskId:H.id,status:H.status})}}}}));let Q=new Map;return Z.push(Q0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:j0(Tj),execute:async(j)=>{let X=E(Tj,j);if(X.runMode==="async"){let A=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return E(rW,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${A.id}.`,runId:A.id})}let H=Q.get(X.agentId);if(H){let A=await H;return E(rW,{...A,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((A)=>E(rW,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:A.text,iterations:A.iterations})).finally(()=>{Q.delete(X.agentId)});return Q.set(X.agentId,Y),await Y}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:j0(Gj),execute:async(j)=>{let X=E(Gj,j),H=$.runtime.cancelRun(X.runId,X.reason);return E(HU,{runId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:j0(Dj),execute:async(j)=>E(iW.array(),$.runtime.listRuns(E(Dj,j)).map(nW))})),Z.push(Q0({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:j0(Bj),timeoutMs:WU,execute:async(j)=>{let X=E(Bj,j);if(X.runId){let A=await $.runtime.awaitRun(X.runId);return RU(A),E(iW,nW(A))}let H=await $.runtime.awaitAllRuns(),Y=H.filter((A)=>["failed","cancelled","interrupted"].includes(A.status));if(Y.length>0){let A=Y.map((V)=>`${V.id}:${V.status}${V.error?`(${V.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${A}`)}return E(iW.array(),H.map(nW))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:j0(Nj),execute:async(j)=>{let X=E(Nj,j),H=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return E(PU,{id:H.id,toAgentId:H.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:j0(Kj),execute:async(j)=>{let X=E(Kj,j),H=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return E(XU,{delivered:H.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:j0(Oj),execute:async(j)=>{let X=E(Oj,j);return E(BU.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:j0(Lj),execute:async(j)=>{let X=E(Lj,j),H=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return E(KU,{id:H.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:j0(Pj),execute:async(j)=>{if(E(Pj,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),E(YU,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:j0(Uj),execute:async(j)=>{let X=E(Uj,j),H=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return E(AU,{outcomeId:H.id,status:H.status,requiredSections:H.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:j0(Vj),execute:async(j)=>{let X=E(Vj,j),H=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return E(zj,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:j0(_j),execute:async(j)=>{let X=E(_j,j),H=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return E(zj,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:j0(Fj),execute:async(j)=>{let X=E(Fj,j),H=$.runtime.finalizeOutcome(X.outcomeId);return E(VU,{outcomeId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:j0(Rj),execute:async(j)=>{return E(Rj,j),E(GU.array(),$.runtime.listOutcomes())}})),Z}function x4($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}function Ej($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var DU=[{id:"read_files",description:"Read the full 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.",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:$1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...kf]}],LU={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function zU($){return $==="plan"||$==="yolo"?$:"act"}function kj($){let f=zU($.mode),J=I0[q$({mode:f})],W=hf($.providerId??"",$.modelId??"",f,Sf);return{mode:f,flags:{...J,...W,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function bj($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=kj(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let W=LU[$];return W?J[W]===!0:!1}function OU($,f){if($.id==="editor"){let{flags:J}=kj(f),W=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:bj($.id,f),headlessToolNames:[W?"apply_patch":"editor"]}}return{...$,defaultEnabled:bj($.id,f)}}function I1($={}){return DU.map((f)=>OU(f,$))}function m4($={}){return I1($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function g4($){if(!$.enabled)return new Set;let f=I1($.availabilityContext),J=new Set(f.map((W)=>W.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((W)=>W.defaultEnabled).map((W)=>W.id));for(let W of $.allowlist)if(!J.has(W))throw Error(`Unknown tool "${W}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function D8($,f={}){return I1(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function v4($,f={}){return D8($,f)}function x1($={}){let{executorOptions:f={},executors:J,...W}=$,Z={...wf(f),...J??{}};return s$({...W,executors:Z})}import{mkdirSync as qU,writeFileSync as wU}from"node:fs";import{dirname as SU}from"node:path";import{normalizeUserInput as hU}from"@cline/shared";import{nanoid as CU}from"nanoid";var xj={};w(xj,{sanitizeSessionToken:()=>m1,parseTeamTaskSubSessionId:()=>mf,parseSubSessionId:()=>z8,makeTeamTaskSubSessionId:()=>L8,makeSubSessionId:()=>xf,deriveSubsessionStatus:()=>O8});import{nanoid as NU}from"nanoid";function m1($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function xf($,f){let J=m1($),W=m1(f),Z=`${J}__${W}`;return Z.length>180?Z.slice(0,180):Z}function L8($,f){let J=m1($),W=m1(f);return`${J}__teamtask__${W}__${NU(6)}`}function mf($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+12),Q=Z.lastIndexOf("__");if(Q<=0)return null;let j=Z.slice(0,Q),X=Z.slice(Q+2);if(!W||!j||!X)return null;return{rootSessionId:W,agentId:j,teamTaskId:X}}function z8($){if(mf($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let W=$.slice(0,J),Z=$.slice(J+f.length);if(!W||!Z)return null;return{rootSessionId:W,agentId:Z}}function O8($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var vj={};w(vj,{isTerminalSessionStatus:()=>gj,isNonTerminalSessionStatus:()=>W0,SessionSource:()=>G0,SESSION_STATUSES:()=>_8,NON_TERMINAL_SESSION_STATUSES:()=>mj});import{SESSION_STATUS_VALUES as MU}from"@cline/shared";var _8=MU,mj=["idle","running","pending"];function gj($){return!mj.includes($)}function W0($){return!gj($)}var G0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};var yU=a.enum(_8),y0=a.object({version:a.literal(1),session_id:a.string().min(1),source:a.string().min(1),pid:a.number().int(),started_at:a.string().min(1),ended_at:a.string().min(1).optional(),exit_code:a.number().int().nullable().optional(),status:yU,interactive:a.boolean(),provider:a.string().min(1),model:a.string().min(1),cwd:a.string().min(1),workspace_root:a.string().min(1),team_name:a.string().min(1).optional(),enable_tools:a.boolean(),enable_spawn:a.boolean(),enable_teams:a.boolean(),prompt:a.string().optional(),metadata:a.record(a.string(),a.unknown()).optional(),messages_path:a.string().min(1).optional()});function uj($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function tW($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let W=[],Z=new Set;for(let Q of J){if(Z.has(Q.name))continue;Z.add(Q.name),W.push(Q)}return W}function cj($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function w$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function aW($,f){let J={...$};J.id=w$(J.id)??CU();let W=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:w$(W?.id)??w$(J.modelId)??w$(f?.id),provider:w$(W?.provider)??w$(J.providerId)??w$(f?.provider),family:w$(W?.family)??w$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function u4($){return $.map((f)=>aW(f))}function c4($,f,J=[]){let W=$.map((H,Y)=>{let A=J[Y],B=A?.role===H.role&&JSON.stringify(A.content)===JSON.stringify(H.content)?{...A,...H}:{...H};return aW(B)}),Z=J.length,Q=[];for(let H=Z;H<W.length;H+=1)if(W[H]?.role==="assistant")Q.push(H);if(Q.length===0){let H=[...W].reverse().findIndex((Y)=>Y.role==="assistant");if(H===-1)return W;Q.push(W.length-1-H)}let j=Q[Q.length-1],X=Q.some((H)=>W[H]?.metrics);for(let H of Q){let Y=W[H],A=Y.metrics;if(!A&&H===j&&!X){let V=f.usage;A={inputTokens:V.inputTokens,outputTokens:V.outputTokens,cacheReadTokens:V.cacheReadTokens??0,cacheWriteTokens:V.cacheWriteTokens??0,cost:V.totalCost}}W[H]={...aW(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...A?{metrics:A}:{},ts:Y.ts??f.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 EU=120;function g1($){let f=$?.trim();return f?f.slice(0,EU):void 0}function sW($){let f=hU($??"").trim();if(!f)return;return g1(f.split(`
137
+ `)[0]?.trim())}function f1($){if(!$)return;let f={...$},J=g1(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function N8($){let f=f1($.metadata)??{},J=$.title!==void 0?g1($.title):sW($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function oW($){let f=mf($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=z8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function eW($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:u4($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function dj($,f,J){qU(SU($),{recursive:!0}),wU($,`${JSON.stringify(eW({updatedAt:f,context:J,messages:[]}),null,2)}
138
+ `,"utf8")}function lj($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.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:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function pj($,f,J){let W=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let Q=await f(Z);if(typeof Q==="object"&&Q!==null&&"updated"in Q&&Q.updated===!1){if(W+=1,W>=J)return Q;continue}return Q}}L0();var rj={};w(rj,{summarizeUsageFromMessages:()=>vf,sumUsageTotals:()=>M8,getCurrentContextSize:()=>$Z,createInitialAccumulatedUsage:()=>B0,accumulateUsageTotals:()=>X0});function B0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function X0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function M8($){let f=B0();for(let J of $)f=X0(f,J);return f}function gf($){return typeof $==="number"&&Number.isFinite($)?$:0}function vf($){let f=B0();for(let J of $){let W=J.metrics;if(!W)continue;f=X0(f,{inputTokens:gf(W.inputTokens),outputTokens:gf(W.outputTokens),cacheReadTokens:gf(W.cacheReadTokens),cacheWriteTokens:gf(W.cacheWriteTokens),totalCost:gf(W.cost)})}return f}function $Z($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let W=gf(J.metrics?.inputTokens);return W>0?W:void 0}return}function bU($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let W=J.trim();return W.length>0?W:void 0}function fZ($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function S$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,W=$.teamRole,Z="root";if(W==="teammate")Z="team_teammate";else if(W==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:W,teamAgentId:$.teamAgentId?.trim()||void 0}}function kU($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function IU($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let W=J?.trim();if(W)return W}return $.isPrimaryAgentEvent?"root":"unknown"}function JZ($,f,J){let{sessionId:W,config:Z,liveSession:Q,emit:j}=$,X=Z.telemetry,H=Q?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,A=fZ(f),V=S$({agentId:J?.agentId??A.agentId,conversationId:J?.conversationId??A.conversationId,parentAgentId:J?.parentAgentId??A.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??H?.getTeamId(),teamName:J?.teamName??H?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=bU(f.input);if(B)F4(X,{ulid:W,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...V})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(U4(X,{ulid:W,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...V}),!K&&(B==="editor"||B==="apply_patch"))R4(X,{ulid:W,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...V})}if(f.type==="notice"&&f.reason==="api_error")i2(X,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...V});if(f.type==="error")i2(X,{ulid:W,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...V});if(f.type==="usage"&&Q?.turnUsageBaseline){let B=kU(f);if(Y){Q.turnPrimaryUsage=X0(Q.turnPrimaryUsage??B0(),B);let G=X0(Q.turnUsageBaseline,Q.turnPrimaryUsage);$.usageBySession.set(W,G),Nf(X,{ulid:W,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...V}),G4(X,{ulid:W,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...V})}else{let G=IU({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:A}),R=Q.turnUsageByAgent??new Map;Q.turnUsageByAgent=R,R.set(G,X0(R.get(G)??B0(),B))}let K=X0(Q.turnPrimaryUsage??B0(),M8(Q.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(W,X0(Q.turnAggregateUsageBaseline??Q.turnUsageBaseline,K))}if(f.type==="iteration_end"&&Y)$.persistMessages(W,Q?.agent.getMessages()??[],Q?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:W,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:W,stream:"agent",chunk:cj(f),ts:Date.now()}})}function J1($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as FD}from"@cline/shared";function ij($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function xU($){let J=new TextEncoder().encode($),W=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(W)}function mU($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),ij(f)}async function d4(){let $=mU(),f=ij(await xU($));return{verifier:$,challenge:f}}function l4($){return $.endsWith("/")?$.slice(0,-1):$}function v1($,f){return new URL(f,`${l4($)}/`).toString()}function uf($,f={}){let J=$.trim();if(!J)return{};try{let W=new URL(J);return{code:W.searchParams.get("code")??void 0,state:W.searchParams.get("state")??void 0,provider:f.includeProvider?W.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[W,Z]=J.split("#",2);return{code:W||void 0,state:Z||void 0}}if(J.includes("code=")){let W=new URLSearchParams(J);return{code:W.get("code")??void 0,state:W.get("state")??void 0,provider:f.includeProvider?W.get("provider")??void 0:void 0}}return{code:J}}function gU($){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 f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let W=J.replace(/-/g,"+").replace(/_/g,"/"),Z=W.padEnd(W.length+(4-W.length%4)%4,"="),Q=gU(Z);if(!Q)return null;return JSON.parse(Q)}catch{return null}}function cf($){try{let f=JSON.parse($),J=f.error,W=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:W,message:Z}}catch{return{}}}function u1($,f){return Date.now()>=$.expires-f}async function df($){if(!$.onManualCodeInput){let Q=await $.waitForCallback();return{code:Q?.code,state:Q?.state,provider:Q?.provider,error:Q?.error}}let f,J,W=$.onManualCodeInput().then((Q)=>{f=Q,$.cancelWait()}).catch((Q)=>{J=Q instanceof Error?Q:Error(String(Q)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return uf(f,$.parseOptions);if(await W,J)throw J;if(f)return uf(f,$.parseOptions);return{}}X$();import{existsSync as W6,readFileSync as kF,statSync as IF}from"node:fs";import{basename as xF,dirname as f6,join as Z6,resolve as J6}from"node:path";import{discoverPluginModulePaths as mF,resolveConfiguredPluginModulePaths as _X,resolvePluginConfigSearchPaths as gF,SKILLS_CONFIG_DIRECTORY_NAME as vF}from"@cline/shared/storage";import{resolve as GF}from"node:path";import{normalizePluginManifest as PF}from"@cline/shared";import{existsSync as P0,readFileSync as rf}from"node:fs";import{builtinModules as aU,createRequire as XZ}from"node:module";import{dirname as W1,extname as S8,isAbsolute as tU,resolve as c}from"node:path";import{fileURLToPath as ZX}from"node:url";import{PLUGIN_FILE_EXTENSIONS as sU}from"@cline/shared";var QX=W1(ZX(import.meta.url)),oU=XZ(import.meta.url),eU=c(QX,"..","..","..","..",".."),ZZ=JF(eU),$F=["@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"],HZ=new Set(aU.flatMap(($)=>[$,$.replace(/^node:/,"")])),w8=new Set(sU),fF=["development","node","import","require","default"];function JF($){let f={},J={"@cline/sdk":c($,"packages/sdk/src/index.ts"),"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[W,Z]of Object.entries(J))if(P0(Z))f[W]=Z;for(let W of["agents","core","llms","shared"]){let Z=c($,"packages",W),Q=c(Z,"package.json");if(!P0(Q))continue;try{let j=JSON.parse(rf(Q,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=c(Z,j.exports);if(P0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,H]of Object.entries(j.exports)){let Y=WF(Z,H);if(!Y)continue;let A=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[A]=Y}}catch{}}return f}function WF($,f){let J=YZ(f);if(!J)return null;let W=jX($,J);for(let Z of W)if(P0(Z))return Z;return null}function YZ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let W of fF){let Z=YZ(J[W],f);if(Z)return Z}return null}function jX($,f){let J=f.replace(/^\.\//,""),W=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...W]}return W}function ZF($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function s4($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function pf($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function QF($){let f=pf($);if($===f)return".";return`.${$.slice(f.length)}`}function XX($){return pf($).startsWith("@cline/")}function QZ($,f){let J=pf(f),W=W1($);while(!0){let Z=c(W,"node_modules",J);if(P0(Z)||P0(c(Z,"package.json")))return!0;let Q=c(W,"..");if(Q===W)return!1;W=Q}}function WX($){return jZ($)!==null}function jZ($){try{return oU.resolve($)}catch{}return jF($)}function jF($){let f=pf($),J=HX(f);if(!J)return null;let W=c(J,"package.json");try{let Z=JSON.parse(rf(W,"utf8")),Q=QF($),j=Q==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,Q)?Z.exports[Q]:void 0,X=YZ(j)??(Q==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let H=c(J,X),Y=[H,...jX(J,X).filter((A)=>A!==H)];for(let A of Y)if(P0(A))return A;return null}catch{return null}}function XF(){let $=[QX],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(W1(W1(f)));let J=process.execPath?.trim();if(J)$.push(W1(J));return[...new Set($.map((W)=>c(W)))]}function HF($,f){let J=$;while(!0){let W=c(J,"package.json");if(P0(W))try{if(JSON.parse(rf(W,"utf8")).name===f)return J}catch{}let Z=c(J,"node_modules",f,"package.json");if(P0(Z))return W1(Z);let Q=c(J,"..");if(Q===J)return null;J=Q}}function HX($){for(let f of XF()){let J=HF(f,$);if(J)return J}return null}function YF($){let J=W1($);for(let W=0;W<4;W++){let Z=c(J,"package.json");if(P0(Z))try{let j=JSON.parse(rf(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let Q=c(J,"..");if(Q===J)return!1;J=Q}return!1}function YX($,f){let J=f.startsWith("file:")?ZX(f):tU(f)?f:c(W1($),f);if(P0(J)&&w8.has(S8(J)))return J;for(let W of w8){let Z=`${J}${W}`;if(P0(Z))return Z}for(let W of w8){let Z=c(J,`index${W}`);if(P0(Z))return Z}return null}function AX($){let f=new Set,J=[/\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 J)for(let Z of $.matchAll(W)){let Q=Z[1];if(Q)f.add(Q)}return[...f]}function AF($){return S8($)!==".ts"}function VX($,f,J=new Set){if(J.has($)||!P0($))return;if(J.add($),!w8.has(S8($)))return;let W=rf($,"utf8"),Z=AF($);for(let Q of AX(W)){if(Q.startsWith("node:")||HZ.has(Q))continue;if(s4(Q)){if(!Z)continue;if(Object.hasOwn(ZZ,Q)||Object.hasOwn(ZZ,pf(Q))||QZ($,Q)||XX(Q)&&WX(Q)||f&&WX(Q))continue;throw Error(`Cannot find module '${pf(Q)}'`)}let j=YX($,Q);if(j)VX(j,f,J)}}function BX($,f=new Set,J=new Set){if(f.has($)||!P0($))return J;if(f.add($),!w8.has(S8($)))return J;let W=rf($,"utf8");for(let Z of AX(W)){if(J.add(Z),s4(Z))continue;let Q=YX($,Z);if(Q)BX(Q,f,J)}return J}function VF($,f){let J=XZ($),W={},Z=BX($),Q=new Set($F);for(let[j,X]of Object.entries(ZZ)){try{J.resolve(j);continue}catch{}W[j]=X}for(let j of Z)if(s4(j)&&(XX(j)||f))Q.add(j);for(let j of Q){if(Object.hasOwn(W,j)||QZ($,j))continue;let X=jZ(j);if(X)W[j]=X}if(!f)return W;for(let j of Z){if(!s4(j)||Object.hasOwn(W,j)||QZ($,j)||j.startsWith("node:")||HZ.has(j))continue;let X=jZ(j);if(X)W[j]=X}return W}function BF($){let f=S8($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var d1;function KF(){if(d1!==void 0)return d1;let $=HX("jiti");if(!$)return d1=null,null;let f=c($,"dist","babel.cjs");if(!P0(f))return d1=null,null;try{let W=XZ(f)(f);d1=typeof W==="function"?W:null}catch{d1=null}return d1}async function KX($,f={}){let J=!YF($);VX($,J);let W=VF($,J),Z=ZF(W),Q=await import("jiti"),j=typeof Q==="function"?Q:typeof Q.default==="function"?Q.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,V])=>BF(V)).map(([V])=>V),H=KF(),Y=H?(V)=>H({...V,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...HZ],transformModules:X,tryNative:!1,...Y?{transform:Y}:{}}).import($,{})}function GX($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function PX($){return typeof $==="object"&&$!==null}function AZ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function UF($,f){if(!PX($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!AZ($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!AZ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!AZ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function FF($,f){if(!PX($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);UF($,f)}async function h8($,f={}){let J=GF(f.cwd??process.cwd(),$),W=await KX(J,{useCache:f.useCache}),Z=f.exportName??"plugin",Q=W.default??W[Z];FF(Q,J);let j=Q,X=j.setup,H=X?(Y,A)=>{let V={...f.session,...A.session},B={...A,session:Object.keys(V).length>0?V:void 0,client:f.client??A.client,user:f.user??A.user,workspaceInfo:f.workspaceInfo??A.workspaceInfo,automation:f.automation??A.automation,logger:f.logger??A.logger,telemetry:f.telemetry??A.telemetry};return X(Y,B)}:void 0;return{...j,manifest:PF(j.manifest),setup:H}}async function o4($,f={}){return(await l1($,f)).plugins}async function l1($,f={}){let J=[],W=[],Z=new Map,Q=0;for(let X of $)try{let H=await h8(X,f);if(!GX(H.manifest,f))continue;let Y=Z.get(H.name);if(Y)W.push({type:"duplicate_plugin_override",pluginName:H.name,pluginPath:X,overriddenPluginPath:Y.pluginPath,message:`Plugin "${H.name}" from ${X} overrides ${Y.pluginPath}`});Z.set(H.name,{plugin:H,pluginPath:X,order:Q++})}catch(H){let Y=H instanceof Error?H.message:String(H);J.push({pluginPath:X,phase:"load",message:Y,stack:H instanceof Error?H.stack:void 0})}let j=[...Z.values()].sort((X,H)=>X.order-H.order);return{plugins:j.map((X)=>X.plugin),pluginPaths:j.map((X)=>X.pluginPath),failures:J,warnings:W}}import{existsSync as GZ}from"node:fs";import{createRequire as OX}from"node:module";import{dirname as e4,join as af}from"node:path";import{fileURLToPath as OF}from"node:url";var LX={};w(LX,{resolveSubprocessRuntimeExecutable:()=>VZ,buildSubprocessSandboxCommand:()=>DX,SubprocessSandbox:()=>nf,CLINE_JS_RUNTIME_PATH_ENV:()=>RX});import{spawn as RF}from"node:child_process";import{basename as DF}from"node:path";import{augmentNodeCommandForDebug as LF,withResolvedClineBuildEnv as zF}from"@cline/shared";function UX($){if($ instanceof Error)return $;return Error(String($))}var RX="CLINE_JS_RUNTIME_PATH";function FX($){let f=$?.trim();if(!f)return!1;let J=DF(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function VZ($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[RX]?.trim();if(J)return J;let W=$.execPath?.trim()||process.execPath;if(FX(W))return W;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let Q=Z?.trim();if(Q&&FX(Q))return Q}return"node"}function DX($,f={}){let J=VZ({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return LF([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class nf{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=DX($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=RF(f[0]??VZ(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:zF(process.env)});this.process=J;let W="",Z=(Q)=>{let j=W+Q;W=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(Q)=>{Z(Q)}),J.on("message",(Q)=>{this.onMessage(Q)}),J.on("error",(Q)=>{this.failPending(Error(`${this.processLabel} process error: ${UX(Q).message}`))}),J.on("exit",(Q,j)=>{this.process=null;let X=W.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(Q)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let W=this.process;if(!W||W.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,Q={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let H={resolve:(Y)=>j(Y),reject:X};if((J.timeoutMs??0)>0)H.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,H),W.send(Q,(Y)=>{if(!Y)return;let A=this.clearPendingRequest(Z);if(!A)return;A.reject(Error(`${this.processLabel} failed to send call "${$}": ${UX(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),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 f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function _F($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function C8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function TF(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function NF(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=OX($).resolve(`${TF()}/package.json`),W=af(e4(J),"extensions","plugin-sandbox-bootstrap.js");return GZ(W)?W:void 0}catch{return}}function MF(){let $=process.execPath?.trim();if(!$)return;let f=af(e4(e4($)),"extensions","plugin-sandbox-bootstrap.js");return GZ(f)?f:void 0}function yF(){let $=e4(OF(import.meta.url)),f=OX(import.meta.url),J=[af($,"plugin-sandbox-bootstrap.js"),af($,"extensions","plugin-sandbox-bootstrap.js"),af($,"agents","plugin-sandbox-bootstrap.js"),NF(),MF()];for(let Q of J.filter((j)=>typeof j==="string"))if(GZ(Q))return{file:Q};let W=af($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`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(`
139
+ `)}}var BZ=yF();function KZ($,f,J){if(typeof $==="number"&&$>0)return $;if(J){let W=process.env[J];if(W){let Z=Number(W);if(Number.isInteger(Z)&&Z>0)return Z}}return f}async function $6($){let f=new nf({name:"plugin-sandbox",..."file"in BZ?{bootstrapFile:BZ.file}:{bootstrapScript:BZ.script},onEvent:$.onEvent}),J=KZ($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),W=KZ($.hookTimeoutMs,3000),Z=KZ($.contributionTimeoutMs,60000),Q={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",Q,{timeoutMs:J}).finally(()=>{j=void 0}),j},H;try{H=await f.call("initialize",Q,{timeoutMs:J})}catch(V){throw await f.shutdown().catch(()=>{}),V}let Y=H.plugins.map(_F);return{extensions:Y.map((V)=>{let B={name:V.name,__clinePluginPath:V.pluginPath,manifest:V.manifest,setup:(K)=>{qF(K,f,V,Z,X),wF(K,f,V,Z,X),SF(K,f,V,Z,X),CF(K,f,V,Z,X),hF(K,V)}};return B.hooks=bF(f,V,W,X),B}),failures:H.failures,pluginPaths:Y.map((V)=>V.pluginPath),shutdown:async()=>{await f.shutdown()},warnings:H.warnings}}function qF($,f,J,W,Z){for(let Q of J.contributions?.tools??[]){let j={name:Q.name,description:Q.description??"",inputSchema:Q.inputSchema??{type:"object",properties:{}},timeoutMs:Q.timeoutMs,retryable:Q.retryable,execute:async(X,H)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:X,context:H},{timeoutMs:W})}catch(Y){if(!C8(Y))throw Y;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:Q.id,input:X,context:H},{timeoutMs:W})}}};$.registerTool(j)}}function wF($,f,J,W,Z){for(let Q of J.contributions?.commands??[])$.registerCommand({name:Q.name,description:Q.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}catch(X){if(!C8(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:Q.id,input:j},{timeoutMs:W})}}})}function SF($,f,J,W,Z){for(let Q of J.contributions?.rules??[])$.registerRule({id:Q.ruleId,source:Q.source,content:Q.hasContentHandler===!0?async()=>{try{return await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}catch(j){if(!C8(j))throw j;return await Z(),await f.call("resolveRuleContent",{pluginId:J.pluginId,contributionId:Q.id},{timeoutMs:W})}}:Q.content??""})}function hF($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function CF($,f,J,W,Z){for(let Q of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:Q.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return zX(X)?X:j}catch(X){if(!C8(X))throw X;await Z();let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:Q.id,messages:j},{timeoutMs:W});return zX(H)?H:j}}})}function zX($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function EF($,f,J,W,Z){return async(Q)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}catch(j){if(!C8(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:Q},{timeoutMs:W})}}}function bF($,f,J,W){let Z={};for(let Q of f.hooks??[])Z[Q]=EF($,f.pluginId,Q,J,W);return Object.keys(Z).length>0?Z:void 0}var UZ="package.json",uF="package";function E8($){return gF($)}function b8($){return mF($)}function cF($){try{return W6($)&&IF($).isDirectory()}catch{return!1}}function FZ($){let f=[],J=new Set;for(let W of $){let Z=J6(W);if(J.has(Z))continue;J.add(Z),f.push(Z)}return f}function TX($){let f=FZ($);return a4(f)}function NX($){return E8($).flatMap((f)=>b8(f)).filter((f)=>W6(f))}function dF($,f){let J=[];for(let W of $)try{J.push(..._X([W],f))}catch{}return J}function PZ($){return typeof $==="object"&&$!==null}function lF($){try{let f=JSON.parse(kF(Z6($,UZ),"utf8"));if(!PZ(f)||!PZ(f.cline))return[];let J=f.cline.plugins;if(!Array.isArray(J))return[];let W=[];for(let Z of J){if(typeof Z==="string"){W.push(Z);continue}if(!PZ(Z)||!Array.isArray(Z.paths))continue;for(let Q of Z.paths)if(typeof Q==="string")W.push(Q)}return W}catch{return[]}}function MX($,f){let J=J6(f);return lF($).some((W)=>J6($,W)===J)}function pF($,f){return xF($)===uF&&W6(Z6(f6($),UZ))&&MX(f6($),f)}function rF($){let f=J6($),J=[],W=f6(f);while(!0){if(pF(W,f)){J.push(W);break}if(W6(Z6(W,UZ))){if(MX(W,f))J.push(W);break}let Z=f6(W);if(Z===W)break;W=Z}return FZ(J)}function p1($={}){let f=$.cwd??process.cwd(),J=NX($.workspacePath),W=_X($.pluginPaths??[],f);return TX([...W,...J])}function iF($={}){let f=$.cwd??process.cwd(),J=NX($.workspacePath),W=dF($.pluginPaths??[],f);return TX([...W,...J])}function r1($){let f=[];for(let J of $)for(let W of rF(J)){let Z=Z6(W,vF);if(cF(Z))f.push(Z)}return FZ(f)}function yX($={}){return r1(iF($))}async function tf($={}){let f=p1($);if(f.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let W=await l1(f,{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 J=await $6({pluginPaths:f,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:J.extensions??[],shutdown:J.shutdown,failures:J.failures,pluginPaths:J.pluginPaths,warnings:J.warnings}}import{execFile as nF}from"node:child_process";import{promisify as aF}from"node:util";var tF=aF(nF);function RZ($,f){$?.log(f,{severity:"warn"})}function sF($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let W=J.latest,Z=J.history.filter((Q)=>!!Q&&typeof Q==="object"&&typeof Q.ref==="string"&&typeof Q.createdAt==="number"&&typeof Q.runCount==="number");if(typeof W.ref!=="string"||typeof W.createdAt!=="number"||typeof W.runCount!=="number")return;return{latest:W,history:Z}}async function i1($,f){let J=await tF("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function DZ($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:W}=await i1($,["for-each-ref","--format=%(refname)",J]),Z=W.trim().split(`
140
+ `).filter(Boolean);await Promise.allSettled(Z.map((Q)=>i1($,["update-ref","-d",Q])))}catch{}}async function qX($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((W)=>i1($,["update-ref",`refs/cline/checkpoints/${f}/${W.runCount}`,W.ref])))}function oF($,f){let J=$.findIndex((W)=>W.runCount===f.runCount);if(J<0)return[...$,f];return $.map((W,Z)=>Z===J?f:W)}function wX($){let f=$.initialRunCount??0,J,W=async()=>{if(J!==void 0)return J;try{J=(await i1($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await W())return;let Q=async(Y)=>{try{let V=(await i1($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!V)return;return{ref:V,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(A){RZ($.logger,`${Y}: ${A instanceof Error?A.message:String(A)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await i1($.cwd,["stash","create",j])).stdout.trim()}catch(Y){return RZ($.logger,`Checkpoint snapshot failed: ${Y instanceof Error?Y.message:String(Y)}`),Q("Checkpoint HEAD fallback failed")}if(!X)return Q("Checkpoint HEAD fallback failed");let H=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await i1($.cwd,["update-ref",H,X])}catch(Y){RZ($.logger,`Checkpoint store failed: ${Y instanceof Error?Y.message:String(Y)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:Q})=>{if(Q.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:Q})=>{if(Q.parentAgentId!=null||Q.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),H=sF(X);if(H?.latest.ref===j.ref)return;let Y=oF(H?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:Y}});return}}}import{spawn as XR}from"node:child_process";import{appendFileSync as HR,readFileSync as YR}from"node:fs";import{join as AR}from"node:path";import{augmentNodeCommandForDebug as CX,withResolvedClineBuildEnv as OZ}from"@cline/shared";import{ensureHookLogDir as SX}from"@cline/shared/storage";function sf($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as eF,readdirSync as $R}from"node:fs";import{basename as fR,extname as JR,join as WR}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as Q6,resolveHooksConfigSearchPaths as ZR}from"@cline/shared/storage";function k8($){return ZR($)}var of;((A)=>{A.TaskStart="TaskStart";A.TaskResume="TaskResume";A.TaskCancel="TaskCancel";A.TaskComplete="TaskComplete";A.TaskError="TaskError";A.PreToolUse="PreToolUse";A.PostToolUse="PostToolUse";A.UserPromptSubmit="UserPromptSubmit";A.PreCompact="PreCompact";A.SessionShutdown="SessionShutdown"})(of||={});var I8={["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"},QR=new Map(Object.values(of).map(($)=>[$.toLowerCase(),$])),jR=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function x8($){let f=JR($).toLowerCase();if(!jR.has(f))return;let J=fR($,f).trim().toLowerCase();return QR.get(J)}function Z1($){let f=[],J=new Set,W=k8($).filter((Z)=>eF(Z));for(let Z of W)try{for(let Q of $R(Z,{withFileTypes:!0})){if(!Q.isFile())continue;let j=x8(Q.name);if(!j)continue;let X=WR(Z,Q.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:I8[j],path:X})}}catch{}return f.sort((Z,Q)=>Z.path.localeCompare(Q.path))}function X6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))f[J]=typeof W==="string"?W:JSON.stringify(W);return f}function j6($,f,J){let W=J instanceof Error?`: ${J.message}`:"",Z=`${f}${W}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function VR($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
141
+ `),W=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:W.length>0?W:void 0}}function BR($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function LZ($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function U0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",W={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:W,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function KR($){let f=$.trim();if(!f)return{};let W=f.split(`
142
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse hook stdout JSON"}}}async function GR($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((W,Z)=>{let Q=!1,j=()=>{J.off("error",H),J.off("finish",Y),$.off("close",A)},X=(V)=>{if(Q)return;if(Q=!0,j(),V){let B=V.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){W();return}Z(V);return}W()},H=(V)=>X(V),Y=()=>X(),A=()=>X();J.on("error",H),J.once("finish",Y),$.once("close",A);try{J.end(f)}catch(V){X(V)}})}async function EX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await hX($,f)}catch(J){let W=FR(f.command,process.platform,J);if(!W)throw J;return await hX($,{...f,command:W})}}async function hX($,f){let J=CX(f.command,{env:f.env,debugRole:"hook"}),W=XR(J[0],J.slice(1),{cwd:f.cwd,env:OZ(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{W.once("spawn",()=>B())}),Q=new Promise((B,K)=>{W.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,Q]),await GR(W,j),f.detached){W.unref();return}if(!W.stdout||!W.stderr)throw Error("hook command failed to create stdout/stderr");let X="",H="",Y=!1,A;W.stdout.on("data",(B)=>{X+=B.toString()}),W.stderr.on("data",(B)=>{H+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,W.kill("SIGKILL")},f.timeoutMs);W.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=KR(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,Q])}function PR($){try{let J=YR($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let W=J.slice(2).trim();if(!W)return;let Z=W.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function UR($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function FR($,f=process.platform,J){if(f!=="win32"||!UR(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function bX($){if($.length===0)return;let[f,...J]=$,W=f.replace(/\\/g,"/").toLowerCase(),Z=W.split("/").at(-1)??W;if(Z==="env")return bX(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function RR($){let f=PR($);if(f&&f.length>0)return[...bX(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return CX(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function DR($){let f={};for(let J of Z1($)){if(!J.hookEventName)continue;let W=J.hookEventName,Z=f[W]??[];Z.push(RR(J.path)),f[W]=Z}return f}async function LR($){let f;for(let J of $.commands){let W=J.join(" ");try{let Z=await EX($.payload,{command:J,cwd:$.cwd,env:OZ(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){j6($.logger,`hook command timed out: ${W}`);continue}if(Z?.parseError){j6($.logger,`hook command returned invalid JSON control output: ${W} (${Z.parseError})`);continue}f=VR(f,BR(Z?.parsedJson))}catch(Z){j6($.logger,`hook command failed: ${W}`,Z)}}return f}function n1($){for(let f of $.commands){let J=f.join(" ");EX($.payload,{command:f,cwd:$.cwd,env:OZ(process.env),detached:!0}).catch((W)=>{j6($.logger,`hook command failed: ${J}`,W)})}}function Q1($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function zZ($,f){return{...Q1($.snapshot),userMessage:f}}function kX($){return{...Q1($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function IX($){return{...Q1($.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 xX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function zR($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function ef($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(W)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...W})}
143
+ `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??AR(SX(),"hooks.jsonl");SX(j),HR(j,Z,"utf8")};return{beforeRun:async(W)=>{let Z=zZ(W,"");J({...U0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(W)=>{let Z=kX(W);J({...U0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:X6(Z.call.input)}});return},afterTool:async(W)=>{let Z=IX(W);J({...U0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:X6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:W,result:Z})=>{let Q=Q1(W);if(Z.status==="completed"){J({...U0(Q,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||LZ(Z.error?.message)){J({...U0(Q,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...U0(Q,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(W)=>{if(W.type!=="message-added"||W.message.role!=="user")return;let Z=zZ({snapshot:W.snapshot},xX(W.message.content));J({...U0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function m8($){let f=DR($.workspacePath);if(!Object.values(f).some((V)=>V.length>0))return;let W=async(V,B)=>{let K=f[B]??[];if(K.length===0)return;n1({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...U0(V,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...U0(V,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(V)=>{let B=f.prompt_submit??[];if(B.length>0)n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"prompt_submit",userPromptSubmit:{prompt:V.userMessage,attachments:[]}}})},Q=async(V)=>{let B=f.tool_call??[];if(B.length===0)return;return LR({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...U0(V,$),hookName:"tool_call",iteration:V.iteration,tool_call:{id:V.call.id,name:V.call.name,input:V.call.input},preToolUse:{toolName:V.call.name,parameters:X6(V.call.input)}}})},j=async(V)=>{let B=f.tool_result??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"tool_result",iteration:V.iteration,tool_result:V.record,postToolUse:{toolName:V.record.name,parameters:X6(V.record.input),result:typeof V.record.output==="string"?V.record.output:JSON.stringify(V.record.output),success:!V.record.error,executionTimeMs:V.record.durationMs}}})},X=async(V)=>{let B=f.agent_end??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_end",iteration:V.iteration,turn:V.turn,taskComplete:{taskMetadata:{}}}})},H=async(V)=>{let B=f.agent_error??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_error",iteration:V.iteration,error:{name:V.error.name,message:V.error.message,stack:V.error.stack}}})},Y=async(V)=>{if(LZ(V.reason)){let K=f.agent_abort??[];if(K.length>0)n1({commands:K,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"agent_abort",reason:V.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;n1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...U0(V,$),hookName:"session_shutdown",reason:V.reason}})},A={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)A.beforeRun=async(V)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await W(Q1(V.snapshot),B);return};if((f.prompt_submit?.length??0)>0)A.onEvent=async(V)=>{if(V.type!=="message-added"||V.message.role!=="user")return;await Z(zZ({snapshot:V.snapshot},xX(V.message.content)))}}if((f.tool_call?.length??0)>0)A.beforeTool=async(V)=>{let B=await Q(kX(V));return zR(B)};if((f.tool_result?.length??0)>0)A.afterTool=async(V)=>{await j(IX(V));return};if((f.agent_end?.length??0)>0)A.afterRun=async({snapshot:V,result:B})=>{if(B.status!=="completed")return;await X({...Q1(V),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let V=A.afterRun;A.afterRun=async(B)=>{await V?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||LZ(G.error?.message)){await Y({...Q1(K),reason:G.error?.message});return}if(G.error)await H({...Q1(K),iteration:G.iterations,error:G.error})}}return A}function $2($){return sf("core.hook_config_files",m8($))}function a1($,f){let J=$.map((W)=>W[f]).filter((W)=>typeof W==="function");if(J.length===0)return;return async(W)=>{let Z;for(let Q of J){let j=await Q(W);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function t1($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:a1(f,"beforeRun"),afterRun:a1(f,"afterRun"),beforeModel:a1(f,"beforeModel"),afterModel:a1(f,"afterModel"),beforeTool:a1(f,"beforeTool"),afterTool:a1(f,"afterTool"),onEvent:a1(f,"onEvent")}}var mX={};w(mX,{normalizeRuntimeCapabilities:()=>F0});function F0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let W=f&&Object.keys(f).length>0;if(!W&&!J)return;return{...W?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}var YH={};w(YH,{toProviderConfig:()=>m0,emptyStoredProviderSettings:()=>Y1,StoredProviderSettingsSchema:()=>Z2,StoredProviderSettingsEntrySchema:()=>b6,ProviderSettingsSchemaTyped:()=>i8});import{z as H1}from"zod";var HH={};w(HH,{toProviderConfig:()=>m0,safeParseSettings:()=>E6,safeCreateProviderConfig:()=>IZ,parseSettings:()=>C6,normalizeProviderId:()=>W2,isBuiltInProviderId:()=>bZ,createProviderConfig:()=>kZ,SapSettingsSchema:()=>w6,ReasoningSettingsSchema:()=>N6,ProviderSettingsSchema:()=>X1,ProviderProtocolSchema:()=>O6,ProviderIdSchema:()=>r8,ProviderClientSchema:()=>_6,OcaSettingsSchema:()=>S6,ModelCatalogSettingsSchema:()=>h6,GcpSettingsSchema:()=>y6,BUILT_IN_PROVIDER_IDS:()=>EZ,BUILT_IN_PROVIDER:()=>p8,AzureSettingsSchema:()=>q6,AwsSettingsSchema:()=>M6,AuthSettingsSchema:()=>T6});import*as x0 from"@cline/llms";import{z as y}from"zod";L0();var $H={};w($H,{refreshOcaToken:()=>v8,loginOcaOAuth:()=>f2,getValidOcaCredentials:()=>u8,generateOcaOpcRequestId:()=>V6,createOcaRequestHeaders:()=>MZ,createOcaOAuthProvider:()=>NZ,OCI_HEADER_OPC_REQUEST_ID:()=>iX,DEFAULT_INTERNAL_OCA_BASE_URL:()=>H6,DEFAULT_INTERNAL_IDCS_URL:()=>cX,DEFAULT_INTERNAL_IDCS_SCOPES:()=>dX,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>uX,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>Y6,DEFAULT_EXTERNAL_IDCS_URL:()=>pX,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>rX,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>lX});import{nanoid as vX}from"nanoid";class _Z{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),W=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+W})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var gX={};w(gX,{startLocalOAuthServer:()=>e0});function OR(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function e0($){let f=await import("node:http"),J=$.host??"127.0.0.1",W=$.timeoutMs??300000,Z=$.successHtml??_R,Q=OR(),j=!1,X=null,H=null,Y=null,A=(K)=>{if(j)return;j=!0,Q.resolve(K)},V=()=>{if(X)clearTimeout(X),X=null;let K=Y;if(Y=null,H)H.close(),H=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{V(),A(null)},W),Q.promise};for(let K of $.ports){let G=f.createServer((P,U)=>{try{let F=new URL(P.url||"",`http://${J}:${K}`);if(F.pathname!==$.callbackPath){U.statusCode=404,U.end("Not found");return}let O={url:F,code:F.searchParams.get("code")??void 0,state:F.searchParams.get("state")??void 0,provider:F.searchParams.get("provider")??void 0,error:F.searchParams.get("error")??void 0};if(O.error){U.statusCode=400,U.end(`Authentication failed: ${O.error}`),V(),A(O);return}if(!O.code){U.statusCode=400,U.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){U.statusCode=400,U.end("State mismatch");return}U.statusCode=200,U.setHeader("Content-Type","text/html; charset=utf-8"),U.end(Z),V(),A(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((P)=>{let U=(F)=>{G.off("error",U),P({bound:!1,error:F})};G.once("error",U),G.listen(K,J,()=>{G.off("error",U),H=G,P({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw V(),R.error}if(R.bound){Y=K;let P=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:P})).catch(()=>{});return{callbackUrl:P,waitForCallback:B,cancelWait:()=>{V(),A(null)},close:()=>{V(),A(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var _R=`<!DOCTYPE html>
144
144
  <html lang="en">
145
145
  <head>
146
146
  <meta charset="utf-8">
@@ -181,7 +181,7 @@ ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function Aj($,f){l
181
181
  </div>
182
182
  <script>setTimeout(() => window.close(), 3000);</script>
183
183
  </body>
184
- </html>`;var uX="a8331954c0cf48ba99b5dd223a14c6ea",cX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",dX="openid offline_access",H6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",lX="c1aba3deed5740659981a752714eba33",pX="https://login-ext.identity.oraclecloud.com",rX="openid offline_access",Y6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",iX="opc-request-id",TR="/auth/oca",NR=Array.from({length:11},($,f)=>48801+f),MR=300000,yR=30000,nX=30000,qR=600000;class A6 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 j1={internal:{clientId:uX,idcsUrl:cX,scopes:dX,baseUrl:H6},external:{clientId:lX,idcsUrl:pX,scopes:rX,baseUrl:Y6}},g8=new Map,wR=86400000,SR=300000,hR=32,TW=new _W(wR,hR);function aX($){if(typeof $==="function")return $();return $??"internal"}function tX($){return{internal:{clientId:$?.internal?.clientId??j1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??j1.internal.idcsUrl,scopes:$?.internal?.scopes??j1.internal.scopes,baseUrl:$?.internal?.baseUrl??j1.internal.baseUrl},external:{clientId:$?.external?.clientId??j1.external.clientId,idcsUrl:$?.external?.idcsUrl??j1.external.idcsUrl,scopes:$?.external?.scopes??j1.external.scopes,baseUrl:$?.external?.baseUrl??j1.external.baseUrl}}}function CR($=Date.now()){let f=$-qR;for(let[J,W]of g8.entries())if(W.createdAt<f)g8.delete(J)}function ER($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=z0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=z0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function sX($,f,J){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let Q=z0($.id_token),j=z0(W),X=Q?.sub??j?.sub,H=Q?.email??j?.email;return{access:W,refresh:Z,expires:ER($,W,$.id_token),accountId:X??J?.accountId,email:H??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function oX($,f){let J=l4($),W=TW.get(J);if(W)return W;let Z=`${J}/.well-known/openid-configuration`,Q=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!Q.ok){let H=`${J}/oauth2/v1/token`;return TW.set(J,H,Date.now(),SR),H}let X=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return TW.set(J,X),X}function eX($){return{code:$.error,message:$.error_description}}async function bR($){let f=g8.get($.state);if(!f)throw Error("No PKCE verifier found for this state");g8.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,W=await oX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await Q.json();if(!Q.ok){let H=eX(j);throw new A6(`Token exchange failed: ${Q.status}${H.message?` - ${H.message}`:""}`,{status:Q.status,errorCode:H.code})}let X=z0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return sX(j,$.mode)}function kR($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${l4(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function f2($){L$($.telemetry,"oca");let f=tX($.config),J=aX($.mode),W=$.callbackPorts?.length?$.callbackPorts:NR,Z=$.callbackPath??TR,Q=$.requestTimeoutMs??nX,j=await e0({ports:W,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let H=vX(16),Y=vX(16),{verifier:A,challenge:V}=await d4();CR(),g8.set(H,{verifier:A,nonce:Y,mode:J,redirectUri:X,createdAt:Date.now()});let B=kR({callbackUrl:X,mode:J,state:H,nonce:Y,challenge:V,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await df({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==H)throw Error("State mismatch");let P=await bR({code:G,state:R,mode:J,config:f,requestTimeoutMs:Q});return z$($.telemetry,"oca"),_$($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw O$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function v8($,f={}){let J=tX(f.config),W=f.requestTimeoutMs??nX,Z=$.metadata?.mode,Q=Z==="internal"||Z==="external"?Z:aX(f.mode),j=Q==="external"?J.external:J.internal,X=await oX(j.idcsUrl,W),H=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(W)}),A=await Y.json();if(!Y.ok){let V=eX(A);throw new A6(`Token refresh failed: ${Y.status}${V.message?` - ${V.message}`:""}`,{status:Y.status,errorCode:V.code})}return sX(A,Q,$)}async function u8($,f,J){if(!$)return null;let W=f?.refreshBufferMs??J?.refreshBufferMs??MR,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??yR;if(f?.forceRefresh!==!0&&!u1($,W))return $;try{return await v8($,J)}catch(j){if(j instanceof A6&&j.isLikelyInvalidGrant())return p$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function NW($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return f2({...$,callbacks:f})},async refreshToken(f){return v8(f,$)},getApiKey(f){return f.access}}}async function V6($,f){let J=new TextEncoder,W=async(Y)=>{let A=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(A).slice(0,4),(V)=>V.toString(16).padStart(2,"0")).join("")},[Z,Q]=await Promise.all([W(f),W($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),X=new Uint32Array(1);crypto.getRandomValues(X);let H=(X[0]??0).toString(16).padStart(8,"0");return Z+Q+j+H}async function MW($){let f=await V6($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[iX]:f}}var XH={};w(XH,{resolveProviderConfig:()=>l8,getProviderConfig:()=>z6,getLiveModelsCatalog:()=>J2,clearPublicModelsCatalogCache:()=>JD,clearPrivateModelsCatalogCache:()=>CW,clearLiveModelsCatalogCache:()=>hW,OPENAI_COMPATIBLE_PROVIDERS:()=>d8,DEFAULT_MODELS_CATALOG_URL:()=>F6});import*as H0 from"@cline/llms";function yW($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((f)=>f.length>0)}function IR($,f){let J=yW($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let W=$,Z=yW(W.data??W.models);if(Z.length>0)return Z;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let j=Object.keys(W.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let Q=W.providers?.[f];if(Q&&typeof Q==="object"){let X=yW(Q.models??Q);if(X.length>0)return X}return[]}async function B6($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return IR(await J.json(),f)}function fH($){return $.replace(/\/+$/,"")}function K6($,f,J){let W=J?.trim();if(!W)return;let Z=$?.trim();if(!Z||!f?.trim())return W;try{let Q=new URL(W),j=new URL(f),X=new URL(Z);if(Q.origin!==j.origin)return W;let H=fH(j.pathname),Y=fH(X.pathname);if(H&&Q.pathname.startsWith(`${H}/`)){let A=Q.pathname.slice(H.length);X.pathname=`${Y}${A}`}else X.pathname=Q.pathname;return X.search=Q.search,X.hash=Q.hash,X.toString()}catch{return W}}function xR($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function mR($){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 gR=Object.values(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:xR($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),WH=Object.fromEntries(gR.map(($)=>[$.id,$]));function vR($){return WH[$]}function uR(){return Object.fromEntries(Object.entries(WH).filter(([,$])=>mR($)))}function ZH($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var F6="https://models.dev/api.json",cR=600000,QH=300000,dR=5000,U6=new Map,c8=new Map,qW=new Map,G6=new Map;async function lR(){return H0.getGeneratedProviderModels()}async function pR($,f={},J={},W={},Z={},Q={}){let j=await lR(),X=H0.resolveProviderModelCatalogKeys($),H=Object.assign({},...X.map((V)=>j[V]??{})),Y=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),A=Object.keys(Z).length>0;if(Y&&A)return H0.sortModelsByReleaseDate({...Z,...Q});if($==="openai-codex")return H0.sortModelsByReleaseDate({...f,...H0.filterOpenAICodexModels(J),...Z,...Q});return H0.sortModelsByReleaseDate({...H,...f,...J,...W,...Z,...Q})}function rR($,f){let J=H0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((W)=>f[W]??{}))}function R6($){let f=$?.trim();return f&&f.length>0?f:""}function SW($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function iR($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function nR($,f){return`${$}:${R6(f.baseUrl)}:${iR(SW(f)??"")}`}async function D6($,f,J=dR){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await fetch($,{...f,signal:W.signal})}finally{clearTimeout(Z)}}function s1($,f,J){if(J&&!$.includes(f))$.push(f)}function L6($,f){let J=["streaming","tools"];return s1(J,"images",Boolean(f.supportsImages)),s1(J,"prompt-cache",Boolean(f.supportsPromptCache)),s1(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function aR($,f){let J=await D6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let H=j.supported_features??[];Q[X]=L6(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:H.includes("reasoning")||H.includes("reasoning_effort"),supportsImages:!1})}return Q}function JH($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function tR($,f){let J=await D6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let X=j.id?.trim();if(!X)continue;Q[X]=L6(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}async function sR($,f){let W=`${(R6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await D6(W,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let H of j){let Y=H.id?.trim();if(!Y)continue;let A=H.supported_features??[],V=H.supported_sampling_parameters??[],B=H.input_modalities??[],K=["streaming"];s1(K,"tools",A.includes("tools")),s1(K,"reasoning",A.includes("reasoning")),s1(K,"temperature",V.includes("temperature")),s1(K,"images",B.includes("image"));let G={input:JH(H.pricing?.prompt),output:JH(H.pricing?.completion)};X[Y]={id:Y,name:H.name??Y,description:H.description,contextWindow:H.context_length,maxInputTokens:H.context_length,maxTokens:H.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function oR($){let f=R6($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function eR($,f){let W=`${oR($.baseUrl)}/v1/model/info`,Z=async(Y)=>D6(W,{method:"GET",headers:{accept:"application/json",...Y}}),Q=await Z({"x-litellm-api-key":f});if(!Q.ok)Q=await Z({Authorization:`Bearer ${f}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let X=(await Q.json())?.data??[],H={};for(let Y of X){let A=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||A;if(!B)continue;let K=Y.model_info,G=L6(B,{name:A??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(H[B]=G,A)H[A]={...G,id:A,name:A}}return H}var jH={baseten:aR,hicap:tR,litellm:eR,poolside:sR},wW=new Map,P6=new Map;function $D($,f){return`${$}:${R6(f.baseUrl)}`}async function fD($,f,J){let W=H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=K6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!Z)return{};let Q=f?.cacheTtlMs??QH,j=$D($,J),X=Date.now(),H=wW.get(j);if(H&&H.expiresAt>X)return H.data;let Y=P6.get(j);if(Y)return Y;let A=B6(Z,$).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,L6(K,{name:K})]));return wW.set(j,{data:B,expiresAt:X+Q}),B}).finally(()=>{P6.delete(j)});return P6.set(j,A),A}function JD(){wW.clear(),P6.clear()}async function WD($,f){let J=SW(f);if(!J)return{};let W=jH[$];if(!W)return{};return W(f,J)}function ZD($,f,J){if(!J)return!1;if(!jH[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(SW(J))}async function QD($,f,J){let W=f?.cacheTtlMs??QH,Z=nR($,J),Q=Date.now(),j=qW.get(Z);if(j&&j.expiresAt>Q)return j.data;let X=G6.get(Z);if(X)return X;let H=WD($,J).then((Y)=>{return qW.set(Z,{data:Y,expiresAt:Q+W}),Y}).finally(()=>{G6.delete(Z)});return G6.set(Z,H),H}async function jD($){return H0.fetchModelsDevProviderModels($,globalThis.fetch)}async function J2($={}){let f=$.url??F6,J=$.cacheTtlMs??cR,W=Date.now(),Z=U6.get(f);if(Z&&Z.expiresAt>W)return Z.data;let Q=c8.get(f);if(Q)return Q;let j=jD(f).then((X)=>{return U6.set(f,{data:X,expiresAt:W+J}),X}).finally(()=>{c8.delete(f)});return c8.set(f,j),j}function hW($){if($){U6.delete($),c8.delete($);return}U6.clear(),c8.clear()}function CW(){qW.clear(),G6.clear()}function XD($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:ZH(J.capabilities)}]))}var d8=XD(uR());function z6($){let f=vR($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:ZH(f.capabilities)}}async function l8($,f,J){let W=z6($);if(!W)return;try{let Z=f?.loadLatestOnInit?await J2(f):void 0,Q=Z?rR($,Z):{},j=J&&ZD($,f,J)?await QD($,f,J):{},H=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:J,Y=H?await fD($,f,H).catch(()=>({})):{},A=await pR($,W.knownModels,Q,j,Y,J?.knownModels);return{...W,knownModels:A}}catch(Z){if(f?.failOnError)throw Z;return W}}var p8=x0.BUILT_IN_PROVIDER,EW=x0.BUILT_IN_PROVIDER_IDS,bW=x0.isBuiltInProviderId,W2=x0.normalizeProviderId,r8=y.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),O6=y.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),_6=y.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),T6=y.object({apiKey:y.string().optional(),accessToken:y.string().optional(),refreshToken:y.string().optional(),expiresAt:y.number().int().positive().optional(),accountId:y.string().optional()}),HD=y.enum(["none","low","medium","high","xhigh"]),N6=y.object({enabled:y.boolean().optional(),effort:HD.optional(),budgetTokens:y.number().int().positive().optional()}),M6=y.object({accessKey:y.string().optional(),secretKey:y.string().optional(),sessionToken:y.string().optional(),region:y.string().optional(),profile:y.string().optional(),authentication:y.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:y.boolean().optional(),useCrossRegionInference:y.boolean().optional(),useGlobalInference:y.boolean().optional(),endpoint:y.string().url().optional(),customModelBaseId:y.string().optional()}),y6=y.object({projectId:y.string().optional(),region:y.string().optional()}),q6=y.object({apiVersion:y.string().optional(),useIdentity:y.boolean().optional()}),w6=y.object({clientId:y.string().optional(),clientSecret:y.string().optional(),tokenUrl:y.string().url().optional(),resourceGroup:y.string().optional(),deploymentId:y.string().optional(),useOrchestrationMode:y.boolean().optional(),api:y.enum(["orchestration","foundation-models"]).optional(),defaultSettings:y.record(y.string(),y.unknown()).optional()}),S6=y.object({mode:y.enum(["internal","external"]).optional(),usePromptCache:y.boolean().optional()}),h6=y.object({loadLatestOnInit:y.boolean().optional(),loadPrivateOnAuth:y.boolean().optional(),url:y.string().url().optional(),cacheTtlMs:y.number().int().positive().optional(),failOnError:y.boolean().optional()}),X1=y.object({provider:r8,apiKey:y.string().optional(),auth:T6.optional(),model:y.string().optional(),protocol:O6.optional(),client:_6.optional(),routingProviderId:r8.optional(),maxTokens:y.number().int().positive().optional(),contextWindow:y.number().int().positive().optional(),baseUrl:y.string().url().optional(),headers:y.record(y.string(),y.string()).optional(),timeout:y.number().int().positive().optional(),reasoning:N6.optional(),aws:M6.optional(),gcp:y6.optional(),azure:q6.optional(),sap:w6.optional(),oca:S6.optional(),region:y.string().optional(),apiLine:y.enum(["china","international"]).optional(),capabilities:y.array(y.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:h6.optional()});function C6($){return X1.parse($)}function E6($){return X1.safeParse($)}function YD($){return $.protocol==="openai-responses"||$.client==="openai"}function m0($,f={}){let J=$.provider,W=W2(J),Z=f.includeKnownModels!==!1,Q=$.reasoning?.effort||"none",j=Q==="none"?void 0:Q,X=d8[W],H=Object.assign({},...x0.resolveProviderModelCatalogKeys(W).map((R)=>x0.getGeneratedModelsForProvider(R))),Y=Object.keys(H)[0],A=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,V=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?H6:Y6:X?.baseUrl),B=$.routingProviderId??(YD($)&&W!==p8.OPENAI_NATIVE?p8.OPENAI_NATIVE:void 0),K=Z?X?.knownModels??(Object.keys(H).length>0?H:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??Y??"default",...Z?{knownModels:K}:{},apiKey:A,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:V,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,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??X?.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(G).filter(([R,P])=>P!==void 0))}function kW($){let f=C6($);return m0(f)}function IW($){let f=E6($);if(f.success)return{success:!0,config:m0(f.data)};return{success:!1,error:f.error}}var i8=X1;var b6=H1.object({settings:X1,updatedAt:H1.string().datetime(),tokenSource:H1.enum(["manual","oauth","migration"]).default("manual")}),Z2=H1.object({version:H1.literal(1),lastUsedProvider:H1.string().min(1).optional(),providers:H1.record(H1.string(),b6)});function Y1(){return{version:1,providers:{}}}X$();var KH={};w(KH,{InMemoryWorkspaceManager:()=>j2});import{upsertWorkspaceInfo as KD,WorkspaceManifestSchema as mW}from"@cline/shared";var BH={};w(BH,{normalizeWorkspacePath:()=>C$,generateWorkspaceInfoWithDiagnostics:()=>n8,generateWorkspaceInfo:()=>Q2,buildWorkspaceMetadataWithInfo:()=>xW,buildWorkspaceMetadata:()=>a8});import{basename as AD,resolve as VD}from"node:path";import{performance as AH}from"node:perf_hooks";import{processWorkspaceInfo as VH}from"@cline/shared";import BD from"simple-git";function C$($){return VD($)}async function Q2($){return(await n8($)).info}function k6($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function n8($){let f=C$($),J={rootPath:f,hint:AD(f)},W;try{let Z=BD({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((H)=>{let Y=H.refs.fetch||H.refs.push;return`${H.name}: ${Y}`});J.associatedRemoteUrls=X}}catch(j){W??=k6(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){W??=k6(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){W??=k6(j)}return{info:J,vcsType:"git",error:W}}catch(Z){return{info:J,vcsType:"none",error:k6(Z)}}}async function a8($){let f=await Q2($);return VH(f)}async function xW($){let f=AH.now(),J=await n8($),W=AH.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:VH(Z),durationMs:W,vcsType:J.vcsType,initError:J.error}}class j2{manifest;listeners=new Set;constructor($){this.manifest=mW.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await Q2($);return this.manifest=KD(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=C$($),J=this.manifest.workspaces[f];if(J)return this.manifest=mW.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath(f);return this.manifest=mW.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 f=C$($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as GD}from"node:crypto";var GH=new Set,PH=new Set;function PD($){return GD("sha256").update($).digest("hex")}function UD($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function UH($){if(!$.telemetry)return;let f=PD($.rootPath),J=$.rootCount??1;if(!GH.has(f))GH.add(f),A4($.telemetry,{root_count:J,vcs_types:UD($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!PH.has(f)){PH.add(f);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",V4($.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function RD($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function DD($,f,J){if(f.length>0)for(let Q of f)J?.log(Q.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(RD).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let Q of $)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function LD($,f){let J=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!J&&!W)return f;return{...f??{},...J?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function FH($,f){return FD($,f)}function zD($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function OD($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||_D($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function _D($){let f=$?.trim();if(!f)return;let J=z0(f),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function TD($,f,J,W,Z){let Q=J.getProviderSettings($.providerId),j=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,X={...Q??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.providerId==="openai-codex"?OD({sessionId:f,configHeaders:$.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:$.apiKey??Q?.auth?.accessToken??Q?.apiKey}):$.headers??Q?.headers,reasoning:LD($,Q?.reasoning),modelCatalog:j},H=m0(X);if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let A=$.fetch??H.fetch??Z;if(A)H.fetch=A;return H}async function RH($){let{input:f,sessionId:J,providerSettingsManager:W,defaultTelemetry:Z,defaultCapabilities:Q,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:H,onTeamEvent:Y,createSpawnTool:A,localRuntime:V,readSessionMetadata:B,writeSessionMetadata:K}=$,G=J1(f.config),{modelCatalogDefaults:R,userInstructionService:P,configExtensions:U,onTeamRestored:F,...O}=V??{},_=Object.keys(O).length>0?O:void 0,{workspaceInfo:D,workspaceMetadata:z,durationMs:N,vcsType:q,initError:$0}=await xW(G),A0=_?.extensionContext,o={...A0??{},workspace:{...D,...A0?.workspace??{}},session:{...A0?.session??{},sessionId:J},logger:A0?.logger??_?.logger,telemetry:A0?.telemetry??_?.telemetry??Z};UH({telemetry:o.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:q,durationMs:N,initError:$0,featureFlagEnabled:!0});let V0=$2({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:_?.logger,workspaceInfo:D}),i=uj(_?.hooks)?void 0:ef({rootSessionId:J,workspacePath:G,workspaceInfo:D}),W$=t1([_?.hooks,i]),p;if(FH(U,"plugins"))try{p=await tf({pluginPaths:_?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:H,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:D,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),DD(p.failures,p.warnings,_?.logger)}catch(p2){let r=p2 instanceof Error?p2.message:String(p2);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let k=t9(V0?[V0]:void 0,t9(_?.extensions,t4(p?.extensions))),D0=FH(U,"plugins")?r1(p?.pluginPaths??[]):void 0,n={...f.config,..._??{},sessionId:J,hooks:W$,extensions:k,extensionContext:o,telemetry:o.telemetry},t0=TD(n,J,W,R,X),T1=t1([n.hooks,n.checkpoint?.enabled===!0?wX({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:zD(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),N1={...n,providerConfig:t0,workspaceMetadata:z,hooks:T1},_f=f.toolPolicies??n.toolPolicies??j,l2=F0(Q,f.capabilities),H4=l2?.requestToolApproval,V9=l2?.toolExecutors,Tf=new j2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:f,config:N1,providerConfig:t0,workspaceMetadata:z,workspaceInfo:D,extensions:k,hooks:T1,toolPolicies:_f,requestToolApproval:H4,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:N1,hooks:T1,extensions:k,onTeamEvent:Y,createSpawnTool:A,onTeamRestored:F,userInstructionService:P,pluginSkillDirectories:D0,configExtensions:U,toolExecutors:V9,workspaceManager:Tf,logger:N1.logger,telemetry:N1.telemetry}}}import{existsSync as x6,mkdirSync as ND,readdirSync as MD,rmdirSync as yD,rmSync as qD,unlinkSync as wD}from"node:fs";import{dirname as DH,join as I6}from"node:path";function s(){return new Date().toISOString()}function t8($){if(!$||!x6($))return;try{wD($)}catch{}}function SD($){let f=mf($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=z8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class gW{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return I6(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!x6(f))ND(f,{recursive:!0});return f}sessionMessagesPath($){return I6(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return I6(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!x6(f)){f=DH(f);continue}try{if(MD(f).length>0)break;yD(f)}catch{break}f=DH(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!x6($))return;try{qD($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:W,fileStem:Z}=SD($),Q=this.sessionArtifactsDir(W);return{messagesPath:I6(Q,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as hD}from"@cline/shared/storage";L0();function LH($,f,J,W,Z){if(J)K4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else B4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});CD($.telemetry,{workspacePath:W})}function CD($,f){let J=hD("Hooks"),W=Z1(f.workspacePath),Z=new Map;for(let Q of W){let j=Q.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[Q,j]of Z.entries())_4($,Q,j.global,j.workspace)}function zH($,f){for(let J of f.mentions)z4($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)D4($,"file",J.length);for(let J of f.ignoredMentions)L4($,"file","not_found",J)}var PK={};w(PK,{ProviderSettingsManager:()=>R$});import{chmodSync as FK,existsSync as y7,mkdirSync as AS,readFileSync as VS,writeFileSync as BS}from"node:fs";import{basename as RK,dirname as q7}from"node:path";import{resolveProviderSettingsPath as KS}from"@cline/shared/storage";var T={};w(T,{writeHubDiscovery:()=>K5,writeGlobalSettings:()=>h$,withHubStartupLock:()=>G5,verifyHubConnection:()=>V$,updateMcpServerOAuthState:()=>Jf,updateLocalProvider:()=>s5,uninstallPlugin:()=>$7,truncateNotificationBody:()=>sJ,toggleDisabledTool:()=>n4,toTeamProgressLifecycleEvent:()=>T2,toProviderConfig:()=>m0,toHubHealthUrl:()=>kZ,toHookConfigFileName:()=>x8,summarizeUsageFromMessages:()=>vf,stopLocalHubServerGracefully:()=>iZ,startLocalOAuthServer:()=>e0,startHubWebSocketServer:()=>Df,startHubServer:()=>KB,startClineDeviceAuth:()=>pW,splitCoreSessionConfig:()=>_J,spawnDetachedHubServerWithRetry:()=>D2,spawnDetachedHubServer:()=>uZ,setTelemetryOptOutGlobally:()=>tj,setMcpServerDisabled:()=>$f,setDisabledTools:()=>WW,setDisabledPlugin:()=>JX,setAutoUpdateEnabledGlobally:()=>oj,sendHubCommand:()=>RV,saveLocalProviderSettings:()=>H7,saveLocalProviderOAuthCredentials:()=>B7,sanitizeSessionToken:()=>m1,safeParseSettings:()=>E6,safeCreateProviderConfig:()=>IW,runSubprocessEvent:()=>q2,runHook:()=>S2,reviveTeamStateDates:()=>x4,restartLocalHubIfIdleAfterStartupTimeout:()=>F5,resolveWorkspaceHubOwnerContext:()=>UA,resolveWorkflowsConfigSearchPaths:()=>BJ,resolveSkillsConfigSearchPaths:()=>AJ,resolveSharedHubOwnerContext:()=>Y0,resolveSessionBackend:()=>BQ,resolveRulesConfigSearchPaths:()=>VJ,resolveProviderConfig:()=>l8,resolvePluginSkillDirectoriesFromPaths:()=>r1,resolvePluginConfigSearchPaths:()=>E8,resolveMcpServerRegistrations:()=>H$,resolveLocalClineAuthToken:()=>K7,resolveHubUrl:()=>FQ,resolveHubOwnerContext:()=>x$,resolveHubEndpointOptions:()=>d0,resolveHubBuildId:()=>U1,resolveHooksConfigSearchPaths:()=>k8,resolveDisabledToolNames:()=>j$,resolveDisabledPluginPaths:()=>q8,resolveDefaultMcpSettingsPath:()=>_0,resolveDefaultHubPort:()=>R2,resolveDefaultHubPathname:()=>vZ,resolveDefaultHubHost:()=>gZ,resolveCoreSelectedToolIds:()=>g4,resolveCompatibleLocalHubUrl:()=>gJ,resolveClineDir:()=>BA,resolveClineDataDir:()=>kJ,resolveAndLoadAgentPlugins:()=>tf,resolveAgentPluginPaths:()=>p1,requestHubShutdown:()=>mJ,requestDesktopToolApproval:()=>rQ,rememberRecoverableLocalHubUrl:()=>F1,registerRemoteConfigSessionBlobUpload:()=>v5,registerMcpServersFromSettingsFile:()=>Wf,registerDisposable:()=>jS,refreshProviderModelsFromSource:()=>Y7,refreshOpenAICodexToken:()=>JJ,refreshOcaToken:()=>v8,refreshClineToken:()=>$J,readSessionCheckpointHistory:()=>oJ,readRemoteConfigSessionBlobUploadMetadata:()=>xQ,readHubDiscovery:()=>K0,readGlobalSettings:()=>O0,probeHubServer:()=>A$,probeHubConnection:()=>FV,prewarmFileIndex:()=>S4,prewarmDetachedHubServer:()=>P5,prepareRemoteConfigCoreIntegration:()=>gQ,parseWorkflowConfigFromMarkdown:()=>YJ,parseUserCommandEnvelope:()=>QS,parseSkillConfigFromMarkdown:()=>XJ,parseSettings:()=>C6,parseRuleConfigFromMarkdown:()=>HJ,parseHookEventPayload:()=>w2,openaiCodexOAuthProvider:()=>tW,normalizeWorkspacePath:()=>C$,normalizeUserInput:()=>ZS,normalizeSdkError:()=>WS,normalizeRuntimeCapabilities:()=>F0,normalizeProviderId:()=>W2,normalizeOpenAICodexCredentials:()=>aW,normalizeOAuthProvider:()=>A7,normalizeHubWebSocketUrl:()=>R1,noopBasicLogger:()=>JS,migrateLegacyProviderSettings:()=>Q4,mergeRulesForSystemPrompt:()=>K2,mergeAgentHooks:()=>t1,makeTeamTaskSubSessionId:()=>L8,makeSubSessionId:()=>xf,loginOpenAICodex:()=>Y2,loginOcaOAuth:()=>f2,loginLocalProvider:()=>V7,loginClineOAuth:()=>H2,loadOpenTelemetryAdapter:()=>lw,loadMcpSettingsFile:()=>e1,loadLlmsConfigFromFile:()=>T7,loadAgentPluginsFromPathsWithDiagnostics:()=>l1,loadAgentPluginsFromPaths:()=>o4,loadAgentPluginFromPath:()=>h8,listSessionHistoryFromBackend:()=>hZ,listPluginToolsWithDiagnostics:()=>Z5,listPluginTools:()=>zJ,listMcpServerOAuthStatuses:()=>DJ,listLocalProviders:()=>j7,listHookConfigFiles:()=>Z1,isToolDisabledGlobally:()=>ej,isTelemetryOptedOutGlobally:()=>i4,isSessionNotFoundError:()=>I$,isRuleEnabled:()=>a6,isPluginDisabledGlobally:()=>fX,isOpenAICodexTokenExpired:()=>nW,isHubReconnectableTransportError:()=>pZ,isHubCommandTimeoutError:()=>U5,isDiscoveryFilePresent:()=>GA,isClineAccountActionRequest:()=>m6,isBuiltInProviderId:()=>bW,isAutoUpdateEnabledGlobally:()=>sj,identifyAccount:()=>_$,hasMcpSettingsFile:()=>b$,getValidOpenAICodexCredentials:()=>WJ,getValidOcaCredentials:()=>u8,getValidClineCredentials:()=>fJ,getProviderConfigFields:()=>G7,getProviderConfig:()=>z6,getMcpServerOAuthState:()=>ff,getLocalProviderModels:()=>X7,getLiveModelsCatalog:()=>J2,getFileIndex:()=>y$,getCurrentContextSize:()=>$W,getCoreHeadlessToolNames:()=>D8,getCoreDefaultEnabledToolIds:()=>m4,getCoreBuiltinToolCatalog:()=>I1,getCoreAcpToolNames:()=>v4,getClineDefaultSystemPrompt:()=>rw,generateWorkspaceInfoWithDiagnostics:()=>n8,generateWorkspaceInfo:()=>Q2,generateOcaOpcRequestId:()=>V6,formatRulesForSystemPrompt:()=>B2,formatDisplayUserInput:()=>fS,filterExtensionToolRegistrations:()=>t4,filterDisabledTools:()=>c1,filterDisabledPluginPaths:()=>a4,fetchClineRecommendedModels:()=>O7,executeClineAccountAction:()=>g6,ensureHubWebSocketServer:()=>I5,ensureHubServer:()=>GB,ensureDetachedHubServer:()=>RA,ensureCustomProvidersLoaded:()=>n5,ensureCompatibleLocalHubUrl:()=>Vf,enrichPromptWithMentions:()=>qf,emptyWorkspaceManifest:()=>$S,emptyStoredProviderSettings:()=>Y1,discoverPluginModulePaths:()=>b8,deriveSubsessionStatus:()=>O8,deleteLocalProvider:()=>o5,defineLlmsConfig:()=>_7,createWorkflowsConfigDefinition:()=>PJ,createUserInstructionConfigService:()=>V1,createToolPoliciesWithPreset:()=>C4,createTool:()=>ew,createTeamName:()=>c5,createSubprocessHooks:()=>M5,createSpawnAgentTool:()=>$1,createSkillsConfigDefinition:()=>KJ,createSessionHost:()=>y2,createRuntimeHost:()=>y2,createRulesConfigDefinition:()=>GJ,createRemoteConfigSessionMessagesArtifactUploader:()=>mQ,createProviderConfig:()=>kW,createOpenTelemetryTelemetryService:()=>tJ,createOcaRequestHeaders:()=>MW,createOcaOAuthProvider:()=>NW,createOAuthClientCallbacks:()=>e8,createMcpTools:()=>U2,createLocalHubScheduleRuntimeHandlers:()=>x5,createLlmsSdk:()=>M7,createInitialAccumulatedUsage:()=>B0,createInMemoryHubOwnerContext:()=>KA,createHubServerUrl:()=>$$,createHubAuthToken:()=>B5,createHookConfigFileHooks:()=>m8,createHookConfigFileExtension:()=>$2,createHookAuditHooks:()=>ef,createDisabledMcpToolPolicy:()=>LJ,createDisabledMcpToolPolicies:()=>W5,createDelegatedAgentConfigProvider:()=>Ef,createDelegatedAgent:()=>bf,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>s$,createDefaultMcpServerClientFactory:()=>P2,createDefaultExecutors:()=>wf,createCoreSettingsService:()=>Qf,createCoreSessionSnapshot:()=>B$,createContributionRegistry:()=>ow,createContextCompactionPrepareTurn:()=>$8,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,createClineTelemetryServiceMetadata:()=>sw,createClineTelemetryServiceConfig:()=>tw,createClineOAuthProvider:()=>iW,createBuiltinTools:()=>x1,createAgentTeamsTools:()=>k1,createAgentRuntime:()=>YS,createAgentHooksExtension:()=>sf,connectToHub:()=>S5,completeClineDeviceAuth:()=>rW,clearPrivateModelsCatalogCache:()=>CW,clearLiveModelsCatalogCache:()=>hW,clearHubDiscovery:()=>c0,captureWorkspacePathResolved:()=>r7,captureWorkspaceInitialized:()=>A4,captureWorkspaceInitError:()=>V4,captureToolUsage:()=>U4,captureTokenUsage:()=>G4,captureTaskRestarted:()=>K4,captureTaskCreated:()=>B4,captureTaskCompleted:()=>r2,captureSubagentExecution:()=>n2,captureSkillUsed:()=>F4,captureSdkError:()=>aw,captureProviderConfigured:()=>i7,captureProviderApiError:()=>i2,captureModeSwitch:()=>P4,captureMentionUsed:()=>D4,captureMentionSearchResults:()=>z4,captureMentionFailed:()=>L4,captureHookDiscovery:()=>_4,captureExtensionActivated:()=>p7,captureDiffEditFailure:()=>R4,captureConversationTurnEvent:()=>Nf,captureCompactionSkipped:()=>N4,captureCompactionExecuted:()=>T4,captureAuthSucceeded:()=>z$,captureAuthStarted:()=>L$,captureAuthLoggedOut:()=>p$,captureAuthFailed:()=>O$,captureAgentTeamCreated:()=>O4,captureAgentCreated:()=>r$,buildWorkspaceMetadata:()=>a8,buildTeamProgressSummary:()=>_2,buildSdkErrorProperties:()=>iw,buildRemoteConfigSessionBlobUploadMetadata:()=>m5,buildDelegatedAgentConfig:()=>E1,bootstrapAgentTeams:()=>If,authorizeMcpServerOAuth:()=>$5,addLocalProvider:()=>Q7,accumulateUsageTotals:()=>X0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>jJ,UnifiedConfigFileWatcher:()=>o1,ToolPresets:()=>I0,TelemetryService:()=>E2,TelemetryLoggerSink:()=>aJ,TEAM_TOOL_NAMES:()=>kf,SubprocessSandbox:()=>nf,StoredProviderSettingsSchema:()=>Z2,StoredProviderSettingsEntrySchema:()=>b6,SqliteTeamStore:()=>Lf,SqliteSessionStore:()=>G$,SessionVersioningService:()=>O1,SessionVersioningError:()=>S0,SessionSource:()=>G0,SessionNotFoundError:()=>k$,SapSettingsSchema:()=>w6,SKILLS_CONFIG_DIRECTORY_NAME:()=>QJ,SESSION_STATUSES:()=>_8,SESSION_NOT_FOUND_ERROR_CODE:()=>jf,SDK_ERROR_TELEMETRY_EVENT:()=>XS,RpcClineAccountService:()=>o8,RemoteRuntimeHost:()=>O2,ReasoningSettingsSchema:()=>N6,RULES_CONFIG_DIRECTORY_NAME:()=>n6,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>g5,ProviderSettingsSchema:()=>X1,ProviderSettingsManager:()=>R$,ProviderProtocolSchema:()=>O6,ProviderIdSchema:()=>r8,ProviderClientSchema:()=>_6,OpenTelemetryProvider:()=>b2,OcaSettingsSchema:()=>S6,OPENAI_COMPATIBLE_PROVIDERS:()=>d8,NodeHubClient:()=>f$,NativeHubTransportAdapter:()=>J4,ModelCatalogSettingsSchema:()=>h6,LocalRuntimeHost:()=>F$,Llms:()=>pw,InMemoryWorkspaceManager:()=>j2,InMemoryMcpManager:()=>Zf,HubUIClient:()=>LQ,HubTransportError:()=>T0,HubSessionClient:()=>DQ,HubServerTransport:()=>x2,HubScheduleService:()=>C2,HubScheduleCommandService:()=>h2,HubRuntimeHost:()=>m$,HubCommandError:()=>L2,HookEventPayloadSchema:()=>N5,HookEventNameSchema:()=>T5,HookConfigFileName:()=>of,HOOK_CONFIG_FILE_EVENT_MAP:()=>I8,HOOKS_CONFIG_DIRECTORY_NAME:()=>Q6,GlobalSettingsSchema:()=>y8,GcpSettingsSchema:()=>y6,FileTeamPersistenceStore:()=>J9,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>H9,DefaultToolNames:()=>J0,DefaultRuntimeBuilder:()=>v2,DefaultLlmsSdk:()=>j4,DEFAULT_MODELS_CATALOG_URL:()=>F6,DEFAULT_HUB_PORT:()=>xZ,DEFAULT_HUB_PATHNAME:()=>mZ,DEFAULT_HUB_HOST:()=>IZ,CoreSettingsService:()=>B1,CoreSessionService:()=>U$,ContributionRegistry:()=>nw,ClineCore:()=>iJ,ClineAccountService:()=>s8,ChatViewStateSchema:()=>L7,ChatSummarySchema:()=>X9,ChatSessionStatusSchema:()=>Z9,ChatSessionConfigSchema:()=>W9,ChatMessageSchema:()=>j9,ChatMessageRoleSchema:()=>Q9,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>z7,BrowserWebSocketHubAdapter:()=>f4,BUILT_IN_PROVIDER_IDS:()=>EW,BUILT_IN_PROVIDER:()=>p8,AzureSettingsSchema:()=>q6,AwsSettingsSchema:()=>M6,AuthSettingsSchema:()=>T6,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>M2,Agent:()=>HS,ALL_DEFAULT_TOOL_NAMES:()=>n$});M(T,rl);import*as pw from"@cline/llms";import{buildClineSystemPrompt as rw,buildSdkErrorProperties as iw,ContributionRegistry as nw,captureSdkError as aw,createClineTelemetryServiceConfig as tw,createClineTelemetryServiceMetadata as sw,createContributionRegistry as ow,createTool as ew,emptyWorkspaceManifest as $S,formatDisplayUserInput as fS,noopBasicLogger as JS,normalizeSdkError as WS,normalizeUserInput as ZS,parseUserCommandEnvelope as QS,registerDisposable as jS,SDK_ERROR_TELEMETRY_EVENT as XS}from"@cline/shared";import"@cline/shared/storage";var _H={};w(_H,{isClineAccountActionRequest:()=>m6,executeClineAccountAction:()=>g6,RpcClineAccountService:()=>o8,ClineAccountService:()=>s8});function ED($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function OH($,f,J){let W=ED(J);if(W)return W;let Z=f.trim();if(Z){let Q=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${Q}`}return`Cline account request failed with status ${$}`}class s8{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,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 f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,Q=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),H;if(X.trim())try{H=JSON.parse(X)}catch{if(!j.ok)throw Error(OH(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(OH(j.status,X,H));if(typeof H==="object"&&H!==null){let Y=H;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(H===void 0||H===null)throw Error("Cline account response payload was empty");return H}finally{clearTimeout(Q)}}}function m6($){return $.action==="clineAccount"}async function g6($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class o8{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 f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var TH={};w(TH,{createOAuthClientCallbacks:()=>e8});function e8($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((W)=>{$.onOpenUrlError?.({url:f,error:W})})}catch(W){$.onOpenUrlError?.({url:f,error:W})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}L0();var CH={};w(CH,{startClineDeviceAuth:()=>pW,refreshClineToken:()=>$J,loginClineOAuth:()=>H2,getValidClineCredentials:()=>fJ,createClineOAuthProvider:()=>iW,completeClineDeviceAuth:()=>rW});import{getClineEnvironmentConfig as vW}from"@cline/shared";var v6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},qH={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},uW="https://api.workos.com",bD="/auth",NH=Array.from({length:11},($,f)=>48801+f),kD=300000,ID=30000,X2=30000,xD=300,mD=5;class A1 extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 gD($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function cW($,f,J={}){let W=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:gD($.expiresAt),accountId:W??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function dW($){if(!$)return{};return typeof $==="function"?await $():$}function MH($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function yH($){await new Promise((f)=>setTimeout(f,$))}function lW($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function wH($,f){let J=await fetch(v1(uW,qH.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??X2)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new A1(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.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:MH(W.expires_in,xD),pollIntervalSeconds:MH(W.interval,mD)}}async function SH($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let W=await fetch(v1($.workosApiBaseUrl,qH.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)}),Z=await W.json().catch(()=>({}));if(W.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await yH(J*1000);break}case"slow_down":{J+=1,await yH(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new A1(Z.error_description||"WorkOS authorization failed",{status:W.status,errorCode:Z.error});default:throw new A1(`WorkOS token polling failed: ${W.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:W.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function hH($,f,J){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(v1(f.apiBaseUrl,v6.register),{method:"POST",headers:{"Content-Type":"application/json",...await dW(f.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(f.requestTimeoutMs??X2)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=cf(j);throw new A1(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let Q=await Z.json();return cW(lW(Q,"Invalid token exchange response"),J??f.provider)}async function vD($,f,J,W){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:W??J.provider},Q=await fetch(v1(J.apiBaseUrl,v6.token),{method:"POST",headers:{"Content-Type":"application/json",...await dW(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??X2)});if(!Q.ok){let X=await Q.text().catch(()=>""),H=cf(X);throw new A1(`Token exchange failed: ${Q.status}${H.message?` - ${H.message}`:""}`,{status:Q.status,errorCode:H.code})}let j=await Q.json();return cW(lW(j,"Invalid token exchange response"),W??J.provider)}async function H2($){L$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:NH,W=$.callbackPath??bD,Z=f?null:await e0({ports:J,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Q=Z?.callbackUrl||`http://127.0.0.1:${J[0]??NH[0]}${W}`;try{let j;if(f){let X=vW().workOsClientId,H=await wH(X,$);$.callbacks.onAuth({url:H.verificationUriComplete??H.verificationUri,instructions:`Enter this code in your browser: ${H.userCode}`});let Y=await SH({clientId:X,deviceCode:H.deviceCode,expiresInSeconds:H.expiresInSeconds,initialPollIntervalSeconds:H.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??X2,workosApiBaseUrl:uW,onProgress:$.callbacks.onProgress});j=await hH(Y,$,$.provider)}else{let X=new URL(v1($.apiBaseUrl,v6.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",Q),X.searchParams.set("redirect_uri",Q),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let H,Y=$.provider,A=await df({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(A.error)throw Error(`OAuth error: ${A.error}`);if(H=A.code,Y=A.provider??Y,!H){let V=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=uf(V,{includeProvider:!0});H=B.code,Y=B.provider??Y}if(!H)throw Error("Missing authorization code");j=await vD(H,Q,$,Y)}return z$($.telemetry,$.provider??"cline"),_$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw O$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function pW($){return await wH(vW().workOsClientId,$)}async function rW($){let f=$.provider??"cline";L$($.telemetry,f);try{let J=await SH({clientId:vW().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??X2,workosApiBaseUrl:uW}),W=await hH(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return z$($.telemetry,f),_$($.telemetry,{id:W.accountId,email:W.email,provider:f}),W}catch(J){throw O$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function $J($,f){let J=await fetch(v1(f.apiBaseUrl,v6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await dW(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??X2)});if(!J.ok){let Q=await J.text().catch(()=>""),j=cf(Q);throw new A1(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let W=await J.json(),Z=$.metadata?.provider??f.provider;return cW(lW(W,"Invalid token refresh response"),Z,$)}async function fJ($,f,J){if(!$)return null;let W=J?.refreshBufferMs??kD,Z=J?.retryableTokenGraceMs??ID;if(J?.forceRefresh!==!0&&!u1($,W))return $;try{return await $J($,f)}catch(j){if(j instanceof A1&&j.isLikelyInvalidGrant())return p$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function iW($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return H2({...$,callbacks:f})},async refreshToken(f){return $J(f,$)},getApiKey(f){return`workos:${f.access}`}}}L0();var kH={};w(kH,{refreshOpenAICodexToken:()=>JJ,openaiCodexOAuthProvider:()=>tW,normalizeOpenAICodexCredentials:()=>aW,loginOpenAICodex:()=>Y2,isOpenAICodexTokenExpired:()=>nW,getValidOpenAICodexCredentials:()=>WJ,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as uD}from"nanoid";var e={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 u6 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 cD($,f,J=e.redirectUri){let W=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function dD($){try{let f=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!f.ok){let W=await f.text().catch(()=>""),Z=cf(W);throw new u6(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.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}}catch(f){if(f instanceof u6)throw f;return{type:"failed"}}}async function lD($="pi"){let{verifier:f,challenge:J}=await d4(),W=uD(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",W),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:W,url:Z.toString()}}function pD(){try{let $=new URL(e.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function EH($,f){let J=f?z0(f):z0($),W=J?J:z0($),Q=W?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let j=W?.organizations;if(Array.isArray(j)&&j.length>0){let H=j[0];if(typeof H?.id==="string"&&H.id.length>0)return H.id}let X=W?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function bH($,f){let J=EH($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function Y2($){L$($.telemetry,"openai-codex");let f=pD(),{verifier:J,state:W,url:Z}=await lD($.originator),Q=await e0({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:W});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await df({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==W)throw Error("State mismatch");if(j=X.code,!j){let A=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=uf(A,{allowHashCodeState:!0});if(V.state&&V.state!==W)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let H=await cD(j,J,f.redirectUri);if(H.type!=="success")throw Error("Token exchange failed");let Y=bH(H);return z$($.telemetry,"openai-codex"),_$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(X){throw O$($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{Q.close()}}async function JJ($,f){let J=await dD($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=bH(J,f);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function WJ($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,W=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!u1($,J))return $;try{return await JJ($.refresh,$)}catch(Q){if(Q instanceof u6&&Q.isLikelyInvalidGrant())return p$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}function nW($,f=e.refreshBufferMs){return u1($,f)}function aW($){let f=$.accountId??EH($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var tW={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return Y2({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return JJ($.refresh,$)},getApiKey($){return $.access}};var YV={};w(YV,{ClineCore:()=>iJ});function IH($){if($===!0)return{};if(!$)return;return $}function xH($){if($==="user")return"global";return $}class sW{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function mH($){let{host:f}=$;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:W2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:nD(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:iD(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function c6($){let f=rD($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,Q=$.context?.telemetry??$.telemetry;if(!f&&!J&&!W&&!Z&&!Q)return $.context;return{...$.context??{},...J?{client:J}:{},...W?{user:W}:{},...Z?{logger:Z}:{},...Q?{telemetry:Q}:{},...f?{automation:f}:{}}}function rD($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function iD($){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((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function nD($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var MY={};w(MY,{createCoreSettingsService:()=>Qf,CoreSettingsService:()=>B1});import{existsSync as Q5}from"node:fs";import{basename as _Y,isAbsolute as Uz,relative as Fz}from"node:path";var eH={};w(eH,{resolveWorkflowsConfigSearchPaths:()=>BJ,resolveSkillsConfigSearchPaths:()=>AJ,resolveRulesConfigSearchPaths:()=>VJ,parseWorkflowConfigFromMarkdown:()=>YJ,parseSkillConfigFromMarkdown:()=>XJ,parseRuleConfigFromMarkdown:()=>HJ,createWorkflowsConfigDefinition:()=>PJ,createUserInstructionConfigService:()=>V1,createSkillsConfigDefinition:()=>KJ,createRulesConfigDefinition:()=>GJ,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>jJ,UnifiedConfigFileWatcher:()=>o1,SKILLS_CONFIG_DIRECTORY_NAME:()=>QJ,RULES_CONFIG_DIRECTORY_NAME:()=>n6});import{createHash as aD}from"node:crypto";import{watch as tD}from"node:fs";import{readdir as sD,readFile as oD}from"node:fs/promises";import{join as eD}from"node:path";function $L($){return aD("sha1").update($).digest("hex")}function uH($){return Boolean($&&typeof $==="object"&&"code"in $)}function gH($){return uH($)&&$.code==="ENOENT"}function vH($){return uH($)&&($.code==="EACCES"||$.code==="EPERM")}class o1{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($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let Z=this.baseTypesByDirectory.get(W);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.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 f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([W,Z])=>[W,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=tD(f,()=>{let W=this.watchedTypesByDirectory.get(f);if(!W)return;for(let Z of W)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(W)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let Q of Z)this.emit({kind:"error",type:Q,error:W,filePath:f})})}catch(J){if(!gH(J)&&!vH(J)){let W=$.get(f);if(!W)continue;for(let Z of W)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}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 f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[Z,Q]of W.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:Q.filePath})}for(let[Z,Q]of f.entries()){let j=W.get(Z);if(j&&j.filePath===Q.filePath&&j.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:Z,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let W of $.directories){J.add(W);let Z=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of Z){let{fileName:j,filePath:X}=Q;if(J.add(Q.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let H=await oD(X,"utf8"),Y={type:$.type,directoryPath:Q.directoryPath,fileName:j,filePath:X,content:H},A=$.parseFile(Y),V=$.resolveId(A,Y).trim();if(!V)continue;f.set(V,{type:$.type,id:V,item:A,filePath:X,fingerprint:$L(H)})}catch(H){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:H,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let Z=$.get(W);if(Z)Z.add(f);else $.set(W,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await sD($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:eD($,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch(f){if(gH(f)||vH(f))return[];throw f}}}import{readdir as eW,readFile as fL,stat as oW}from"node:fs/promises";import{basename as E$,dirname as JL,extname as l6,join as q0,resolve as ZJ}from"node:path";import{AGENTS_RULES_FILE_NAME as cH,RULES_CONFIG_DIRECTORY_NAME as n6,resolveGlobalAgentsRulesPath as WL,resolveRulesConfigSearchPaths as ZL,resolveSkillsConfigSearchPaths as QL,resolveWorkflowsConfigSearchPaths as jL,SKILLS_CONFIG_DIRECTORY_NAME as QJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as jJ}from"@cline/shared/storage";import XL from"yaml";var d6="SKILL.md",HL="managed.json",YL=new Set([".md",".markdown",".txt"]);function $Z($){return $.trim().toLowerCase()}function A2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function p6($){return YL.has(l6($).toLowerCase())}function dH($){let f=[],J=new Set;for(let W of $){let Z=ZJ(W);if(J.has(Z))continue;J.add(Z),f.push(W)}return f}function AL($){let f=[...$?.directories??AJ($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...yX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return dH(f)}async function fZ($){try{let f=await eW($,{withFileTypes:!0}),J=[];for(let W of f){if(!W.isDirectory())continue;let Z=q0($,W.name),Q=q0(Z,HL);try{let j=await fL(Q,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(A2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((W,Z)=>W.localeCompare(Z))}catch(f){if(A2(f))return[];throw f}}function JZ($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J;try{let Q=XL.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}catch(Q){let j=Q instanceof Error?Q.message:String(Q);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function r6($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let W=$.trim();if(!W&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return W||void 0}function V2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function VL($,f){if(E$($.filePath).toLowerCase()!==cH.toLowerCase())return E$($.filePath,l6($.filePath));if(f&&ZJ($.filePath)===ZJ(f,cH))return"Workspace AGENTS.md";if(ZJ($.filePath)===ZJ(WL()))return"Global AGENTS.md";return E$($.filePath,l6($.filePath))}function XJ($,f){let{data:J,body:W,parseError:Z}=JZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let X=r6(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:r6(J.description,"description",!1),disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function HJ($,f){let{data:J,body:W,parseError:Z}=JZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let j=r6(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function YJ($,f){let{data:J,body:W,parseError:Z}=JZ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let j=r6(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function AJ($){return QL($)}function VJ($){return ZL($)}function BJ($){return jL($)}async function lH($){if(E$($)===".cline"){let f=await fZ($);return(await Promise.all(f.map((W)=>lH(q0(W,QJ))))).flat()}try{let f=await eW($,{withFileTypes:!0}),J=[];for(let W of f){if(W.isFile()&&W.name===d6){J.push({directoryPath:$,fileName:W.name,filePath:q0($,W.name)});continue}let Z=q0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await oW(Z).then((j)=>j.isDirectory()).catch((j)=>{if(A2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:d6,filePath:q0(Z,d6)})}return J}catch(f){if(A2(f))return[];throw f}}async function i6($){if(E$($)===".cline"){let f=await fZ($);return(await Promise.all(f.map((W)=>i6(q0(W,"rules.md"))))).flat()}try{if((await oW($)).isFile())return[{directoryPath:JL($),fileName:E$($),filePath:$}]}catch(f){if(!A2(f))throw f}try{let J=(await eW($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&p6(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:q0($,Z.name)})),W=q0($,"AGENTS.md");try{if((await oW(W)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch(f){if(A2(f))return[];throw f}}async function BL($){if(E$($)===".cline"){let f=await fZ($);return(await Promise.all(f.map((W)=>i6(q0(W,jJ))))).flat()}return i6($)}function KJ($){let f=AL($),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?dH([...f,J]):f,discoverFiles:lH,includeFile:(W)=>W===d6,parseFile:(W)=>XJ(W.content,E$(W.directoryPath)),resolveId:(W)=>$Z(W.name)}}function GJ($){let f=$?.directories??VJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:i6,includeFile:(W,Z)=>W===".clinerules"||p6(W)||p6(Z),parseFile:(W)=>HJ(W.content,VL(W,$?.workspacePath)),resolveId:(W)=>$Z(W.name)}}function PJ($){let f=$?.directories??BJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:BL,includeFile:(W)=>p6(W),parseFile:(W)=>YJ(W.content,E$(W.filePath,l6(W.filePath))),resolveId:(W)=>$Z(W.name)}}function pH($){let f=[KJ($?.skills),GJ($?.rules),PJ($?.workflows)];return new o1(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as rH}from"@cline/shared";function KL($,f){if($.description?.trim())return rH($.description,".");if(f==="workflow")return;return rH($.instructions,".")}function GL($){return $.disabled!==!0}function iH($,f){return[...$.getSnapshot(f).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>GL(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:KL(W.item,f),kind:f})).sort((J,W)=>J.name.localeCompare(W.name))}function UJ($){let f=new Map;for(let J of[...iH($,"workflow"),...iH($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,W)=>J.name.localeCompare(W.name))}function nH($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let W=J[1];if(!W)return $;let Z=W.length+1,Q=$.slice(Z),j=UJ(f).find((X)=>X.name===W);return j?`${j.instructions}${Q}`:$}var tH={};w(tH,{mergeRulesForSystemPrompt:()=>K2,loadRulesForSystemPromptFromWatcher:()=>WZ,listEnabledRulesFromWatcher:()=>aH,isRuleEnabled:()=>a6,formatRulesForSystemPrompt:()=>B2});function a6($){return $.disabled!==!0}function B2($){if($.length===0)return"";return`
184
+ </html>`;var uX="a8331954c0cf48ba99b5dd223a14c6ea",cX="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",dX="openid offline_access",H6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",lX="c1aba3deed5740659981a752714eba33",pX="https://login-ext.identity.oraclecloud.com",rX="openid offline_access",Y6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",iX="opc-request-id",TR="/auth/oca",NR=Array.from({length:11},($,f)=>48801+f),MR=300000,yR=30000,nX=30000,qR=600000;class A6 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 j1={internal:{clientId:uX,idcsUrl:cX,scopes:dX,baseUrl:H6},external:{clientId:lX,idcsUrl:pX,scopes:rX,baseUrl:Y6}},g8=new Map,wR=86400000,SR=300000,hR=32,TZ=new _Z(wR,hR);function aX($){if(typeof $==="function")return $();return $??"internal"}function tX($){return{internal:{clientId:$?.internal?.clientId??j1.internal.clientId,idcsUrl:$?.internal?.idcsUrl??j1.internal.idcsUrl,scopes:$?.internal?.scopes??j1.internal.scopes,baseUrl:$?.internal?.baseUrl??j1.internal.baseUrl},external:{clientId:$?.external?.clientId??j1.external.clientId,idcsUrl:$?.external?.idcsUrl??j1.external.idcsUrl,scopes:$?.external?.scopes??j1.external.scopes,baseUrl:$?.external?.baseUrl??j1.external.baseUrl}}}function CR($=Date.now()){let f=$-qR;for(let[J,W]of g8.entries())if(W.createdAt<f)g8.delete(J)}function ER($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=z0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=z0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function sX($,f,J){let W=$.access_token;if(!W)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let Q=z0($.id_token),j=z0(W),X=Q?.sub??j?.sub,H=Q?.email??j?.email;return{access:W,refresh:Z,expires:ER($,W,$.id_token),accountId:X??J?.accountId,email:H??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function oX($,f){let J=l4($),W=TZ.get(J);if(W)return W;let Z=`${J}/.well-known/openid-configuration`,Q=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!Q.ok){let H=`${J}/oauth2/v1/token`;return TZ.set(J,H,Date.now(),SR),H}let X=(await Q.json()).token_endpoint||`${J}/oauth2/v1/token`;return TZ.set(J,X),X}function eX($){return{code:$.error,message:$.error_description}}async function bR($){let f=g8.get($.state);if(!f)throw Error("No PKCE verifier found for this state");g8.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,W=await oX(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),Q=await fetch(W,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await Q.json();if(!Q.ok){let H=eX(j);throw new A6(`Token exchange failed: ${Q.status}${H.message?` - ${H.message}`:""}`,{status:Q.status,errorCode:H.code})}let X=z0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return sX(j,$.mode)}function kR($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${l4(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function f2($){L$($.telemetry,"oca");let f=tX($.config),J=aX($.mode),W=$.callbackPorts?.length?$.callbackPorts:NR,Z=$.callbackPath??TR,Q=$.requestTimeoutMs??nX,j=await e0({ports:W,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let H=vX(16),Y=vX(16),{verifier:A,challenge:V}=await d4();CR(),g8.set(H,{verifier:A,nonce:Y,mode:J,redirectUri:X,createdAt:Date.now()});let B=kR({callbackUrl:X,mode:J,state:H,nonce:Y,challenge:V,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await df({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==H)throw Error("State mismatch");let P=await bR({code:G,state:R,mode:J,config:f,requestTimeoutMs:Q});return z$($.telemetry,"oca"),_$($.telemetry,{id:P.accountId,email:P.email,provider:"oca"}),P}catch(K){throw O$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function v8($,f={}){let J=tX(f.config),W=f.requestTimeoutMs??nX,Z=$.metadata?.mode,Q=Z==="internal"||Z==="external"?Z:aX(f.mode),j=Q==="external"?J.external:J.internal,X=await oX(j.idcsUrl,W),H=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(W)}),A=await Y.json();if(!Y.ok){let V=eX(A);throw new A6(`Token refresh failed: ${Y.status}${V.message?` - ${V.message}`:""}`,{status:Y.status,errorCode:V.code})}return sX(A,Q,$)}async function u8($,f,J){if(!$)return null;let W=f?.refreshBufferMs??J?.refreshBufferMs??MR,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??yR;if(f?.forceRefresh!==!0&&!u1($,W))return $;try{return await v8($,J)}catch(j){if(j instanceof A6&&j.isLikelyInvalidGrant())return p$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function NZ($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return f2({...$,callbacks:f})},async refreshToken(f){return v8(f,$)},getApiKey(f){return f.access}}}async function V6($,f){let J=new TextEncoder,W=async(Y)=>{let A=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(A).slice(0,4),(V)=>V.toString(16).padStart(2,"0")).join("")},[Z,Q]=await Promise.all([W(f),W($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),X=new Uint32Array(1);crypto.getRandomValues(X);let H=(X[0]??0).toString(16).padStart(8,"0");return Z+Q+j+H}async function MZ($){let f=await V6($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[iX]:f}}var XH={};w(XH,{resolveProviderConfig:()=>l8,getProviderConfig:()=>z6,getLiveModelsCatalog:()=>J2,clearPublicModelsCatalogCache:()=>JD,clearPrivateModelsCatalogCache:()=>CZ,clearLiveModelsCatalogCache:()=>hZ,OPENAI_COMPATIBLE_PROVIDERS:()=>d8,DEFAULT_MODELS_CATALOG_URL:()=>F6});import*as H0 from"@cline/llms";function yZ($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let W of[J.id,J.name,J.model])if(typeof W==="string"&&W.trim())return W.trim()}return""}).filter((f)=>f.length>0)}function IR($,f){let J=yZ($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let W=$,Z=yZ(W.data??W.models);if(Z.length>0)return Z;if(W.models&&typeof W.models==="object"&&!Array.isArray(W.models)){let j=Object.keys(W.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let Q=W.providers?.[f];if(Q&&typeof Q==="object"){let X=yZ(Q.models??Q);if(X.length>0)return X}return[]}async function B6($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return IR(await J.json(),f)}function fH($){return $.replace(/\/+$/,"")}function K6($,f,J){let W=J?.trim();if(!W)return;let Z=$?.trim();if(!Z||!f?.trim())return W;try{let Q=new URL(W),j=new URL(f),X=new URL(Z);if(Q.origin!==j.origin)return W;let H=fH(j.pathname),Y=fH(X.pathname);if(H&&Q.pathname.startsWith(`${H}/`)){let A=Q.pathname.slice(H.length);X.pathname=`${Y}${A}`}else X.pathname=Q.pathname;return X.search=Q.search,X.hash=Q.hash,X.toString()}catch{return W}}function xR($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function mR($){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 gR=Object.values(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:xR($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),WH=Object.fromEntries(gR.map(($)=>[$.id,$]));function vR($){return WH[$]}function uR(){return Object.fromEntries(Object.entries(WH).filter(([,$])=>mR($)))}function ZH($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var F6="https://models.dev/api.json",cR=600000,QH=300000,dR=5000,U6=new Map,c8=new Map,qZ=new Map,G6=new Map;async function lR(){return H0.getGeneratedProviderModels()}async function pR($,f={},J={},W={},Z={},Q={}){let j=await lR(),X=H0.resolveProviderModelCatalogKeys($),H=Object.assign({},...X.map((V)=>j[V]??{})),Y=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),A=Object.keys(Z).length>0;if(Y&&A)return H0.sortModelsByReleaseDate({...Z,...Q});if($==="openai-codex")return H0.sortModelsByReleaseDate({...f,...H0.filterOpenAICodexModels(J),...Z,...Q});return H0.sortModelsByReleaseDate({...H,...f,...J,...W,...Z,...Q})}function rR($,f){let J=H0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((W)=>f[W]??{}))}function R6($){let f=$?.trim();return f&&f.length>0?f:""}function SZ($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function iR($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function nR($,f){return`${$}:${R6(f.baseUrl)}:${iR(SZ(f)??"")}`}async function D6($,f,J=dR){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await fetch($,{...f,signal:W.signal})}finally{clearTimeout(Z)}}function s1($,f,J){if(J&&!$.includes(f))$.push(f)}function L6($,f){let J=["streaming","tools"];return s1(J,"images",Boolean(f.supportsImages)),s1(J,"prompt-cache",Boolean(f.supportsPromptCache)),s1(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function aR($,f){let J=await D6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let H=j.supported_features??[];Q[X]=L6(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:H.includes("reasoning")||H.includes("reasoning_effort"),supportsImages:!1})}return Q}function JH($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function tR($,f){let J=await D6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],Q={};for(let j of Z){let X=j.id?.trim();if(!X)continue;Q[X]=L6(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return Q}async function sR($,f){let W=`${(R6($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await D6(W,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let H of j){let Y=H.id?.trim();if(!Y)continue;let A=H.supported_features??[],V=H.supported_sampling_parameters??[],B=H.input_modalities??[],K=["streaming"];s1(K,"tools",A.includes("tools")),s1(K,"reasoning",A.includes("reasoning")),s1(K,"temperature",V.includes("temperature")),s1(K,"images",B.includes("image"));let G={input:JH(H.pricing?.prompt),output:JH(H.pricing?.completion)};X[Y]={id:Y,name:H.name??Y,description:H.description,contextWindow:H.context_length,maxInputTokens:H.context_length,maxTokens:H.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function oR($){let f=R6($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function eR($,f){let W=`${oR($.baseUrl)}/v1/model/info`,Z=async(Y)=>D6(W,{method:"GET",headers:{accept:"application/json",...Y}}),Q=await Z({"x-litellm-api-key":f});if(!Q.ok)Q=await Z({Authorization:`Bearer ${f}`});if(!Q.ok)throw Error(`LiteLLM model refresh failed: HTTP ${Q.status}`);let X=(await Q.json())?.data??[],H={};for(let Y of X){let A=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||A;if(!B)continue;let K=Y.model_info,G=L6(B,{name:A??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(H[B]=G,A)H[A]={...G,id:A,name:A}}return H}var jH={baseten:aR,hicap:tR,litellm:eR,poolside:sR},wZ=new Map,P6=new Map;function $D($,f){return`${$}:${R6(f.baseUrl)}`}async function fD($,f,J){let W=H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=K6(J.baseUrl,W?.provider.baseUrl,W?.provider.modelsSourceUrl);if(!Z)return{};let Q=f?.cacheTtlMs??QH,j=$D($,J),X=Date.now(),H=wZ.get(j);if(H&&H.expiresAt>X)return H.data;let Y=P6.get(j);if(Y)return Y;let A=B6(Z,$).then((V)=>{let B=Object.fromEntries(V.map((K)=>[K,L6(K,{name:K})]));return wZ.set(j,{data:B,expiresAt:X+Q}),B}).finally(()=>{P6.delete(j)});return P6.set(j,A),A}function JD(){wZ.clear(),P6.clear()}async function WD($,f){let J=SZ(f);if(!J)return{};let W=jH[$];if(!W)return{};return W(f,J)}function ZD($,f,J){if(!J)return!1;if(!jH[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(SZ(J))}async function QD($,f,J){let W=f?.cacheTtlMs??QH,Z=nR($,J),Q=Date.now(),j=qZ.get(Z);if(j&&j.expiresAt>Q)return j.data;let X=G6.get(Z);if(X)return X;let H=WD($,J).then((Y)=>{return qZ.set(Z,{data:Y,expiresAt:Q+W}),Y}).finally(()=>{G6.delete(Z)});return G6.set(Z,H),H}async function jD($){return H0.fetchModelsDevProviderModels($,globalThis.fetch)}async function J2($={}){let f=$.url??F6,J=$.cacheTtlMs??cR,W=Date.now(),Z=U6.get(f);if(Z&&Z.expiresAt>W)return Z.data;let Q=c8.get(f);if(Q)return Q;let j=jD(f).then((X)=>{return U6.set(f,{data:X,expiresAt:W+J}),X}).finally(()=>{c8.delete(f)});return c8.set(f,j),j}function hZ($){if($){U6.delete($),c8.delete($);return}U6.clear(),c8.clear()}function CZ(){qZ.clear(),G6.clear()}function XD($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:ZH(J.capabilities)}]))}var d8=XD(uR());function z6($){let f=vR($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:ZH(f.capabilities)}}async function l8($,f,J){let W=z6($);if(!W)return;try{let Z=f?.loadLatestOnInit?await J2(f):void 0,Q=Z?rR($,Z):{},j=J&&ZD($,f,J)?await QD($,f,J):{},H=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:W.modelId,baseUrl:W.baseUrl}:J,Y=H?await fD($,f,H).catch(()=>({})):{},A=await pR($,W.knownModels,Q,j,Y,J?.knownModels);return{...W,knownModels:A}}catch(Z){if(f?.failOnError)throw Z;return W}}var p8=x0.BUILT_IN_PROVIDER,EZ=x0.BUILT_IN_PROVIDER_IDS,bZ=x0.isBuiltInProviderId,W2=x0.normalizeProviderId,r8=y.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),O6=y.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),_6=y.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),T6=y.object({apiKey:y.string().optional(),accessToken:y.string().optional(),refreshToken:y.string().optional(),expiresAt:y.number().int().positive().optional(),accountId:y.string().optional()}),HD=y.enum(["none","low","medium","high","xhigh"]),N6=y.object({enabled:y.boolean().optional(),effort:HD.optional(),budgetTokens:y.number().int().positive().optional()}),M6=y.object({accessKey:y.string().optional(),secretKey:y.string().optional(),sessionToken:y.string().optional(),region:y.string().optional(),profile:y.string().optional(),authentication:y.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:y.boolean().optional(),useCrossRegionInference:y.boolean().optional(),useGlobalInference:y.boolean().optional(),endpoint:y.string().url().optional(),customModelBaseId:y.string().optional()}),y6=y.object({projectId:y.string().optional(),region:y.string().optional()}),q6=y.object({apiVersion:y.string().optional(),useIdentity:y.boolean().optional()}),w6=y.object({clientId:y.string().optional(),clientSecret:y.string().optional(),tokenUrl:y.string().url().optional(),resourceGroup:y.string().optional(),deploymentId:y.string().optional(),useOrchestrationMode:y.boolean().optional(),api:y.enum(["orchestration","foundation-models"]).optional(),defaultSettings:y.record(y.string(),y.unknown()).optional()}),S6=y.object({mode:y.enum(["internal","external"]).optional(),usePromptCache:y.boolean().optional()}),h6=y.object({loadLatestOnInit:y.boolean().optional(),loadPrivateOnAuth:y.boolean().optional(),url:y.string().url().optional(),cacheTtlMs:y.number().int().positive().optional(),failOnError:y.boolean().optional()}),X1=y.object({provider:r8,apiKey:y.string().optional(),auth:T6.optional(),model:y.string().optional(),protocol:O6.optional(),client:_6.optional(),routingProviderId:r8.optional(),maxTokens:y.number().int().positive().optional(),contextWindow:y.number().int().positive().optional(),baseUrl:y.string().url().optional(),headers:y.record(y.string(),y.string()).optional(),timeout:y.number().int().positive().optional(),reasoning:N6.optional(),aws:M6.optional(),gcp:y6.optional(),azure:q6.optional(),sap:w6.optional(),oca:S6.optional(),region:y.string().optional(),apiLine:y.enum(["china","international"]).optional(),capabilities:y.array(y.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:h6.optional()});function C6($){return X1.parse($)}function E6($){return X1.safeParse($)}function YD($){return $.protocol==="openai-responses"||$.client==="openai"}function m0($,f={}){let J=$.provider,W=W2(J),Z=f.includeKnownModels!==!1,Q=$.reasoning?.effort||"none",j=Q==="none"?void 0:Q,X=d8[W],H=Object.assign({},...x0.resolveProviderModelCatalogKeys(W).map((R)=>x0.getGeneratedModelsForProvider(R))),Y=Object.keys(H)[0],A=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,V=$.baseUrl??(W==="oca"?$.oca?.mode==="internal"?H6:Y6:X?.baseUrl),B=$.routingProviderId??(YD($)&&W!==p8.OPENAI_NATIVE?p8.OPENAI_NATIVE:void 0),K=Z?X?.knownModels??(Object.keys(H).length>0?H:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??Y??"default",...Z?{knownModels:K}:{},apiKey:A,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:V,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,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??X?.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(G).filter(([R,P])=>P!==void 0))}function kZ($){let f=C6($);return m0(f)}function IZ($){let f=E6($);if(f.success)return{success:!0,config:m0(f.data)};return{success:!1,error:f.error}}var i8=X1;var b6=H1.object({settings:X1,updatedAt:H1.string().datetime(),tokenSource:H1.enum(["manual","oauth","migration"]).default("manual")}),Z2=H1.object({version:H1.literal(1),lastUsedProvider:H1.string().min(1).optional(),providers:H1.record(H1.string(),b6)});function Y1(){return{version:1,providers:{}}}X$();var KH={};w(KH,{InMemoryWorkspaceManager:()=>j2});import{upsertWorkspaceInfo as KD,WorkspaceManifestSchema as mZ}from"@cline/shared";var BH={};w(BH,{normalizeWorkspacePath:()=>C$,generateWorkspaceInfoWithDiagnostics:()=>n8,generateWorkspaceInfo:()=>Q2,buildWorkspaceMetadataWithInfo:()=>xZ,buildWorkspaceMetadata:()=>a8});import{basename as AD,resolve as VD}from"node:path";import{performance as AH}from"node:perf_hooks";import{processWorkspaceInfo as VH}from"@cline/shared";import BD from"simple-git";function C$($){return VD($)}async function Q2($){return(await n8($)).info}function k6($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function n8($){let f=C$($),J={rootPath:f,hint:AD(f)},W;try{let Z=BD({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((H)=>{let Y=H.refs.fetch||H.refs.push;return`${H.name}: ${Y}`});J.associatedRemoteUrls=X}}catch(j){W??=k6(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){W??=k6(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){W??=k6(j)}return{info:J,vcsType:"git",error:W}}catch(Z){return{info:J,vcsType:"none",error:k6(Z)}}}async function a8($){let f=await Q2($);return VH(f)}async function xZ($){let f=AH.now(),J=await n8($),W=AH.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:VH(Z),durationMs:W,vcsType:J.vcsType,initError:J.error}}class j2{manifest;listeners=new Set;constructor($){this.manifest=mZ.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await Q2($);return this.manifest=KD(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=C$($),J=this.manifest.workspaces[f];if(J)return this.manifest=mZ.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let W=await this.addWorkspacePath(f);return this.manifest=mZ.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 f=C$($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}L0();import{createHash as GD}from"node:crypto";var GH=new Set,PH=new Set;function PD($){return GD("sha256").update($).digest("hex")}function UD($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function UH($){if(!$.telemetry)return;let f=PD($.rootPath),J=$.rootCount??1;if(!GH.has(f))GH.add(f),A4($.telemetry,{root_count:J,vcs_types:UD($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!PH.has(f)){PH.add(f);let W=Error($.initError.message);W.name=$.initError.errorType||"Error",V4($.telemetry,W,{fallback_to_single_root:!0,workspace_count:J})}}function RD($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function DD($,f,J){if(f.length>0)for(let Q of f)J?.log(Q.message,{severity:"warn"});if($.length===0)return;let W=$.slice(0,3).map(RD).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${W}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let Q of $)J?.log(`Plugin initialization failed (${Q.phase}) for ${Q.pluginPath}`,{severity:"warn",stack:Q.stack,pluginPath:Q.pluginPath,pluginName:Q.pluginName})}function LD($,f){let J=typeof $.thinking==="boolean",W=typeof $.reasoningEffort==="string";if(!J&&!W)return f;return{...f??{},...J?{enabled:$.thinking}:{},...W?{effort:$.reasoningEffort}:{}}}function FH($,f){return FD($,f)}function zD($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function OD($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||_D($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function _D($){let f=$?.trim();if(!f)return;let J=z0(f),W=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let Q=J?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;return}function TD($,f,J,W,Z){let Q=J.getProviderSettings($.providerId),j=W||Q?.modelCatalog?{...W??{},...Q?.modelCatalog??{}}:void 0,X={...Q??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??Q?.apiKey,baseUrl:$.baseUrl??Q?.baseUrl,headers:$.providerId==="openai-codex"?OD({sessionId:f,configHeaders:$.headers,storedHeaders:Q?.headers,accountId:Q?.auth?.accountId,accessToken:$.apiKey??Q?.auth?.accessToken??Q?.apiKey}):$.headers??Q?.headers,reasoning:LD($,Q?.reasoning),modelCatalog:j},H=m0(X);if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let A=$.fetch??H.fetch??Z;if(A)H.fetch=A;return H}async function RH($){let{input:f,sessionId:J,providerSettingsManager:W,defaultTelemetry:Z,defaultCapabilities:Q,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:H,onTeamEvent:Y,createSpawnTool:A,localRuntime:V,readSessionMetadata:B,writeSessionMetadata:K}=$,G=J1(f.config),{modelCatalogDefaults:R,userInstructionService:P,configExtensions:U,onTeamRestored:F,...O}=V??{},_=Object.keys(O).length>0?O:void 0,{workspaceInfo:D,workspaceMetadata:z,durationMs:N,vcsType:q,initError:$0}=await xZ(G),A0=_?.extensionContext,o={...A0??{},workspace:{...D,...A0?.workspace??{}},session:{...A0?.session??{},sessionId:J},logger:A0?.logger??_?.logger,telemetry:A0?.telemetry??_?.telemetry??Z};UH({telemetry:o.telemetry,rootPath:D.rootPath,workspaceInfo:D,rootCount:1,vcsType:q,durationMs:N,initError:$0,featureFlagEnabled:!0});let V0=$2({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:_?.logger,workspaceInfo:D}),i=uj(_?.hooks)?void 0:ef({rootSessionId:J,workspacePath:G,workspaceInfo:D}),W$=t1([_?.hooks,i]),p;if(FH(U,"plugins"))try{p=await tf({pluginPaths:_?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:H,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:D,session:o.session,client:o.client,user:o.user,logger:o.logger,telemetry:o.telemetry,automation:o.automation}),DD(p.failures,p.warnings,_?.logger)}catch(p2){let r=p2 instanceof Error?p2.message:String(p2);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${r})`)}let k=tW(V0?[V0]:void 0,tW(_?.extensions,t4(p?.extensions))),D0=FH(U,"plugins")?r1(p?.pluginPaths??[]):void 0,n={...f.config,..._??{},sessionId:J,hooks:W$,extensions:k,extensionContext:o,telemetry:o.telemetry},t0=TD(n,J,W,R,X),T1=t1([n.hooks,n.checkpoint?.enabled===!0?wX({cwd:n.cwd,sessionId:J,logger:n.logger,createCheckpoint:n.checkpoint?.createCheckpoint,initialRunCount:zD(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),N1={...n,providerConfig:t0,workspaceMetadata:z,hooks:T1},_f=f.toolPolicies??n.toolPolicies??j,l2=F0(Q,f.capabilities),H4=l2?.requestToolApproval,VW=l2?.toolExecutors,Tf=new j2({currentWorkspacePath:D.rootPath,workspaces:{[D.rootPath]:D}});return{effectiveInput:f,config:N1,providerConfig:t0,workspaceMetadata:z,workspaceInfo:D,extensions:k,hooks:T1,toolPolicies:_f,requestToolApproval:H4,pluginSandboxShutdown:p?.shutdown,runtimeBuilderInput:{config:N1,hooks:T1,extensions:k,onTeamEvent:Y,createSpawnTool:A,onTeamRestored:F,userInstructionService:P,pluginSkillDirectories:D0,configExtensions:U,toolExecutors:VW,workspaceManager:Tf,logger:N1.logger,telemetry:N1.telemetry}}}import{existsSync as x6,mkdirSync as ND,readdirSync as MD,rmdirSync as yD,rmSync as qD,unlinkSync as wD}from"node:fs";import{dirname as DH,join as I6}from"node:path";function s(){return new Date().toISOString()}function t8($){if(!$||!x6($))return;try{wD($)}catch{}}function SD($){let f=mf($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=z8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class gZ{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return I6(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!x6(f))ND(f,{recursive:!0});return f}sessionMessagesPath($){return I6(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return I6(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!x6(f)){f=DH(f);continue}try{if(MD(f).length>0)break;yD(f)}catch{break}f=DH(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!x6($))return;try{qD($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:W,fileStem:Z}=SD($),Q=this.sessionArtifactsDir(W);return{messagesPath:I6(Q,`${Z}.messages.json`)}}}import{resolveDocumentsExtensionPath as hD}from"@cline/shared/storage";L0();function LH($,f,J,W,Z){if(J)K4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else B4($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});CD($.telemetry,{workspacePath:W})}function CD($,f){let J=hD("Hooks"),W=Z1(f.workspacePath),Z=new Map;for(let Q of W){let j=Q.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(Q.path===J||Q.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[Q,j]of Z.entries())_4($,Q,j.global,j.workspace)}function zH($,f){for(let J of f.mentions)z4($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)D4($,"file",J.length);for(let J of f.ignoredMentions)L4($,"file","not_found",J)}var PK={};w(PK,{ProviderSettingsManager:()=>R$});import{chmodSync as FK,existsSync as y7,mkdirSync as AS,readFileSync as VS,writeFileSync as BS}from"node:fs";import{basename as RK,dirname as q7}from"node:path";import{resolveProviderSettingsPath as KS}from"@cline/shared/storage";var T={};w(T,{writeHubDiscovery:()=>K5,writeGlobalSettings:()=>h$,withHubStartupLock:()=>G5,verifyHubConnection:()=>V$,updateMcpServerOAuthState:()=>Jf,updateLocalProvider:()=>s5,uninstallPlugin:()=>$7,truncateNotificationBody:()=>sJ,toggleDisabledTool:()=>n4,toTeamProgressLifecycleEvent:()=>T2,toProviderConfig:()=>m0,toHubHealthUrl:()=>k9,toHookConfigFileName:()=>x8,summarizeUsageFromMessages:()=>vf,stopLocalHubServerGracefully:()=>i9,startLocalOAuthServer:()=>e0,startHubWebSocketServer:()=>Df,startHubServer:()=>KB,startClineDeviceAuth:()=>pZ,splitCoreSessionConfig:()=>_J,spawnDetachedHubServerWithRetry:()=>D2,spawnDetachedHubServer:()=>u9,setTelemetryOptOutGlobally:()=>tj,setMcpServerDisabled:()=>$f,setDisabledTools:()=>WZ,setDisabledPlugin:()=>JX,setAutoUpdateEnabledGlobally:()=>oj,sendHubCommand:()=>RV,saveLocalProviderSettings:()=>H7,saveLocalProviderOAuthCredentials:()=>B7,sanitizeSessionToken:()=>m1,safeParseSettings:()=>E6,safeCreateProviderConfig:()=>IZ,runSubprocessEvent:()=>q2,runHook:()=>S2,reviveTeamStateDates:()=>x4,restartLocalHubIfIdleAfterStartupTimeout:()=>F5,resolveWorkspaceHubOwnerContext:()=>UA,resolveWorkflowsConfigSearchPaths:()=>BJ,resolveSkillsConfigSearchPaths:()=>AJ,resolveSharedHubOwnerContext:()=>Y0,resolveSessionBackend:()=>BQ,resolveRulesConfigSearchPaths:()=>VJ,resolveProviderConfig:()=>l8,resolvePluginSkillDirectoriesFromPaths:()=>r1,resolvePluginConfigSearchPaths:()=>E8,resolveMcpServerRegistrations:()=>H$,resolveLocalClineAuthToken:()=>K7,resolveHubUrl:()=>FQ,resolveHubOwnerContext:()=>x$,resolveHubEndpointOptions:()=>d0,resolveHubBuildId:()=>U1,resolveHooksConfigSearchPaths:()=>k8,resolveDisabledToolNames:()=>j$,resolveDisabledPluginPaths:()=>q8,resolveDefaultMcpSettingsPath:()=>_0,resolveDefaultHubPort:()=>R2,resolveDefaultHubPathname:()=>v9,resolveDefaultHubHost:()=>g9,resolveCoreSelectedToolIds:()=>g4,resolveCompatibleLocalHubUrl:()=>gJ,resolveClineDir:()=>BA,resolveClineDataDir:()=>kJ,resolveAndLoadAgentPlugins:()=>tf,resolveAgentPluginPaths:()=>p1,requestHubShutdown:()=>mJ,requestDesktopToolApproval:()=>rQ,rememberRecoverableLocalHubUrl:()=>F1,registerRemoteConfigSessionBlobUpload:()=>v5,registerMcpServersFromSettingsFile:()=>Wf,registerDisposable:()=>jS,refreshProviderModelsFromSource:()=>Y7,refreshOpenAICodexToken:()=>JJ,refreshOcaToken:()=>v8,refreshClineToken:()=>$J,readSessionCheckpointHistory:()=>oJ,readRemoteConfigSessionBlobUploadMetadata:()=>xQ,readHubDiscovery:()=>K0,readGlobalSettings:()=>O0,probeHubServer:()=>A$,probeHubConnection:()=>FV,prewarmFileIndex:()=>S4,prewarmDetachedHubServer:()=>P5,prepareRemoteConfigCoreIntegration:()=>gQ,parseWorkflowConfigFromMarkdown:()=>YJ,parseUserCommandEnvelope:()=>QS,parseSkillConfigFromMarkdown:()=>XJ,parseSettings:()=>C6,parseRuleConfigFromMarkdown:()=>HJ,parseHookEventPayload:()=>w2,openaiCodexOAuthProvider:()=>tZ,normalizeWorkspacePath:()=>C$,normalizeUserInput:()=>ZS,normalizeSdkError:()=>WS,normalizeRuntimeCapabilities:()=>F0,normalizeProviderId:()=>W2,normalizeOpenAICodexCredentials:()=>aZ,normalizeOAuthProvider:()=>A7,normalizeHubWebSocketUrl:()=>R1,noopBasicLogger:()=>JS,migrateLegacyProviderSettings:()=>Q4,mergeRulesForSystemPrompt:()=>K2,mergeAgentHooks:()=>t1,makeTeamTaskSubSessionId:()=>L8,makeSubSessionId:()=>xf,loginOpenAICodex:()=>Y2,loginOcaOAuth:()=>f2,loginLocalProvider:()=>V7,loginClineOAuth:()=>H2,loadOpenTelemetryAdapter:()=>lw,loadMcpSettingsFile:()=>e1,loadLlmsConfigFromFile:()=>T7,loadAgentPluginsFromPathsWithDiagnostics:()=>l1,loadAgentPluginsFromPaths:()=>o4,loadAgentPluginFromPath:()=>h8,listSessionHistoryFromBackend:()=>h9,listPluginToolsWithDiagnostics:()=>Z5,listPluginTools:()=>zJ,listMcpServerOAuthStatuses:()=>DJ,listLocalProviders:()=>j7,listHookConfigFiles:()=>Z1,isToolDisabledGlobally:()=>ej,isTelemetryOptedOutGlobally:()=>i4,isSessionNotFoundError:()=>I$,isRuleEnabled:()=>a6,isPluginDisabledGlobally:()=>fX,isOpenAICodexTokenExpired:()=>nZ,isHubReconnectableTransportError:()=>p9,isHubCommandTimeoutError:()=>U5,isDiscoveryFilePresent:()=>GA,isClineAccountActionRequest:()=>m6,isBuiltInProviderId:()=>bZ,isAutoUpdateEnabledGlobally:()=>sj,identifyAccount:()=>_$,hasMcpSettingsFile:()=>b$,getValidOpenAICodexCredentials:()=>WJ,getValidOcaCredentials:()=>u8,getValidClineCredentials:()=>fJ,getProviderConfigFields:()=>G7,getProviderConfig:()=>z6,getMcpServerOAuthState:()=>ff,getLocalProviderModels:()=>X7,getLiveModelsCatalog:()=>J2,getFileIndex:()=>y$,getCurrentContextSize:()=>$Z,getCoreHeadlessToolNames:()=>D8,getCoreDefaultEnabledToolIds:()=>m4,getCoreBuiltinToolCatalog:()=>I1,getCoreAcpToolNames:()=>v4,getClineDefaultSystemPrompt:()=>rw,generateWorkspaceInfoWithDiagnostics:()=>n8,generateWorkspaceInfo:()=>Q2,generateOcaOpcRequestId:()=>V6,formatRulesForSystemPrompt:()=>B2,formatDisplayUserInput:()=>fS,filterExtensionToolRegistrations:()=>t4,filterDisabledTools:()=>c1,filterDisabledPluginPaths:()=>a4,fetchClineRecommendedModels:()=>O7,executeClineAccountAction:()=>g6,ensureHubWebSocketServer:()=>I5,ensureHubServer:()=>GB,ensureDetachedHubServer:()=>RA,ensureCustomProvidersLoaded:()=>n5,ensureCompatibleLocalHubUrl:()=>Vf,enrichPromptWithMentions:()=>qf,emptyWorkspaceManifest:()=>$S,emptyStoredProviderSettings:()=>Y1,discoverPluginModulePaths:()=>b8,deriveSubsessionStatus:()=>O8,deleteLocalProvider:()=>o5,defineLlmsConfig:()=>_7,createWorkflowsConfigDefinition:()=>PJ,createUserInstructionConfigService:()=>V1,createToolPoliciesWithPreset:()=>C4,createTool:()=>ew,createTeamName:()=>c5,createSubprocessHooks:()=>M5,createSpawnAgentTool:()=>$1,createSkillsConfigDefinition:()=>KJ,createSessionHost:()=>y2,createRuntimeHost:()=>y2,createRulesConfigDefinition:()=>GJ,createRemoteConfigSessionMessagesArtifactUploader:()=>mQ,createProviderConfig:()=>kZ,createOpenTelemetryTelemetryService:()=>tJ,createOcaRequestHeaders:()=>MZ,createOcaOAuthProvider:()=>NZ,createOAuthClientCallbacks:()=>e8,createMcpTools:()=>U2,createLocalHubScheduleRuntimeHandlers:()=>x5,createLlmsSdk:()=>M7,createInitialAccumulatedUsage:()=>B0,createInMemoryHubOwnerContext:()=>KA,createHubServerUrl:()=>$$,createHubAuthToken:()=>B5,createHookConfigFileHooks:()=>m8,createHookConfigFileExtension:()=>$2,createHookAuditHooks:()=>ef,createDisabledMcpToolPolicy:()=>LJ,createDisabledMcpToolPolicies:()=>W5,createDelegatedAgentConfigProvider:()=>Ef,createDelegatedAgent:()=>bf,createDefaultToolsWithPreset:()=>E4,createDefaultTools:()=>s$,createDefaultMcpServerClientFactory:()=>P2,createDefaultExecutors:()=>wf,createCoreSettingsService:()=>Qf,createCoreSessionSnapshot:()=>B$,createContributionRegistry:()=>ow,createContextCompactionPrepareTurn:()=>$8,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,createClineTelemetryServiceMetadata:()=>sw,createClineTelemetryServiceConfig:()=>tw,createClineOAuthProvider:()=>iZ,createBuiltinTools:()=>x1,createAgentTeamsTools:()=>k1,createAgentRuntime:()=>YS,createAgentHooksExtension:()=>sf,connectToHub:()=>S5,completeClineDeviceAuth:()=>rZ,clearPrivateModelsCatalogCache:()=>CZ,clearLiveModelsCatalogCache:()=>hZ,clearHubDiscovery:()=>c0,captureWorkspacePathResolved:()=>r7,captureWorkspaceInitialized:()=>A4,captureWorkspaceInitError:()=>V4,captureToolUsage:()=>U4,captureTokenUsage:()=>G4,captureTaskRestarted:()=>K4,captureTaskCreated:()=>B4,captureTaskCompleted:()=>r2,captureSubagentExecution:()=>n2,captureSkillUsed:()=>F4,captureSdkError:()=>aw,captureProviderConfigured:()=>i7,captureProviderApiError:()=>i2,captureModeSwitch:()=>P4,captureMentionUsed:()=>D4,captureMentionSearchResults:()=>z4,captureMentionFailed:()=>L4,captureHookDiscovery:()=>_4,captureExtensionActivated:()=>p7,captureDiffEditFailure:()=>R4,captureConversationTurnEvent:()=>Nf,captureCompactionSkipped:()=>N4,captureCompactionExecuted:()=>T4,captureAuthSucceeded:()=>z$,captureAuthStarted:()=>L$,captureAuthLoggedOut:()=>p$,captureAuthFailed:()=>O$,captureAgentTeamCreated:()=>O4,captureAgentCreated:()=>r$,buildWorkspaceMetadata:()=>a8,buildTeamProgressSummary:()=>_2,buildSdkErrorProperties:()=>iw,buildRemoteConfigSessionBlobUploadMetadata:()=>m5,buildDelegatedAgentConfig:()=>E1,bootstrapAgentTeams:()=>If,authorizeMcpServerOAuth:()=>$5,addLocalProvider:()=>Q7,accumulateUsageTotals:()=>X0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>jJ,UnifiedConfigFileWatcher:()=>o1,ToolPresets:()=>I0,TelemetryService:()=>E2,TelemetryLoggerSink:()=>aJ,TEAM_TOOL_NAMES:()=>kf,SubprocessSandbox:()=>nf,StoredProviderSettingsSchema:()=>Z2,StoredProviderSettingsEntrySchema:()=>b6,SqliteTeamStore:()=>Lf,SqliteSessionStore:()=>G$,SessionVersioningService:()=>O1,SessionVersioningError:()=>S0,SessionSource:()=>G0,SessionNotFoundError:()=>k$,SapSettingsSchema:()=>w6,SKILLS_CONFIG_DIRECTORY_NAME:()=>QJ,SESSION_STATUSES:()=>_8,SESSION_NOT_FOUND_ERROR_CODE:()=>jf,SDK_ERROR_TELEMETRY_EVENT:()=>XS,RpcClineAccountService:()=>o8,RemoteRuntimeHost:()=>O2,ReasoningSettingsSchema:()=>N6,RULES_CONFIG_DIRECTORY_NAME:()=>n6,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>g5,ProviderSettingsSchema:()=>X1,ProviderSettingsManager:()=>R$,ProviderProtocolSchema:()=>O6,ProviderIdSchema:()=>r8,ProviderClientSchema:()=>_6,OpenTelemetryProvider:()=>b2,OcaSettingsSchema:()=>S6,OPENAI_COMPATIBLE_PROVIDERS:()=>d8,NodeHubClient:()=>f$,NativeHubTransportAdapter:()=>J4,ModelCatalogSettingsSchema:()=>h6,LocalRuntimeHost:()=>F$,Llms:()=>pw,InMemoryWorkspaceManager:()=>j2,InMemoryMcpManager:()=>Zf,HubUIClient:()=>LQ,HubTransportError:()=>T0,HubSessionClient:()=>DQ,HubServerTransport:()=>x2,HubScheduleService:()=>C2,HubScheduleCommandService:()=>h2,HubRuntimeHost:()=>m$,HubCommandError:()=>L2,HookEventPayloadSchema:()=>N5,HookEventNameSchema:()=>T5,HookConfigFileName:()=>of,HOOK_CONFIG_FILE_EVENT_MAP:()=>I8,HOOKS_CONFIG_DIRECTORY_NAME:()=>Q6,GlobalSettingsSchema:()=>y8,GcpSettingsSchema:()=>y6,FileTeamPersistenceStore:()=>JW,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>HW,DefaultToolNames:()=>J0,DefaultRuntimeBuilder:()=>v2,DefaultLlmsSdk:()=>j4,DEFAULT_MODELS_CATALOG_URL:()=>F6,DEFAULT_HUB_PORT:()=>x9,DEFAULT_HUB_PATHNAME:()=>m9,DEFAULT_HUB_HOST:()=>I9,CoreSettingsService:()=>B1,CoreSessionService:()=>U$,ContributionRegistry:()=>nw,ClineCore:()=>iJ,ClineAccountService:()=>s8,ChatViewStateSchema:()=>L7,ChatSummarySchema:()=>XW,ChatSessionStatusSchema:()=>ZW,ChatSessionConfigSchema:()=>WW,ChatMessageSchema:()=>jW,ChatMessageRoleSchema:()=>QW,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>z7,BrowserWebSocketHubAdapter:()=>f4,BUILT_IN_PROVIDER_IDS:()=>EZ,BUILT_IN_PROVIDER:()=>p8,AzureSettingsSchema:()=>q6,AwsSettingsSchema:()=>M6,AuthSettingsSchema:()=>T6,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>M2,Agent:()=>HS,ALL_DEFAULT_TOOL_NAMES:()=>n$});M(T,rl);import*as pw from"@cline/llms";import{buildClineSystemPrompt as rw,buildSdkErrorProperties as iw,ContributionRegistry as nw,captureSdkError as aw,createClineTelemetryServiceConfig as tw,createClineTelemetryServiceMetadata as sw,createContributionRegistry as ow,createTool as ew,emptyWorkspaceManifest as $S,formatDisplayUserInput as fS,noopBasicLogger as JS,normalizeSdkError as WS,normalizeUserInput as ZS,parseUserCommandEnvelope as QS,registerDisposable as jS,SDK_ERROR_TELEMETRY_EVENT as XS}from"@cline/shared";import"@cline/shared/storage";var _H={};w(_H,{isClineAccountActionRequest:()=>m6,executeClineAccountAction:()=>g6,RpcClineAccountService:()=>o8,ClineAccountService:()=>s8});function ED($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function OH($,f,J){let W=ED(J);if(W)return W;let Z=f.trim();if(Z){let Q=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${Q}`}return`Cline account request failed with status ${$}`}class s8{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,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 f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let W=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(W)return W;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let W=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,Q=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...W??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),H;if(X.trim())try{H=JSON.parse(X)}catch{if(!j.ok)throw Error(OH(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(OH(j.status,X,H));if(typeof H==="object"&&H!==null){let Y=H;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(H===void 0||H===null)throw Error("Cline account response payload was empty");return H}finally{clearTimeout(Q)}}}function m6($){return $.action==="clineAccount"}async function g6($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class o8{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 f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}var TH={};w(TH,{createOAuthClientCallbacks:()=>e8});function e8($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((W)=>{$.onOpenUrlError?.({url:f,error:W})})}catch(W){$.onOpenUrlError?.({url:f,error:W})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}L0();var CH={};w(CH,{startClineDeviceAuth:()=>pZ,refreshClineToken:()=>$J,loginClineOAuth:()=>H2,getValidClineCredentials:()=>fJ,createClineOAuthProvider:()=>iZ,completeClineDeviceAuth:()=>rZ});import{getClineEnvironmentConfig as vZ}from"@cline/shared";var v6={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},qH={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},uZ="https://api.workos.com",bD="/auth",NH=Array.from({length:11},($,f)=>48801+f),kD=300000,ID=30000,X2=30000,xD=300,mD=5;class A1 extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 gD($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function cZ($,f,J={}){let W=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:gD($.expiresAt),accountId:W??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function dZ($){if(!$)return{};return typeof $==="function"?await $():$}function MH($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function yH($){await new Promise((f)=>setTimeout(f,$))}function lZ($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function wH($,f){let J=await fetch(v1(uZ,qH.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??X2)}),W=await J.json().catch(()=>({}));if(!J.ok)throw new A1(`Device authorization failed: ${J.status}${W.error_description?` - ${W.error_description}`:""}`,{status:J.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:MH(W.expires_in,xD),pollIntervalSeconds:MH(W.interval,mD)}}async function SH($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let W=await fetch(v1($.workosApiBaseUrl,qH.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)}),Z=await W.json().catch(()=>({}));if(W.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await yH(J*1000);break}case"slow_down":{J+=1,await yH(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new A1(Z.error_description||"WorkOS authorization failed",{status:W.status,errorCode:Z.error});default:throw new A1(`WorkOS token polling failed: ${W.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:W.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function hH($,f,J){let W={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(v1(f.apiBaseUrl,v6.register),{method:"POST",headers:{"Content-Type":"application/json",...await dZ(f.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(f.requestTimeoutMs??X2)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=cf(j);throw new A1(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let Q=await Z.json();return cZ(lZ(Q,"Invalid token exchange response"),J??f.provider)}async function vD($,f,J,W){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:W??J.provider},Q=await fetch(v1(J.apiBaseUrl,v6.token),{method:"POST",headers:{"Content-Type":"application/json",...await dZ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??X2)});if(!Q.ok){let X=await Q.text().catch(()=>""),H=cf(X);throw new A1(`Token exchange failed: ${Q.status}${H.message?` - ${H.message}`:""}`,{status:Q.status,errorCode:H.code})}let j=await Q.json();return cZ(lZ(j,"Invalid token exchange response"),W??J.provider)}async function H2($){L$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:NH,W=$.callbackPath??bD,Z=f?null:await e0({ports:J,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),Q=Z?.callbackUrl||`http://127.0.0.1:${J[0]??NH[0]}${W}`;try{let j;if(f){let X=vZ().workOsClientId,H=await wH(X,$);$.callbacks.onAuth({url:H.verificationUriComplete??H.verificationUri,instructions:`Enter this code in your browser: ${H.userCode}`});let Y=await SH({clientId:X,deviceCode:H.deviceCode,expiresInSeconds:H.expiresInSeconds,initialPollIntervalSeconds:H.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??X2,workosApiBaseUrl:uZ,onProgress:$.callbacks.onProgress});j=await hH(Y,$,$.provider)}else{let X=new URL(v1($.apiBaseUrl,v6.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",Q),X.searchParams.set("redirect_uri",Q),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let H,Y=$.provider,A=await df({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(A.error)throw Error(`OAuth error: ${A.error}`);if(H=A.code,Y=A.provider??Y,!H){let V=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=uf(V,{includeProvider:!0});H=B.code,Y=B.provider??Y}if(!H)throw Error("Missing authorization code");j=await vD(H,Q,$,Y)}return z$($.telemetry,$.provider??"cline"),_$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw O$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function pZ($){return await wH(vZ().workOsClientId,$)}async function rZ($){let f=$.provider??"cline";L$($.telemetry,f);try{let J=await SH({clientId:vZ().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??X2,workosApiBaseUrl:uZ}),W=await hH(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return z$($.telemetry,f),_$($.telemetry,{id:W.accountId,email:W.email,provider:f}),W}catch(J){throw O$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function $J($,f){let J=await fetch(v1(f.apiBaseUrl,v6.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await dZ(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??X2)});if(!J.ok){let Q=await J.text().catch(()=>""),j=cf(Q);throw new A1(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let W=await J.json(),Z=$.metadata?.provider??f.provider;return cZ(lZ(W,"Invalid token refresh response"),Z,$)}async function fJ($,f,J){if(!$)return null;let W=J?.refreshBufferMs??kD,Z=J?.retryableTokenGraceMs??ID;if(J?.forceRefresh!==!0&&!u1($,W))return $;try{return await $J($,f)}catch(j){if(j instanceof A1&&j.isLikelyInvalidGrant())return p$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function iZ($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return H2({...$,callbacks:f})},async refreshToken(f){return $J(f,$)},getApiKey(f){return`workos:${f.access}`}}}L0();var kH={};w(kH,{refreshOpenAICodexToken:()=>JJ,openaiCodexOAuthProvider:()=>tZ,normalizeOpenAICodexCredentials:()=>aZ,loginOpenAICodex:()=>Y2,isOpenAICodexTokenExpired:()=>nZ,getValidOpenAICodexCredentials:()=>WJ,OPENAI_CODEX_OAUTH_CONFIG:()=>e});import{nanoid as uD}from"nanoid";var e={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 u6 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.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 cD($,f,J=e.redirectUri){let W=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:e.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!W.ok)return{type:"failed"};let Z=await W.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function dD($){try{let f=await fetch(e.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:e.clientId}),signal:AbortSignal.timeout(e.httpTimeoutMs)});if(!f.ok){let W=await f.text().catch(()=>""),Z=cf(W);throw new u6(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.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}}catch(f){if(f instanceof u6)throw f;return{type:"failed"}}}async function lD($="pi"){let{verifier:f,challenge:J}=await d4(),W=uD(32),Z=new URL(e.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",e.clientId),Z.searchParams.set("redirect_uri",e.redirectUri),Z.searchParams.set("scope",e.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",W),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:W,url:Z.toString()}}function pD(){try{let $=new URL(e.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):e.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:e.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:e.callbackPort,callbackPath:"/auth/callback",redirectUri:e.redirectUri}}}function EH($,f){let J=f?z0(f):z0($),W=J?J:z0($),Q=W?.[e.jwtClaimPath]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let j=W?.organizations;if(Array.isArray(j)&&j.length>0){let H=j[0];if(typeof H?.id==="string"&&H.id.length>0)return H.id}let X=W?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function bH($,f){let J=EH($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function Y2($){L$($.telemetry,"openai-codex");let f=pD(),{verifier:J,state:W,url:Z}=await lD($.originator),Q=await e0({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:W});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await df({waitForCallback:Q.waitForCallback,cancelWait:Q.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==W)throw Error("State mismatch");if(j=X.code,!j){let A=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),V=uf(A,{allowHashCodeState:!0});if(V.state&&V.state!==W)throw Error("State mismatch");j=V.code}if(!j)throw Error("Missing authorization code");let H=await cD(j,J,f.redirectUri);if(H.type!=="success")throw Error("Token exchange failed");let Y=bH(H);return z$($.telemetry,"openai-codex"),_$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(X){throw O$($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{Q.close()}}async function JJ($,f){let J=await dD($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let W=bH(J,f);if(!W.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return W}async function WJ($,f){if(!$)return null;let J=f?.refreshBufferMs??e.refreshBufferMs,W=f?.retryableTokenGraceMs??e.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!u1($,J))return $;try{return await JJ($.refresh,$)}catch(Q){if(Q instanceof u6&&Q.isLikelyInvalidGrant())return p$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}function nZ($,f=e.refreshBufferMs){return u1($,f)}function aZ($){let f=$.accountId??EH($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var tZ={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return Y2({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return JJ($.refresh,$)},getApiKey($){return $.access}};var YV={};w(YV,{ClineCore:()=>iJ});function IH($){if($===!0)return{};if(!$)return;return $}function xH($){if($==="user")return"global";return $}class sZ{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function mH($){let{host:f}=$;return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:W2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:nD(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content),delivery:W.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:iD(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function c6($){let f=rD($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),W=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,Q=$.context?.telemetry??$.telemetry;if(!f&&!J&&!W&&!Z&&!Q)return $.context;return{...$.context??{},...J?{client:J}:{},...W?{user:W}:{},...Z?{logger:Z}:{},...Q?{telemetry:Q}:{},...f?{automation:f}:{}}}function rD($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function iD($){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((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function nD($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var MY={};w(MY,{createCoreSettingsService:()=>Qf,CoreSettingsService:()=>B1});import{existsSync as Q5}from"node:fs";import{basename as _Y,isAbsolute as Uz,relative as Fz}from"node:path";var eH={};w(eH,{resolveWorkflowsConfigSearchPaths:()=>BJ,resolveSkillsConfigSearchPaths:()=>AJ,resolveRulesConfigSearchPaths:()=>VJ,parseWorkflowConfigFromMarkdown:()=>YJ,parseSkillConfigFromMarkdown:()=>XJ,parseRuleConfigFromMarkdown:()=>HJ,createWorkflowsConfigDefinition:()=>PJ,createUserInstructionConfigService:()=>V1,createSkillsConfigDefinition:()=>KJ,createRulesConfigDefinition:()=>GJ,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>jJ,UnifiedConfigFileWatcher:()=>o1,SKILLS_CONFIG_DIRECTORY_NAME:()=>QJ,RULES_CONFIG_DIRECTORY_NAME:()=>n6});import{createHash as aD}from"node:crypto";import{watch as tD}from"node:fs";import{readdir as sD,readFile as oD}from"node:fs/promises";import{join as eD}from"node:path";function $L($){return aD("sha1").update($).digest("hex")}function uH($){return Boolean($&&typeof $==="object"&&"code"in $)}function gH($){return uH($)&&$.code==="ENOENT"}function vH($){return uH($)&&($.code==="EACCES"||$.code==="EPERM")}class o1{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($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let W of J.directories){let Z=this.baseTypesByDirectory.get(W);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(W,new Set([J.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 f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,W])=>[J,{...W}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([W,Z])=>[W,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=tD(f,()=>{let W=this.watchedTypesByDirectory.get(f);if(!W)return;for(let Z of W)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(W)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let Q of Z)this.emit({kind:"error",type:Q,error:W,filePath:f})})}catch(J){if(!gH(J)&&!vH(J)){let W=$.get(f);if(!W)continue;for(let Z of W)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}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 f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),W=this.recordsByType.get($.type)??new Map;for(let[Z,Q]of W.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:Q.filePath})}for(let[Z,Q]of f.entries()){let j=W.get(Z);if(j&&j.filePath===Q.filePath&&j.fingerprint===Q.fingerprint)continue;this.emit({kind:"upsert",record:{type:Q.type,id:Z,item:Q.item,filePath:Q.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let W of $.directories){J.add(W);let Z=$.discoverFiles?await $.discoverFiles(W):await this.readDirectoryFileCandidates(W);for(let Q of Z){let{fileName:j,filePath:X}=Q;if(J.add(Q.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let H=await oD(X,"utf8"),Y={type:$.type,directoryPath:Q.directoryPath,fileName:j,filePath:X,content:H},A=$.parseFile(Y),V=$.resolveId(A,Y).trim();if(!V)continue;f.set(V,{type:$.type,id:V,item:A,filePath:X,fingerprint:$L(H)})}catch(H){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:H,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let W of J){let Z=$.get(W);if(Z)Z.add(f);else $.set(W,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await sD($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:eD($,J.name)})).sort((J,W)=>J.fileName.localeCompare(W.fileName))}catch(f){if(gH(f)||vH(f))return[];throw f}}}import{readdir as eZ,readFile as fL,stat as oZ}from"node:fs/promises";import{basename as E$,dirname as JL,extname as l6,join as q0,resolve as ZJ}from"node:path";import{AGENTS_RULES_FILE_NAME as cH,RULES_CONFIG_DIRECTORY_NAME as n6,resolveGlobalAgentsRulesPath as WL,resolveRulesConfigSearchPaths as ZL,resolveSkillsConfigSearchPaths as QL,resolveWorkflowsConfigSearchPaths as jL,SKILLS_CONFIG_DIRECTORY_NAME as QJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as jJ}from"@cline/shared/storage";import XL from"yaml";var d6="SKILL.md",HL="managed.json",YL=new Set([".md",".markdown",".txt"]);function $9($){return $.trim().toLowerCase()}function A2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"||f?.code==="ELOOP"}function p6($){return YL.has(l6($).toLowerCase())}function dH($){let f=[],J=new Set;for(let W of $){let Z=ZJ(W);if(J.has(Z))continue;J.add(Z),f.push(W)}return f}function AL($){let f=[...$?.directories??AJ($?.workspacePath)];if($?.pluginSkillDirectories)f.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)f.push(...yX({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return dH(f)}async function f9($){try{let f=await eZ($,{withFileTypes:!0}),J=[];for(let W of f){if(!W.isDirectory())continue;let Z=q0($,W.name),Q=q0(Z,HL);try{let j=await fL(Q,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(A2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((W,Z)=>W.localeCompare(Z))}catch(f){if(A2(f))return[];throw f}}function J9($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J;try{let Q=XL.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}catch(Q){let j=Q instanceof Error?Q.message:String(Q);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function r6($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let W=$.trim();if(!W&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return W||void 0}function V2($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function VL($,f){if(E$($.filePath).toLowerCase()!==cH.toLowerCase())return E$($.filePath,l6($.filePath));if(f&&ZJ($.filePath)===ZJ(f,cH))return"Workspace AGENTS.md";if(ZJ($.filePath)===ZJ(WL()))return"Global AGENTS.md";return E$($.filePath,l6($.filePath))}function XJ($,f){let{data:J,body:W,parseError:Z}=J9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in skill file.");let X=r6(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:r6(J.description,"description",!1),disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function HJ($,f){let{data:J,body:W,parseError:Z}=J9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in rule file.");let j=r6(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function YJ($,f){let{data:J,body:W,parseError:Z}=J9($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let Q=W.trim();if(!Q)throw Error("Missing instructions body in workflow file.");let j=r6(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:V2(J.disabled,"disabled")??(V2(J.enabled,"enabled")===!1?!0:void 0),instructions:Q,frontmatter:J}}function AJ($){return QL($)}function VJ($){return ZL($)}function BJ($){return jL($)}async function lH($){if(E$($)===".cline"){let f=await f9($);return(await Promise.all(f.map((W)=>lH(q0(W,QJ))))).flat()}try{let f=await eZ($,{withFileTypes:!0}),J=[];for(let W of f){if(W.isFile()&&W.name===d6){J.push({directoryPath:$,fileName:W.name,filePath:q0($,W.name)});continue}let Z=q0($,W.name);if(W.isDirectory()||W.isSymbolicLink()&&await oZ(Z).then((j)=>j.isDirectory()).catch((j)=>{if(A2(j))return!1;throw j}))J.push({directoryPath:Z,fileName:d6,filePath:q0(Z,d6)})}return J}catch(f){if(A2(f))return[];throw f}}async function i6($){if(E$($)===".cline"){let f=await f9($);return(await Promise.all(f.map((W)=>i6(q0(W,"rules.md"))))).flat()}try{if((await oZ($)).isFile())return[{directoryPath:JL($),fileName:E$($),filePath:$}]}catch(f){if(!A2(f))throw f}try{let J=(await eZ($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&p6(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:q0($,Z.name)})),W=q0($,"AGENTS.md");try{if((await oZ(W)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:W})}}catch{}return J}catch(f){if(A2(f))return[];throw f}}async function BL($){if(E$($)===".cline"){let f=await f9($);return(await Promise.all(f.map((W)=>i6(q0(W,jJ))))).flat()}return i6($)}function KJ($){let f=AL($),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?dH([...f,J]):f,discoverFiles:lH,includeFile:(W)=>W===d6,parseFile:(W)=>XJ(W.content,E$(W.directoryPath)),resolveId:(W)=>$9(W.name)}}function GJ($){let f=$?.directories??VJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:i6,includeFile:(W,Z)=>W===".clinerules"||p6(W)||p6(Z),parseFile:(W)=>HJ(W.content,VL(W,$?.workspacePath)),resolveId:(W)=>$9(W.name)}}function PJ($){let f=$?.directories??BJ($?.workspacePath),J=$?.workspacePath?q0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:BL,includeFile:(W)=>p6(W),parseFile:(W)=>YJ(W.content,E$(W.filePath,l6(W.filePath))),resolveId:(W)=>$9(W.name)}}function pH($){let f=[KJ($?.skills),GJ($?.rules),PJ($?.workflows)];return new o1(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as rH}from"@cline/shared";function KL($,f){if($.description?.trim())return rH($.description,".");if(f==="workflow")return;return rH($.instructions,".")}function GL($){return $.disabled!==!0}function iH($,f){return[...$.getSnapshot(f).entries()].map(([J,W])=>({id:J,record:W})).filter(({record:J})=>GL(J.item)).map(({id:J,record:W})=>({id:J,name:W.item.name,instructions:W.item.instructions,description:KL(W.item,f),kind:f})).sort((J,W)=>J.name.localeCompare(W.name))}function UJ($){let f=new Map;for(let J of[...iH($,"workflow"),...iH($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,W)=>J.name.localeCompare(W.name))}function nH($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let W=J[1];if(!W)return $;let Z=W.length+1,Q=$.slice(Z),j=UJ(f).find((X)=>X.name===W);return j?`${j.instructions}${Q}`:$}var tH={};w(tH,{mergeRulesForSystemPrompt:()=>K2,loadRulesForSystemPromptFromWatcher:()=>W9,listEnabledRulesFromWatcher:()=>aH,isRuleEnabled:()=>a6,formatRulesForSystemPrompt:()=>B2});function a6($){return $.disabled!==!0}function B2($){if($.length===0)return"";return`
185
185
 
186
186
  # Rules
187
187
  ${$.map((J)=>`## ${J.name}
@@ -189,13 +189,13 @@ ${J.instructions}`).join(`
189
189
 
190
190
  `)}`}function K2($,f){let J=$?.trim(),W=f?.trim();if(J&&W)return`${J}
191
191
 
192
- ${W}`;return J||W||void 0}function aH($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(a6).sort((J,W)=>J.name.localeCompare(W.name))}function WZ($){return B2(aH($))}function t6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function PL($){if(!$||$.length===0)return;let f=$.map(t6).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function UL($,f,J){if(!J)return!0;let W=t6($),Z=t6(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function FJ($,f){let J=PL(f);return[...$.getSnapshot("skill").entries()].map(([Z,Q])=>{let j=Q.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>UL(Z.id,Z.name,J))}function FL($,f){return FJ($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function RL($,f,J){let W=t6(f);if(!W)return{error:"Missing skill name."};let Z=FJ($,J),Q=Z.find((A)=>A.id===W);if(Q){let{skill:A}=Q;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Q.id,skill:A}}let j=W.includes(":")?W.split(":").at(-1)??W:W,X=Z.filter(({id:A})=>{if(A===j)return!0;return A.endsWith(`:${j}`)}),H=X.filter(({skill:A})=>A.disabled!==!0);if(H.length===1){let{id:A,skill:V}=H[0];return{id:A,skill:V}}if(H.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${H.map(({id:A})=>A).join(", ")}`};if(X.length===1){let{skill:A}=X[0];return{error:`Skill "${A.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:A})=>A).join(", ")}`};let Y=FL($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function DL($,f=Promise.resolve(),J){let W=new Set,Z=async(Q,j)=>{await f;let X=RL($,Q,J);if("error"in X)return X.error;let{id:H,skill:Y}=X;if(W.has(H))return`Skill "${Y.name}" is already running.`;W.add(H);try{let A=j?.trim(),V=A?`
192
+ ${W}`;return J||W||void 0}function aH($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(a6).sort((J,W)=>J.name.localeCompare(W.name))}function W9($){return B2(aH($))}function t6($){return $.trim().replace(/^\/+/,"").toLowerCase()}function PL($){if(!$||$.length===0)return;let f=$.map(t6).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function UL($,f,J){if(!J)return!0;let W=t6($),Z=t6(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function FJ($,f){let J=PL(f);return[...$.getSnapshot("skill").entries()].map(([Z,Q])=>{let j=Q.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>UL(Z.id,Z.name,J))}function FL($,f){return FJ($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,W)=>J.localeCompare(W))}function RL($,f,J){let W=t6(f);if(!W)return{error:"Missing skill name."};let Z=FJ($,J),Q=Z.find((A)=>A.id===W);if(Q){let{skill:A}=Q;if(A.disabled===!0)return{error:`Skill "${A.name}" is configured but disabled.`};return{id:Q.id,skill:A}}let j=W.includes(":")?W.split(":").at(-1)??W:W,X=Z.filter(({id:A})=>{if(A===j)return!0;return A.endsWith(`:${j}`)}),H=X.filter(({skill:A})=>A.disabled!==!0);if(H.length===1){let{id:A,skill:V}=H[0];return{id:A,skill:V}}if(H.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${H.map(({id:A})=>A).join(", ")}`};if(X.length===1){let{skill:A}=X[0];return{error:`Skill "${A.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:A})=>A).join(", ")}`};let Y=FL($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function DL($,f=Promise.resolve(),J){let W=new Set,Z=async(Q,j)=>{await f;let X=RL($,Q,J);if("error"in X)return X.error;let{id:H,skill:Y}=X;if(W.has(H))return`Skill "${Y.name}" is already running.`;W.add(H);try{let A=j?.trim(),V=A?`
193
193
  <command-args>${A}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
194
194
 
195
195
  `:"";return`<command-name>${Y.name}</command-name>${V}
196
196
  <command-instructions>
197
197
  ${B}${Y.instructions}
198
- </command-instructions>`}finally{W.delete(H)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>FJ($,J).map(({skill:Q,...j})=>j),enumerable:!0,configurable:!1}),Z}function sH($){let f=$.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 f,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>WZ($.watcher)});if($.registerSkillsTool)W.registerTool(w1(DL($.watcher,f,$.allowedSkillNames)));for(let Z of UJ($.watcher).filter((Q)=>Q.kind==="skill"&&$.includeSkills||Q.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:Z.name,description:Z.description,handler:(Q)=>{let j=Q.trim();return j?`${Z.instructions}
198
+ </command-instructions>`}finally{W.delete(H)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>FJ($,J).map(({skill:Q,...j})=>j),enumerable:!0,configurable:!1}),Z}function sH($){let f=$.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 f,$.includeRules)W.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>W9($.watcher)});if($.registerSkillsTool)W.registerTool(w1(DL($.watcher,f,$.allowedSkillNames)));for(let Z of UJ($.watcher).filter((Q)=>Q.kind==="skill"&&$.includeSkills||Q.kind==="workflow"&&$.includeWorkflows))W.registerCommand({name:Z.name,description:Z.description,handler:(Q)=>{let j=Q.trim();return j?`${Z.instructions}
199
199
 
200
200
  ${j}`:Z.instructions}})}}}class oH{watcher;ready;stopped=!1;constructor($){this.watcher=pH($)}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(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return UJ(this.watcher)}resolveRuntimeSlashCommand($){return nH($,this.watcher)}hasConfiguredSkills($){return FJ(this.watcher,$).some((f)=>!f.disabled)}createExtension($){return sH({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function V1($){return new oH($)}import{readFile as LL,writeFile as zL}from"node:fs/promises";import fY from"yaml";function OL($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,W,Z]=J,Q=fY.parse(W);return{data:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:{},body:Z,hadFrontmatter:!0}}function $Y($,f){return`---
201
201
  ${fY.stringify($).trimEnd()}
@@ -203,10 +203,10 @@ ${fY.stringify($).trimEnd()}
203
203
  ${f}`}function _L($,f){let{data:J,body:W,hadFrontmatter:Z}=OL($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return W;return $Y(J,W)}return J.disabled=!0,$Y(J,W)}async function JY({filePath:$,enabled:f}){let J=await LL($,"utf8"),W=_L(J,f);return await zL($,W),{filePath:$,enabled:f,disabled:!f}}var LY={};w(LY,{updateMcpServerOAuthState:()=>Jf,setMcpServerDisabled:()=>$f,resolveMcpServerRegistrations:()=>H$,resolveDefaultMcpSettingsPath:()=>_0,registerMcpServersFromSettingsFile:()=>Wf,loadMcpSettingsFile:()=>e1,listMcpServerOAuthStatuses:()=>DJ,hasMcpSettingsFile:()=>b$,getMcpServerOAuthState:()=>ff,createMcpTools:()=>U2,createDisabledMcpToolPolicy:()=>LJ,createDisabledMcpToolPolicies:()=>W5,createDefaultMcpServerClientFactory:()=>P2,authorizeMcpServerOAuth:()=>$5,InMemoryMcpManager:()=>Zf});import{spawn as tL}from"node:child_process";import{StringDecoder as PY}from"node:string_decoder";import{UnauthorizedError as VY}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as sL}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as vL}from"node:crypto";import{UnauthorizedError as uL}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as cL}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as dL}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as lL}from"@modelcontextprotocol/sdk/client/streamableHttp.js";s6();var pL="/mcp/oauth/callback",rL=[1456,1457,1458],iL=300000;function nL($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function aL($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function e6($){let f={};try{f=ff($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,W,Z=async(j)=>{let X=G2(j(f))??{};try{f=Jf($.serverName,()=>X,{filePath:$.settingsPath})}catch{f=X}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return aL(f.redirectUrl??$.redirectUrl)},state:()=>{return W=vL(),W},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((X)=>({...X,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((X)=>({...X,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((X)=>({...X,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((X)=>{if(j==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((X)=>({...X,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>W,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((X)=>({...X,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function o6($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new dL(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new lL(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function AY($){return new cL({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function $5($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (s6(),YY)),W=J({filePath:$.filePath}).find((H)=>H.name===f);if(!W)throw Error(`MCP server "${f}" is not configured.`);if(W.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(W.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await e0({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:rL,callbackPath:$.callbackPath??pL,timeoutMs:$.timeoutMs??iL,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let Q=e6({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(H)=>{await $.openUrl?.(H)}});await Q.resetInteractiveState();let j=AY($),X;try{let H=o6({registration:W,oauthProvider:Q.provider,fetch:$.fetch});try{return await j.connect(H),await j.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(Y){if(!(Y instanceof uL))throw Y;if(!Q.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let V=await Z.waitForCallback();if(!V)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(V.error)throw Error(`OAuth authorization failed: ${V.error}`);if(!V.code)throw Error("OAuth callback did not include an authorization code.");let B=Q.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(V.state!==B)throw Error("OAuth authorization failed: state mismatch.");await H.finishAuth(V.code),X=AY($);let K=o6({registration:W,oauthProvider:Q.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await Q.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(H){let Y=nL(H);throw await Q.markError(Y),Error(Y)}finally{await j.close().catch(()=>{return}),await X?.close().catch(()=>{return}),Z.close()}}var oL="2024-11-05",eL=5000,$z=1500,BY="http://127.0.0.1:1456/mcp/oauth/callback";function f5($){return $ instanceof Error?$.message:String($)}function KY($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
204
204
  \r
205
205
  `,"utf8");return Buffer.concat([J,f])}function GY($){return Buffer.from(`${JSON.stringify($)}
206
- `,"utf8")}class XZ{buffer="";decoder=new PY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
206
+ `,"utf8")}class X9{buffer="";decoder=new PY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
207
207
  \r
208
- `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(Z[1],10),j=J+4,X=j+Q;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class HZ{buffer="";decoder=new PY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
209
- `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)f.push(W)}return f}}class UY{registration;process;nextRequestId=1;pending=new Map;framedParser=new XZ;newlineParser=new HZ;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"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:oL,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},$z),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){f=W instanceof Error?W:Error(String(W))}}throw f??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((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new XZ,this.newlineParser=new HZ,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=tL(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(Z)=>this.handleStdout(Z)),W.stderr.on("data",(Z)=>{if(this.process!==W)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(Z)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${f5(Z)}`))}),W.once("exit",(Z,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${Q??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let Z=this.pending.get(W.id);if(!Z)continue;if(this.pending.delete(W.id),clearTimeout(Z.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;Z.reject(Error(Q));continue}Z.resolve(W.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${f5($)}.${J}`)),f.kill()}async request($,f,J=eL){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,Q={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,H)=>{let Y=setTimeout(()=>{this.pending.delete(Z),H(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:H,timeout:Y})});try{W.stdin.write(this.protocolMode==="framed"?KY(Q):GY(Q))}catch(X){let H=this.pending.get(Z);if(H)clearTimeout(H.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?KY(W):GY(W))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class FY{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}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 $=e6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BY});this.authContext=$;try{let f=new sL({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=o6({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof VY?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):f5(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}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 f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??e6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BY}),J=$ instanceof VY?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):f5($);throw await f.markError(J),Error(J)}}function P2($={}){return(f)=>f.transport.type==="stdio"?new UY(f):new FY(f,$)}s6();function g0(){return Date.now()}function fz($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Zf{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:g0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=g0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=g0(),f)await this.disconnectState(J)})}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(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&g0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),W=await(await this.ensureConnectedClient(f)).listTools(),Z=fz(W);return f.toolCache=Z,f.toolCacheUpdatedAt=g0(),f.updatedAt=g0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=g0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}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=g0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=g0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=g0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=g0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=g0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),W,Z=new Promise((j)=>{W=j}),Q=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,Q),await J.catch(()=>{return});try{return await f()}finally{if(W?.(),this.operationLocks.get($)===Q)this.operationLocks.delete($)}}}import{createHash as Jz}from"node:crypto";var RY=128,Wz=/[^a-zA-Z0-9_-]+/g,DY=8,Zz=1,Qz="mcp_tool";function jz($){return Jz("sha1").update($).digest("hex").slice(0,DY)}function Xz($){return $.replace(Wz,"_")}var J5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,W=Xz(J);if(W===J&&J.length<=RY)return J;let Z=jz(J),Q=RY-Zz-DY;return`${W.slice(0,Q)||Qz}_${Z}`};function LJ($){return{[($.nameTransform??J5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function W5($){let f={};for(let J of $.toolNames)Object.assign(f,LJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as Hz}from"@cline/shared";function Yz($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function U2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??J5;return f.map((W)=>{let Z=J({serverName:$.serverName,toolName:W.name});return Hz({name:Z,description:Yz($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(Q,j)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:j})})})}X$();var OY={};w(OY,{listPluginToolsWithDiagnostics:()=>Z5,listPluginTools:()=>zJ});import{stat as Az}from"node:fs/promises";X$();var Vz=32,F2=new Map;function Bz($,f){if(!F2.has($)&&F2.size>=Vz){let J=F2.keys().next().value;if(J)F2.delete(J)}F2.set($,f)}async function Kz($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let W=await Az(J);return`${J}:${W.mtimeMs}:${W.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function zY($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function Gz($){return $.sort((f,J)=>{let W=f.name.localeCompare(J.name);if(W!==0)return W;return f.path.localeCompare(J.path)})}function Pz($,f){if(!$.setup)return[];let J=[],W={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(W,{workspaceInfo:f}),J}async function Z5($){let f=p1({workspacePath:$.workspacePath,cwd:$.cwd}),J=j$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let W=await Kz({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=F2.get(W);if(Z)return{tools:zY(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let Q=[],j=[],X=[],H;try{H=await $6({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...H.failures],X=[...H.warnings];for(let V of H.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of Pz(V,{rootPath:$.workspacePath}))Q.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=f.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await H?.shutdown().catch(()=>{})}let Y=Gz(Q);return Bz(W,{tools:Y,failures:j,warnings:X}),{tools:zY(Y,J),failures:j,warnings:X}}async function zJ($){return(await Z5($)).tools}function j5($,f){if(!f)return"global";let J=Fz(f,$);return!J.startsWith("..")&&!Uz(J)?"workspace":"global"}function OJ($){return[...$].sort((f,J)=>{let W=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return W(f.source)-W(J.source);return f.name.localeCompare(J.name)})}function NY($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function TY($,f){if($.userInstructionService)return await f($.userInstructionService);let J=NY($);if(!J)return await f(void 0);let W=$.cwd?.trim()||J,Z=V1({skills:{workspacePath:J,includePluginSkills:!0,cwd:W},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function Rz($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let W=J.find((Z)=>Z.id===f.id);if(W)return W}for(let W of J)if(W.filePath===f.path||W.item.name===f.name||W.id===f.name)return W;return}class B1{async list($={}){return await TY($,async(f)=>{let J=NY($),W=[],Z=[],Q=[],j=[],X=[];if(f){for(let Y of f.listRecords("workflow")){let A=Y.item;W.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"workflow",source:j5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let A=Y.item;Z.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"rule",source:j5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let A=Y.item;Q.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"skill",source:j5(Y.filePath,J),description:A.description,toggleable:!0})}}if(J)try{for(let Y of await zJ({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let H=_0();if(b$({filePath:H}))try{for(let Y of H$({filePath:H}))X.push({id:Y.name,name:Y.name,path:H,enabled:Y.disabled!==!0,kind:"mcp",source:j5(H,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:OJ(W.filter((Y)=>Q5(Y.path))),rules:OJ(Z.filter((Y)=>Q5(Y.path))),skills:OJ(Q.filter((Y)=>Q5(Y.path))),tools:OJ(j),mcp:OJ(X.filter((Y)=>Q5(Y.path)))}})}async toggle($){if($.type==="skills")return await TY($,async(f)=>{let J=Rz(f,$),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??_Y($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=$.enabled??(Z!==void 0?!Z:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??_Y($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await JY({filePath:W,enabled:Q}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)n4($.name);else $X($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||_0(),W=$.enabled;if(W===void 0){let Z=H$({filePath:J}).find((Q)=>Q.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);W=Z.disabled===!0}return $f({filePath:J,name:f,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Qf(){return new B1}function yY($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Qf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Qf().toggle(f)}}}function qY($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}var wY={};w(wY,{splitCoreSessionConfig:()=>_J,isSessionNotFoundError:()=>I$,SessionNotFoundError:()=>k$,SESSION_NOT_FOUND_ERROR_CODE:()=>jf});var jf="session_not_found";class k$ extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function I$($){return $ instanceof k$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function _J($){let{hooks:f,logger:J,telemetry:W,extensionContext:Z,extraTools:Q,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:H,checkpoint:Y,compaction:A,...V}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(W)B.telemetry=W;if(Z)B.extensionContext=Z;if(Q)B.extraTools=Q;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(H)B.onConsecutiveMistakeLimitReached=H;if(Y?.createCheckpoint)B.checkpoint=Y;if(A?.compact)B.compaction=A;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...Y?{checkpoint:{enabled:Y.enabled}}:{},...A?{compaction:{enabled:A.enabled,strategy:A.strategy,thresholdRatio:A.thresholdRatio,reserveTokens:A.reserveTokens,preserveRecentTokens:A.preserveRecentTokens,maxInputTokens:A.maxInputTokens,summarizer:A.summarizer}}:{}},...K?{localRuntime:K}:{}}}function SY($){let f=$.config;return"providerId"in f?{...$,config:{...f,...Dz($.localRuntime)},localRuntime:$.localRuntime}:$}function YZ($,f={}){let J=_J($.config),W=F0(f.defaultCapabilities,$.capabilities),Z=Lz(J.localRuntime,$.localRuntime),Q=f.withExtensionContext?.(Z?.extensionContext);if(Q)Z={...Z??{},extensionContext:Q};return{...$,...J,...Z?{localRuntime:Z}:{},...W?{capabilities:W}:{}}}function Dz($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:W,onTeamRestored:Z,...Q}=$;return Q}function Lz(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function hY($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??G0.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 TJ($){return!!$&&typeof $==="object"&&!Array.isArray($)}function AZ($){let f=$?.trim();return f?f:void 0}function zz($,f){let J=$?.trim();if(!J)return f;let W=Date.parse(J);if(!Number.isFinite(W))return f;return new Date(W).toISOString()}function CY($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function EY($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function Oz($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function _z($,f){let J=$.eventId.trim(),W=$.eventType.trim(),Z=$.source.trim(),Q=AZ($.subject),j=AZ($.dedupeKey)??`${W}:${Z}:${Q??J}`;return{eventId:J,eventType:W,source:Z,subject:Q,occurredAt:zz($.occurredAt,f),workspaceRoot:AZ($.workspaceRoot),payload:TJ($.payload)?$.payload:void 0,attributes:TJ($.attributes)?$.attributes:void 0,dedupeKey:j}}function VZ($,f){if(!f)return;let J=f.split("."),W=$;for(let Z of J){if(!TJ(W))return;W=W[Z]}return W}function Tz($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=VZ(J,f);if(W!==void 0)return W;if($.attributes){let Z=VZ($.attributes,f);if(Z!==void 0)return Z}if($.payload)return VZ($.payload,f);return}function X5($,f){if(Array.isArray(f))return f.some((J)=>X5($,J));if(Array.isArray($))return $.some((J)=>X5(J,f));if(TJ(f)){if(!TJ($))return!1;return Object.entries(f).every(([J,W])=>X5($[J],W))}return Object.is($,f)}function Nz($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,W])=>X5(Tz($,J),W))}class BZ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=_z($,f),W=this.store.insertEventLog(J,{receivedAtIso:f});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 Z=this.store.listEventSpecsForType(J.eventType),Q=[],j=[],X=[];for(let A of Z){if(!Nz(J,A.filters)){Q.push({specId:A.specId,externalId:A.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(A);let V=this.materializeForSpec(A,J,W.record.receivedAt);if(V.run)X.push(V.run);else Q.push({specId:A.specId,externalId:A.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let H=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:H,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:Q.filter((A)=>A.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:H,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:Y??W.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:Q}}catch(Z){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let W=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let H=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(H){let Y=Oz(H.scheduledFor,CY(J,Z)),A=this.store.updateQueuedEventRunForDebounce({runId:H.runId,triggerEventId:f.eventId,scheduledFor:Y});if(A)return{run:A,reason:"dedupe_window"}}}let Q=$.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:EY(J,Q)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:EY(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?CY(J,Z):J}),reason:"dedupe_window"}}}class NJ{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of f)if(this.materializeOneOff(W))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)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 Cz}from"node:path";import{buildClineSystemPrompt as Ez}from"@cline/shared";import{nowIso as bY}from"@cline/shared/db";import{mkdirSync as Mz,writeFileSync as yz}from"node:fs";import{join as qz}from"node:path";import{resolveCronReportsDir as wz}from"@cline/shared/storage";function K1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Xf($,f){if(f===void 0||f===null)return;return`${$}: ${K1(f)}`}function Sz($,f,J){let W=[`runId: ${K1($.runId)}`,`specId: ${K1(f.specId)}`,`externalId: ${K1(f.externalId)}`,`title: ${K1(f.title)}`,`triggerKind: ${K1($.triggerKind)}`,`status: ${K1($.status)}`,`sourcePath: ${K1(f.sourcePath)}`],Z=[Xf("sessionId",$.sessionId),Xf("startedAt",$.startedAt),Xf("completedAt",$.completedAt),Xf("triggerEventId",$.triggerEventId),Xf("triggerEventType",J?.eventType),Xf("triggerEventSource",J?.source),Xf("triggerEventSubject",J?.subject)];for(let Q of Z)if(Q)W.push(Q);return`---
208
+ `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let Q=Number.parseInt(Z[1],10),j=J+4,X=j+Q;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class H9{buffer="";decoder=new PY("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
209
+ `);if(J<0)break;let W=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),W.length>0)f.push(W)}return f}}class UY{registration;process;nextRequestId=1;pending=new Map;framedParser=new X9;newlineParser=new H9;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"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:oL,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},$z),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(W){f=W instanceof Error?W:Error(String(W))}}throw f??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((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new X9,this.newlineParser=new H9,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},W=tL(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=W,W.stdout.on("data",(Z)=>this.handleStdout(Z)),W.stderr.on("data",(Z)=>{if(this.process!==W)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),W.once("error",(Z)=>{if(this.process!==W)return;this.failAllPending(Error(`MCP process error: ${f5(Z)}`))}),W.once("exit",(Z,Q)=>{if(this.process!==W)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${Q??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let W=JSON.parse(J);if(typeof W.id!=="number")continue;let Z=this.pending.get(W.id);if(!Z)continue;if(this.pending.delete(W.id),clearTimeout(Z.timeout),W.error){let Q=W.error.message||`MCP request failed with code ${W.error.code??"unknown"}`;Z.reject(Error(Q));continue}Z.resolve(W.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${f5($)}.${J}`)),f.kill()}async request($,f,J=eL){let W=this.process;if(!W?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,Q={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,H)=>{let Y=setTimeout(()=>{this.pending.delete(Z),H(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:H,timeout:Y})});try{W.stdin.write(this.protocolMode==="framed"?KY(Q):GY(Q))}catch(X){let H=this.pending.get(Z);if(H)clearTimeout(H.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let W={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?KY(W):GY(W))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class FY{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}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 $=e6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BY});this.authContext=$;try{let f=new sL({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=o6({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof VY?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):f5(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}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 f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??e6({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??BY}),J=$ instanceof VY?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):f5($);throw await f.markError(J),Error(J)}}function P2($={}){return(f)=>f.transport.type==="stdio"?new UY(f):new FY(f,$)}s6();function g0(){return Date.now()}function fz($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Zf{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:g0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=g0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=g0(),f)await this.disconnectState(J)})}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(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&g0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),W=await(await this.ensureConnectedClient(f)).listTools(),Z=fz(W);return f.toolCache=Z,f.toolCacheUpdatedAt=g0(),f.updatedAt=g0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=g0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}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=g0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=g0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=g0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=g0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=g0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),W,Z=new Promise((j)=>{W=j}),Q=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,Q),await J.catch(()=>{return});try{return await f()}finally{if(W?.(),this.operationLocks.get($)===Q)this.operationLocks.delete($)}}}import{createHash as Jz}from"node:crypto";var RY=128,Wz=/[^a-zA-Z0-9_-]+/g,DY=8,Zz=1,Qz="mcp_tool";function jz($){return Jz("sha1").update($).digest("hex").slice(0,DY)}function Xz($){return $.replace(Wz,"_")}var J5=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,W=Xz(J);if(W===J&&J.length<=RY)return J;let Z=jz(J),Q=RY-Zz-DY;return`${W.slice(0,Q)||Qz}_${Z}`};function LJ($){return{[($.nameTransform??J5)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function W5($){let f={};for(let J of $.toolNames)Object.assign(f,LJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as Hz}from"@cline/shared";function Yz($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function U2($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??J5;return f.map((W)=>{let Z=J({serverName:$.serverName,toolName:W.name});return Hz({name:Z,description:Yz($.serverName,W),inputSchema:W.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(Q,j)=>$.provider.callTool({serverName:$.serverName,toolName:W.name,arguments:Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:void 0,context:j})})})}X$();var OY={};w(OY,{listPluginToolsWithDiagnostics:()=>Z5,listPluginTools:()=>zJ});import{stat as Az}from"node:fs/promises";X$();var Vz=32,F2=new Map;function Bz($,f){if(!F2.has($)&&F2.size>=Vz){let J=F2.keys().next().value;if(J)F2.delete(J)}F2.set($,f)}async function Kz($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let W=await Az(J);return`${J}:${W.mtimeMs}:${W.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function zY($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function Gz($){return $.sort((f,J)=>{let W=f.name.localeCompare(J.name);if(W!==0)return W;return f.path.localeCompare(J.path)})}function Pz($,f){if(!$.setup)return[];let J=[],W={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(W,{workspaceInfo:f}),J}async function Z5($){let f=p1({workspacePath:$.workspacePath,cwd:$.cwd}),J=j$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let W=await Kz({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=F2.get(W);if(Z)return{tools:zY(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let Q=[],j=[],X=[],H;try{H=await $6({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...H.failures],X=[...H.warnings];for(let V of H.extensions??[]){let B=V.__clinePluginPath;if(!B)continue;for(let K of Pz(V,{rootPath:$.workspacePath}))Q.push({name:K.name,pluginName:V.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:K.description?.trim()||void 0})}}catch(V){j=f.map((B)=>({pluginPath:B,phase:"load",message:V instanceof Error?V.message:String(V),stack:V instanceof Error?V.stack:void 0}))}finally{await H?.shutdown().catch(()=>{})}let Y=Gz(Q);return Bz(W,{tools:Y,failures:j,warnings:X}),{tools:zY(Y,J),failures:j,warnings:X}}async function zJ($){return(await Z5($)).tools}function j5($,f){if(!f)return"global";let J=Fz(f,$);return!J.startsWith("..")&&!Uz(J)?"workspace":"global"}function OJ($){return[...$].sort((f,J)=>{let W=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return W(f.source)-W(J.source);return f.name.localeCompare(J.name)})}function NY($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function TY($,f){if($.userInstructionService)return await f($.userInstructionService);let J=NY($);if(!J)return await f(void 0);let W=$.cwd?.trim()||J,Z=V1({skills:{workspacePath:J,includePluginSkills:!0,cwd:W},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Z.start(),await f(Z)}finally{Z.stop()}}function Rz($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let W=J.find((Z)=>Z.id===f.id);if(W)return W}for(let W of J)if(W.filePath===f.path||W.item.name===f.name||W.id===f.name)return W;return}class B1{async list($={}){return await TY($,async(f)=>{let J=NY($),W=[],Z=[],Q=[],j=[],X=[];if(f){for(let Y of f.listRecords("workflow")){let A=Y.item;W.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"workflow",source:j5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let A=Y.item;Z.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"rule",source:j5(Y.filePath,J),description:A.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let A=Y.item;Q.push({id:Y.id,name:A.name,path:Y.filePath,enabled:A.disabled!==!0,kind:"skill",source:j5(Y.filePath,J),description:A.description,toggleable:!0})}}if(J)try{for(let Y of await zJ({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let H=_0();if(b$({filePath:H}))try{for(let Y of H$({filePath:H}))X.push({id:Y.name,name:Y.name,path:H,enabled:Y.disabled!==!0,kind:"mcp",source:j5(H,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:OJ(W.filter((Y)=>Q5(Y.path))),rules:OJ(Z.filter((Y)=>Q5(Y.path))),skills:OJ(Q.filter((Y)=>Q5(Y.path))),tools:OJ(j),mcp:OJ(X.filter((Y)=>Q5(Y.path)))}})}async toggle($){if($.type==="skills")return await TY($,async(f)=>{let J=Rz(f,$),W=J?.filePath;if(!W)throw Error(`Unable to resolve skill setting '${$.id??$.name??_Y($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,Q=$.enabled??(Z!==void 0?!Z:void 0);if(Q===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??_Y($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await JY({filePath:W,enabled:Q}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)n4($.name);else $X($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||_0(),W=$.enabled;if(W===void 0){let Z=H$({filePath:J}).find((Q)=>Q.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);W=Z.disabled===!0}return $f({filePath:J,name:f,disabled:!W}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function Qf(){return new B1}function yY($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await Qf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await Qf().toggle(f)}}}function qY($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}var wY={};w(wY,{splitCoreSessionConfig:()=>_J,isSessionNotFoundError:()=>I$,SessionNotFoundError:()=>k$,SESSION_NOT_FOUND_ERROR_CODE:()=>jf});var jf="session_not_found";class k$ extends Error{sessionId;code="session_not_found";constructor($,f){super(f??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function I$($){return $ instanceof k$||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function _J($){let{hooks:f,logger:J,telemetry:W,extensionContext:Z,extraTools:Q,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:H,checkpoint:Y,compaction:A,...V}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(W)B.telemetry=W;if(Z)B.extensionContext=Z;if(Q)B.extraTools=Q;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(H)B.onConsecutiveMistakeLimitReached=H;if(Y?.createCheckpoint)B.checkpoint=Y;if(A?.compact)B.compaction=A;let K=Object.keys(B).length>0?B:void 0;return{config:{...V,...Y?{checkpoint:{enabled:Y.enabled}}:{},...A?{compaction:{enabled:A.enabled,strategy:A.strategy,thresholdRatio:A.thresholdRatio,reserveTokens:A.reserveTokens,preserveRecentTokens:A.preserveRecentTokens,maxInputTokens:A.maxInputTokens,summarizer:A.summarizer}}:{}},...K?{localRuntime:K}:{}}}function SY($){let f=$.config;return"providerId"in f?{...$,config:{...f,...Dz($.localRuntime)},localRuntime:$.localRuntime}:$}function Y9($,f={}){let J=_J($.config),W=F0(f.defaultCapabilities,$.capabilities),Z=Lz(J.localRuntime,$.localRuntime),Q=f.withExtensionContext?.(Z?.extensionContext);if(Q)Z={...Z??{},extensionContext:Q};return{...$,...J,...Z?{localRuntime:Z}:{},...W?{capabilities:W}:{}}}function Dz($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:W,onTeamRestored:Z,...Q}=$;return Q}function Lz(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}L0();function hY($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??G0.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 TJ($){return!!$&&typeof $==="object"&&!Array.isArray($)}function A9($){let f=$?.trim();return f?f:void 0}function zz($,f){let J=$?.trim();if(!J)return f;let W=Date.parse(J);if(!Number.isFinite(W))return f;return new Date(W).toISOString()}function CY($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function EY($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function Oz($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function _z($,f){let J=$.eventId.trim(),W=$.eventType.trim(),Z=$.source.trim(),Q=A9($.subject),j=A9($.dedupeKey)??`${W}:${Z}:${Q??J}`;return{eventId:J,eventType:W,source:Z,subject:Q,occurredAt:zz($.occurredAt,f),workspaceRoot:A9($.workspaceRoot),payload:TJ($.payload)?$.payload:void 0,attributes:TJ($.attributes)?$.attributes:void 0,dedupeKey:j}}function V9($,f){if(!f)return;let J=f.split("."),W=$;for(let Z of J){if(!TJ(W))return;W=W[Z]}return W}function Tz($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},W=V9(J,f);if(W!==void 0)return W;if($.attributes){let Z=V9($.attributes,f);if(Z!==void 0)return Z}if($.payload)return V9($.payload,f);return}function X5($,f){if(Array.isArray(f))return f.some((J)=>X5($,J));if(Array.isArray($))return $.some((J)=>X5(J,f));if(TJ(f)){if(!TJ($))return!1;return Object.entries(f).every(([J,W])=>X5($[J],W))}return Object.is($,f)}function Nz($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,W])=>X5(Tz($,J),W))}class B9{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=_z($,f),W=this.store.insertEventLog(J,{receivedAtIso:f});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 Z=this.store.listEventSpecsForType(J.eventType),Q=[],j=[],X=[];for(let A of Z){if(!Nz(J,A.filters)){Q.push({specId:A.specId,externalId:A.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(A);let V=this.materializeForSpec(A,J,W.record.receivedAt);if(V.run)X.push(V.run);else Q.push({specId:A.specId,externalId:A.externalId,reason:V.reason,dedupeKey:J.dedupeKey})}let H=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(W.record.eventId,{status:H,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:Q.filter((A)=>A.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(W.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:W.record.eventId,eventType:W.record.eventType,status:H,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:Y??W.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:Q}}catch(Z){if(this.store.updateEventLogProcessing(W.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:W.record.eventId,eventType:W.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let W=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let H=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:W});if(H){let Y=Oz(H.scheduledFor,CY(J,Z)),A=this.store.updateQueuedEventRunForDebounce({runId:H.runId,triggerEventId:f.eventId,scheduledFor:Y});if(A)return{run:A,reason:"dedupe_window"}}}let Q=$.dedupeWindowSeconds??0;if(Q>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:W,sinceIso:EY(J,Q)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:EY(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?CY(J,Z):J}),reason:"dedupe_window"}}}class NJ{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let W of f)if(this.materializeOneOff(W))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let W of J)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 Cz}from"node:path";import{buildClineSystemPrompt as Ez}from"@cline/shared";import{nowIso as bY}from"@cline/shared/db";import{mkdirSync as Mz,writeFileSync as yz}from"node:fs";import{join as qz}from"node:path";import{resolveCronReportsDir as wz}from"@cline/shared/storage";function K1($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function Xf($,f){if(f===void 0||f===null)return;return`${$}: ${K1(f)}`}function Sz($,f,J){let W=[`runId: ${K1($.runId)}`,`specId: ${K1(f.specId)}`,`externalId: ${K1(f.externalId)}`,`title: ${K1(f.title)}`,`triggerKind: ${K1($.triggerKind)}`,`status: ${K1($.status)}`,`sourcePath: ${K1(f.sourcePath)}`],Z=[Xf("sessionId",$.sessionId),Xf("startedAt",$.startedAt),Xf("completedAt",$.completedAt),Xf("triggerEventId",$.triggerEventId),Xf("triggerEventType",J?.eventType),Xf("triggerEventSource",J?.source),Xf("triggerEventSubject",J?.subject)];for(let Q of Z)if(Q)W.push(Q);return`---
210
210
  ${W.join(`
211
211
  `)}
212
212
  ---
@@ -229,17 +229,17 @@ ${W.join(`
229
229
  ${J.join(`
230
230
  `)}
231
231
  `)}return f.join(`
232
- `)}function KZ($){let f=wz($.specs);Mz(f,{recursive:!0});let J=qz(f,`${$.run.runId}.md`),W=`${Sz($.run,$.spec,$.data.triggerEvent)}
233
- ${hz($.data)}`;return yz(J,W,"utf8"),J}class GZ{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=W)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var bz=15000,kz=90,kY=["rules","skills","plugins"];function Iz($,f){return new Set($.extensions??kY).has(f)}function xz($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)J[W]={enabled:!0,autoApprove:!0};if(f==="yolo")J[J0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function mz($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} 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(`
234
- `)}class PZ extends Error{constructor($){super($);this.name="TimeoutError"}}async function gz($,f){if(f<=0)return $;let J,W=new Promise((Z,Q)=>{J=setTimeout(()=>{Q(new PZ("cron run timed out"))},f)});try{return await Promise.race([$,W])}finally{if(J)clearTimeout(J)}}class MJ{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 GZ($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??kz)*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??bz);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 f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,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:bY(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,W)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let Q=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,H=Date.now(),Y;if(J.timeoutSeconds&&J.timeoutSeconds>0)Y=H+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let A=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(A)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:A,prompt:this.buildPrompt(J,Q)},K=this.options.runtimeHandlers.sendSession(j,B),G=Y?Math.max(1,Y-Date.now()):0,P=(await gz(K,G)).result,U=Date.now(),F=KZ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:U-H,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,bY())}catch(A){let V=A instanceof PZ;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=A instanceof Error?A.message:String(A),K=Date.now(),G=KZ({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-H,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(J);if(!W)return;let Z=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.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:Z,errorMessage:W.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let W={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
232
+ `)}function K9($){let f=wz($.specs);Mz(f,{recursive:!0});let J=qz(f,`${$.run.runId}.md`),W=`${Sz($.run,$.spec,$.data.triggerEvent)}
233
+ ${hz($.data)}`;return yz(J,W,"utf8"),J}class G9{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let W=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=W)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var bz=15000,kz=90,kY=["rules","skills","plugins"];function Iz($,f){return new Set($.extensions??kY).has(f)}function xz($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let W of $.tools)J[W]={enabled:!0,autoApprove:!0};if(f==="yolo")J[J0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function mz($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} 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(`
234
+ `)}class P9 extends Error{constructor($){super($);this.name="TimeoutError"}}async function gz($,f){if(f<=0)return $;let J,W=new Promise((Z,Q)=>{J=setTimeout(()=>{Q(new P9("cron run timed out"))},f)});try{return await Promise.race([$,W])}finally{if(J)clearTimeout(J)}}class MJ{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 G9($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??kz)*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??bz);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 f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,W])=>{if(W.sessionId)try{await this.options.runtimeHandlers.abortSession(W.sessionId)}catch{}try{this.store.requeueRun({runId:J,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:bY(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let W=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,W)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let Q=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,H=Date.now(),Y;if(J.timeoutSeconds&&J.timeoutSeconds>0)Y=H+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let A=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(A)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:A,prompt:this.buildPrompt(J,Q)},K=this.options.runtimeHandlers.sendSession(j,B),G=Y?Math.max(1,Y-Date.now()):0,P=(await gz(K,G)).result,U=Date.now(),F=K9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:P.text,usage:P.usage,toolCalls:P.toolCalls,durationMs:U-H,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,bY())}catch(A){let V=A instanceof P9;if(j&&V)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=A instanceof Error?A.message:String(A),K=Date.now(),G=K9({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-H,triggerEvent:Q}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let W=this.store.getRun(J);if(!W)return;let Z=W.status==="done"?"success":W.status==="cancelled"?"aborted":W.status==="running"?"running":W.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.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:Z,errorMessage:W.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let W={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
235
235
 
236
236
  Trigger event:
237
- ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,W){let Z=mz($.notesDirectory),Q=K2(void 0,Z),j=await a8(f),X=Ez({ide:"Cline Cron",workspaceRoot:f,workspaceName:Cz(f),metadata:j,rules:$.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?K2(X,Q)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),W=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,Q=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:Q,provider:J,model:W,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:xz($,j),configExtensions:kY.filter((X)=>Iz($,X))}}}import{existsSync as HO,readdirSync as YO,readFileSync as AO,statSync as VO}from"node:fs";import{relative as BO}from"node:path";import{resolveCronSpecsDir as KO}from"@cline/shared/storage";function yJ($,f,J,W){let Z=new Set;function Q(j){let X=j.toLowerCase();if(W){let Y=W.indexOf(X);if(Y!==-1)return Y+f}let H=Number(j);if(!Number.isInteger(H)||H<f||H>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return H}for(let j of $.split(",")){if(j==="*"){for(let Y=f;Y<=J;Y+=1)Z.add(Y);continue}let X=j.indexOf("/");if(X!==-1){let Y=j.slice(0,X),A=Number(j.slice(X+1));if(!Number.isInteger(A)||A<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let V=f,B=J;if(Y!=="*"){let K=Y.indexOf("-");if(K!==-1)V=Q(Y.slice(0,K)),B=Q(Y.slice(K+1));else V=Q(Y)}if(V>B)throw Error(`Invalid cron range "${Y}"`);for(let K=V;K<=B;K+=A)Z.add(K);continue}let H=j.indexOf("-");if(H!==-1){let Y=Q(j.slice(0,H)),A=Q(j.slice(H+1));if(Y>A)throw Error(`Invalid cron range "${j}"`);for(let V=Y;V<=A;V+=1)Z.add(V);continue}Z.add(Q(j))}return[...Z].sort((j,X)=>j-X)}var vz=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],xY=["sun","mon","tue","wed","thu","fri","sat"];function qJ($,f,J){let W=$[f];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return W}function UZ($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function FZ($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:yJ(qJ(f,0,$),0,59),hours:yJ(qJ(f,1,$),0,23),daysOfMonth:yJ(qJ(f,2,$),1,31),months:yJ(qJ(f,3,$),1,12,vz),daysOfWeek:yJ(qJ(f,4,$),0,6,xY)}}function RZ($){FZ($)}function mY($,f,J=Date.now()){Hf($,J,f)}var IY=new Map,uz=new Map(xY.map(($,f)=>[$,f]));function gY($){let f=$?.trim();return f?f:void 0}function vY($){let f=IY.get($);if(f)return f;let J=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 IY.set($,J),J}function cz($){let f=gY($);if(!f)return;vY(f).format(new Date)}function dz($,f){let J=vY(f).formatToParts(new Date($)),W=new Map(J.map((j)=>[j.type,j.value])),Z=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=uz.get(Z);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function lz($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function pz($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function rz($,f,J){let W=FZ($),Z=new Date(f);Z.setSeconds(0,0);let Q=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(Q<=X){if(pz(W,dz(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function Hf($,f,J){let W=gY(J);if(W)return cz(W),rz($,f,W);let Z=FZ($),Q=new Date(f);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(Q<=j){let{month:X,dayOfMonth:H,dayOfWeek:Y,hour:A,minute:V}=lz(Q.getTime());if(!Z.months.includes(X)){let B=Z.months.find((G)=>G>X)??UZ(Z.months,"months"),K=B<=X?1:0;Q=new Date(Q.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(H)||!Z.daysOfWeek.includes(Y)){Q=new Date(Q.getFullYear(),Q.getMonth(),H+1,0,0,0,0);continue}if(!Z.hours.includes(A)){let B=Z.hours.find((G)=>G>A)??UZ(Z.hours,"hours"),K=B<=A?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((G)=>G>V)??UZ(Z.minutes,"minutes"),K=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+K,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as iz}from"node:crypto";import nz from"yaml";function az($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function tz($){let f=$.replace(/\r\n/g,`
237
+ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let W=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,W))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,W){let Z=mz($.notesDirectory),Q=K2(void 0,Z),j=await a8(f),X=Ez({ide:"Cline Cron",workspaceRoot:f,workspaceName:Cz(f),metadata:j,rules:$.systemPrompt?void 0:Q,mode:J,providerId:W,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?K2(X,Q)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),W=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,Q=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:Q,provider:J,model:W,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:xz($,j),configExtensions:kY.filter((X)=>Iz($,X))}}}import{existsSync as HO,readdirSync as YO,readFileSync as AO,statSync as VO}from"node:fs";import{relative as BO}from"node:path";import{resolveCronSpecsDir as KO}from"@cline/shared/storage";function yJ($,f,J,W){let Z=new Set;function Q(j){let X=j.toLowerCase();if(W){let Y=W.indexOf(X);if(Y!==-1)return Y+f}let H=Number(j);if(!Number.isInteger(H)||H<f||H>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return H}for(let j of $.split(",")){if(j==="*"){for(let Y=f;Y<=J;Y+=1)Z.add(Y);continue}let X=j.indexOf("/");if(X!==-1){let Y=j.slice(0,X),A=Number(j.slice(X+1));if(!Number.isInteger(A)||A<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let V=f,B=J;if(Y!=="*"){let K=Y.indexOf("-");if(K!==-1)V=Q(Y.slice(0,K)),B=Q(Y.slice(K+1));else V=Q(Y)}if(V>B)throw Error(`Invalid cron range "${Y}"`);for(let K=V;K<=B;K+=A)Z.add(K);continue}let H=j.indexOf("-");if(H!==-1){let Y=Q(j.slice(0,H)),A=Q(j.slice(H+1));if(Y>A)throw Error(`Invalid cron range "${j}"`);for(let V=Y;V<=A;V+=1)Z.add(V);continue}Z.add(Q(j))}return[...Z].sort((j,X)=>j-X)}var vz=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],xY=["sun","mon","tue","wed","thu","fri","sat"];function qJ($,f,J){let W=$[f];if(typeof W!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return W}function U9($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function F9($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:yJ(qJ(f,0,$),0,59),hours:yJ(qJ(f,1,$),0,23),daysOfMonth:yJ(qJ(f,2,$),1,31),months:yJ(qJ(f,3,$),1,12,vz),daysOfWeek:yJ(qJ(f,4,$),0,6,xY)}}function R9($){F9($)}function mY($,f,J=Date.now()){Hf($,J,f)}var IY=new Map,uz=new Map(xY.map(($,f)=>[$,f]));function gY($){let f=$?.trim();return f?f:void 0}function vY($){let f=IY.get($);if(f)return f;let J=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 IY.set($,J),J}function cz($){let f=gY($);if(!f)return;vY(f).format(new Date)}function dz($,f){let J=vY(f).formatToParts(new Date($)),W=new Map(J.map((j)=>[j.type,j.value])),Z=W.get("weekday")?.toLowerCase().slice(0,3)??"",Q=uz.get(Z);if(Q===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(W.get("month")),dayOfMonth:Number(W.get("day")),dayOfWeek:Q,hour:Number(W.get("hour")),minute:Number(W.get("minute"))}}function lz($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function pz($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function rz($,f,J){let W=F9($),Z=new Date(f);Z.setSeconds(0,0);let Q=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(Q<=X){if(pz(W,dz(Q,J)))return Q;Q+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function Hf($,f,J){let W=gY(J);if(W)return cz(W),rz($,f,W);let Z=F9($),Q=new Date(f);Q.setSeconds(0,0),Q=new Date(Q.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(Q<=j){let{month:X,dayOfMonth:H,dayOfWeek:Y,hour:A,minute:V}=lz(Q.getTime());if(!Z.months.includes(X)){let B=Z.months.find((G)=>G>X)??U9(Z.months,"months"),K=B<=X?1:0;Q=new Date(Q.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(H)||!Z.daysOfWeek.includes(Y)){Q=new Date(Q.getFullYear(),Q.getMonth(),H+1,0,0,0,0);continue}if(!Z.hours.includes(A)){let B=Z.hours.find((G)=>G>A)??U9(Z.hours,"hours"),K=B<=A?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(V)){let B=Z.minutes.find((G)=>G>V)??U9(Z.minutes,"minutes"),K=B<=V?1:0;Q=new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),Q.getHours()+K,B,0,0);continue}return Q.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as iz}from"node:crypto";import nz from"yaml";function az($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function tz($){let f=$.replace(/\r\n/g,`
238
238
  `);if(!f.startsWith(`---
239
239
  `))return{frontmatter:void 0,body:$};let J=f.slice(4),W=J.indexOf(`
240
240
  ---`);if(W===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,W),Q=J.slice(W+4);if(Q.startsWith(`
241
- `))Q=Q.slice(1);return{frontmatter:Z,body:Q}}function v0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function sz($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function zZ($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function oz($){let f=zZ($);if(!f)return;let J=v0(f.providerId),W=v0(f.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function ez($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function cY($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let W=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return W;return W.length>0?W:void 0}var $O=new Set(n$);function fO($){let f=cY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!$O.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var JO=new Set(["rules","skills","plugins"]);function WO($){let f=cY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!JO.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function DZ($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function LZ($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function OZ($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>OZ(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${f.map(([J,W])=>`${JSON.stringify(J)}:${OZ(W)}`).join(",")}}`}function dY($,f){let J=iz("sha256");return J.update(OZ($)),J.update(`
242
- `),J.update(f),J.digest("hex")}function ZO($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var QO=["schedule","timezone"],jO=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],XO=["cwd"];function uY($,f,J,W,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:dY(W,J),error:Z}}function Y$($,f,J,W,Z,Q){return{externalId:$,relativePath:f,triggerKind:J,body:W,contentHash:Z,error:Q}}function lY($){let f=$.relativePath.replace(/\\/g,"/"),J=az(f),{frontmatter:W,body:Z}=tz($.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let F=nz.parse(W);if(F&&typeof F==="object"&&!Array.isArray(F))Q=F;else if(F!==null&&F!==void 0)return uY(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(F){return uY(f,J,Z,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let j=dY(Q,Z),X=v0(Q.id),H=X??f;if(J!=="schedule"){for(let F of QO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of XO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let F of jO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is only allowed on .event.md specs`)}let Y=v0(Q.prompt),A=Z.trim(),V=Y??(A.length>0?A:void 0);if(!V)return Y$(H,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=v0(Q.workspaceRoot);if(!B)return Y$(H,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=fO(Q.tools),G=WO(Q.extensions)}catch(F){return Y$(H,f,J,Z,j,F instanceof Error?F.message:String(F))}let R=ez(Q.mode);if(Q.mode!==void 0&&R===void 0)return Y$(H,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:X,title:v0(Q.title)??X??ZO(f),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:v0(Q.systemPrompt),modelSelection:oz(Q.modelSelection),maxIterations:DZ(Q.maxIterations),timeoutSeconds:DZ(Q.timeoutSeconds),tools:K,notesDirectory:v0(Q.notesDirectory),extensions:G,source:v0(Q.source)??"user",tags:sz(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:zZ(Q.metadata)},U;if(J==="schedule"){let F=v0(Q.schedule);if(!F)return Y$(H,f,J,Z,j,"schedule is required for *.cron.md specs");let O=v0(Q.timezone);try{mY(F,O)}catch(D){return Y$(H,f,J,Z,j,D instanceof Error?D.message:String(D))}U={...P,triggerKind:"schedule",schedule:F,timezone:O}}else if(J==="event"){let F=v0(Q.event);if(!F)return Y$(H,f,J,Z,j,"event is required for .event.md specs");U={...P,triggerKind:"event",event:F,filters:zZ(Q.filters),debounceSeconds:LZ(Q.debounceSeconds),dedupeWindowSeconds:LZ(Q.dedupeWindowSeconds),cooldownSeconds:LZ(Q.cooldownSeconds),maxParallel:DZ(Q.maxParallel)}}else U={...P,triggerKind:"one_off"};return{externalId:H,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:U}}function GO($,f){return BO($,f).replace(/\\/g,"/")}function PO($){if(!HO($))return[];let f=[],J=[$];while(J.length>0){let W=J.pop();if(!W)continue;let Z;try{Z=YO(W,{withFileTypes:!0})}catch{continue}for(let Q of Z){let j=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(j);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;f.push(j)}}return f}class _Z{store;cronDir;constructor($){this.store=$.store,this.cronDir=KO($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=PO(this.cronDir),J=new Set;for(let Z of f){let Q=GO(this.cronDir,Z);J.add(Q),$.scanned+=1;let j=await this.reconcileFile(Q,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of W)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),W,Z;try{W=AO(f,"utf8"),Z=VO(f).mtimeMs}catch{return}let j=lY({relativePath:$,raw:W}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),W=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=Hf($.scheduleExpr,W,$.timezone),Q=new Date(Z).toISOString();if($.nextRunAt!==Q)this.store.updateSpecNextRunAt($.specId,Q)}catch{}}}import{existsSync as UO,mkdirSync as FO,watch as RO}from"node:fs";import{relative as DO,resolve as LO}from"node:path";var zO=250;class TZ{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??zO),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{FO($,{recursive:!0}),this.watcher=RO($,{recursive:!0},(f,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}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 f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=LO(this.reconciler.getCronDir(),$);if(!UO(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=DO(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as wJ}from"node:crypto";import{asOptionalString as I,asString as t,loadSqliteDb as _O,nowIso as R0}from"@cline/shared/db";import{resolveCronDbPath as TO}from"@cline/shared/storage";var OO=[`CREATE TABLE IF NOT EXISTS cron_specs (
241
+ `))Q=Q.slice(1);return{frontmatter:Z,body:Q}}function v0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function sz($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function z9($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function oz($){let f=z9($);if(!f)return;let J=v0(f.providerId),W=v0(f.modelId);if(J===void 0&&W===void 0)return;return{providerId:J,modelId:W}}function ez($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function cY($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let W=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return W;return W.length>0?W:void 0}var $O=new Set(n$);function fO($){let f=cY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!$O.has(W));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var JO=new Set(["rules","skills","plugins"]);function WO($){let f=cY($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((W)=>!JO.has(W));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function D9($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function L9($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function O9($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>O9(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[W])=>J<W?-1:J>W?1:0),`{${f.map(([J,W])=>`${JSON.stringify(J)}:${O9(W)}`).join(",")}}`}function dY($,f){let J=iz("sha256");return J.update(O9($)),J.update(`
242
+ `),J.update(f),J.digest("hex")}function ZO($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var QO=["schedule","timezone"],jO=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],XO=["cwd"];function uY($,f,J,W,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:dY(W,J),error:Z}}function Y$($,f,J,W,Z,Q){return{externalId:$,relativePath:f,triggerKind:J,body:W,contentHash:Z,error:Q}}function lY($){let f=$.relativePath.replace(/\\/g,"/"),J=az(f),{frontmatter:W,body:Z}=tz($.raw),Q={};if(W!==void 0&&W.trim().length>0)try{let F=nz.parse(W);if(F&&typeof F==="object"&&!Array.isArray(F))Q=F;else if(F!==null&&F!==void 0)return uY(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(F){return uY(f,J,Z,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let j=dY(Q,Z),X=v0(Q.id),H=X??f;if(J!=="schedule"){for(let F of QO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of XO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let F of jO)if(Q[F]!==void 0)return Y$(H,f,J,Z,j,`field "${F}" is only allowed on .event.md specs`)}let Y=v0(Q.prompt),A=Z.trim(),V=Y??(A.length>0?A:void 0);if(!V)return Y$(H,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=v0(Q.workspaceRoot);if(!B)return Y$(H,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=fO(Q.tools),G=WO(Q.extensions)}catch(F){return Y$(H,f,J,Z,j,F instanceof Error?F.message:String(F))}let R=ez(Q.mode);if(Q.mode!==void 0&&R===void 0)return Y$(H,f,J,Z,j,"mode must be one of: act, plan, yolo");let P={id:X,title:v0(Q.title)??X??ZO(f),prompt:V,workspaceRoot:B,mode:R??"yolo",systemPrompt:v0(Q.systemPrompt),modelSelection:oz(Q.modelSelection),maxIterations:D9(Q.maxIterations),timeoutSeconds:D9(Q.timeoutSeconds),tools:K,notesDirectory:v0(Q.notesDirectory),extensions:G,source:v0(Q.source)??"user",tags:sz(Q.tags),enabled:typeof Q.enabled==="boolean"?Q.enabled:!0,metadata:z9(Q.metadata)},U;if(J==="schedule"){let F=v0(Q.schedule);if(!F)return Y$(H,f,J,Z,j,"schedule is required for *.cron.md specs");let O=v0(Q.timezone);try{mY(F,O)}catch(D){return Y$(H,f,J,Z,j,D instanceof Error?D.message:String(D))}U={...P,triggerKind:"schedule",schedule:F,timezone:O}}else if(J==="event"){let F=v0(Q.event);if(!F)return Y$(H,f,J,Z,j,"event is required for .event.md specs");U={...P,triggerKind:"event",event:F,filters:z9(Q.filters),debounceSeconds:L9(Q.debounceSeconds),dedupeWindowSeconds:L9(Q.dedupeWindowSeconds),cooldownSeconds:L9(Q.cooldownSeconds),maxParallel:D9(Q.maxParallel)}}else U={...P,triggerKind:"one_off"};return{externalId:H,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:U}}function GO($,f){return BO($,f).replace(/\\/g,"/")}function PO($){if(!HO($))return[];let f=[],J=[$];while(J.length>0){let W=J.pop();if(!W)continue;let Z;try{Z=YO(W,{withFileTypes:!0})}catch{continue}for(let Q of Z){let j=`${W}/${Q.name}`;if(Q.isDirectory()){if(Q.name==="reports")continue;J.push(j);continue}if(!Q.isFile())continue;if(!Q.name.endsWith(".md"))continue;f.push(j)}}return f}class _9{store;cronDir;constructor($){this.store=$.store,this.cronDir=KO($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=PO(this.cronDir),J=new Set;for(let Z of f){let Q=GO(this.cronDir,Z);J.add(Q),$.scanned+=1;let j=await this.reconcileFile(Q,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let W=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of W)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),W,Z;try{W=AO(f,"utf8"),Z=VO(f).mtimeMs}catch{return}let j=lY({relativePath:$,raw:W}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),W=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=Hf($.scheduleExpr,W,$.timezone),Q=new Date(Z).toISOString();if($.nextRunAt!==Q)this.store.updateSpecNextRunAt($.specId,Q)}catch{}}}import{existsSync as UO,mkdirSync as FO,watch as RO}from"node:fs";import{relative as DO,resolve as LO}from"node:path";var zO=250;class T9{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??zO),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{FO($,{recursive:!0}),this.watcher=RO($,{recursive:!0},(f,J)=>{if(!J)return;let W=String(J).replace(/\\/g,"/");if(!W.endsWith(".md"))return;if(W.startsWith("reports/"))return;this.scheduleReconcile(W)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}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 f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=LO(this.reconciler.getCronDir(),$);if(!UO(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=DO(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as wJ}from"node:crypto";import{asOptionalString as I,asString as t,loadSqliteDb as _O,nowIso as R0}from"@cline/shared/db";import{resolveCronDbPath as TO}from"@cline/shared/storage";var OO=[`CREATE TABLE IF NOT EXISTS cron_specs (
243
243
  spec_id TEXT PRIMARY KEY,
244
244
  external_id TEXT NOT NULL,
245
245
  source_path TEXT NOT NULL UNIQUE,
@@ -330,11 +330,11 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
330
330
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
331
331
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
332
332
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
333
- ON cron_specs(source_path);`];function pY($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of OO)$.exec(f)}function H5($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function NZ($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let W=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function Yf($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function G1($){return{specId:t($.spec_id),externalId:t($.external_id),sourcePath:t($.source_path),triggerKind:t($.trigger_kind),sourceMtimeMs:Yf($.source_mtime_ms),sourceHash:I($.source_hash),parseStatus:t($.parse_status)==="invalid"?"invalid":"valid",parseError:I($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:t($.title),prompt:I($.prompt),workspaceRoot:I($.workspace_root),scheduleExpr:I($.schedule_expr),timezone:I($.timezone),eventType:I($.event_type),filters:H5(I($.filters_json)),debounceSeconds:Yf($.debounce_seconds),dedupeWindowSeconds:Yf($.dedupe_window_seconds),cooldownSeconds:Yf($.cooldown_seconds),mode:I($.mode),systemPrompt:I($.system_prompt),providerId:I($.provider_id),modelId:I($.model_id),maxIterations:Yf($.max_iterations),timeoutSeconds:Yf($.timeout_seconds),maxParallel:Yf($.max_parallel),tools:NZ(I($.tools_json),{preserveEmpty:!0}),notesDirectory:I($.notes_directory),extensions:NZ(I($.extensions_json),{preserveEmpty:!0}),source:I($.source),tags:NZ(I($.tags_json)),metadata:H5(I($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:I($.last_materialized_run_id),lastRunAt:I($.last_run_at),nextRunAt:I($.next_run_at),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function MZ($){return{runId:t($.run_id),specId:t($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:t($.trigger_kind),status:t($.status),claimToken:I($.claim_token),claimStartedAt:I($.claim_started_at),claimUntilAt:I($.claim_until_at),scheduledFor:I($.scheduled_for),triggerEventId:I($.trigger_event_id),startedAt:I($.started_at),completedAt:I($.completed_at),sessionId:I($.session_id),reportPath:I($.report_path),error:I($.error),attemptCount:Number($.attempt_count??0),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function rY($){return{eventId:t($.event_id),eventType:t($.event_type),source:t($.source),subject:I($.subject),occurredAt:t($.occurred_at),receivedAt:t($.received_at),workspaceRoot:I($.workspace_root),dedupeKey:I($.dedupe_key),payload:H5(I($.payload_json)),attributes:H5(I($.attributes_json)),processingStatus:t($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:I($.error),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function iY($){return $?JSON.stringify($):null}var NO=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function nY($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function MO($,f,J,W){for(let Z of NO){let Q=$[Z],j=f[Z];if(nY(Q)!==nY(j))return!0}if(J===!1&&W===!0)return!0;return!1}function yO($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function qO($){return`hub/schedules/${$}.cron.md`}function wO($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function yZ($){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((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:wO($)}}function aY($){return JSON.stringify(yZ($))}function SO($,f){let J=$.metadata?{...$.metadata}:{},W=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:W,tags:f.tags??$.tags,runtimeOptions:Q,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class SJ{db;constructor($={}){let f=$.dbPath??TO();this.db=_O(f),pY(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?G1(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?G1(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?G1(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>G1(j))}createHubSchedule($){let f=`sched_${wJ()}`,J=this.upsertSpec({externalId:f,sourcePath:qO(f),triggerKind:"schedule",sourceHash:aY($),parseStatus:"valid",spec:yZ($)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
333
+ ON cron_specs(source_path);`];function pY($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of OO)$.exec(f)}function H5($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function N9($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let W=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return W;return W.length>0?W:void 0}catch{return}}function Yf($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function G1($){return{specId:t($.spec_id),externalId:t($.external_id),sourcePath:t($.source_path),triggerKind:t($.trigger_kind),sourceMtimeMs:Yf($.source_mtime_ms),sourceHash:I($.source_hash),parseStatus:t($.parse_status)==="invalid"?"invalid":"valid",parseError:I($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:t($.title),prompt:I($.prompt),workspaceRoot:I($.workspace_root),scheduleExpr:I($.schedule_expr),timezone:I($.timezone),eventType:I($.event_type),filters:H5(I($.filters_json)),debounceSeconds:Yf($.debounce_seconds),dedupeWindowSeconds:Yf($.dedupe_window_seconds),cooldownSeconds:Yf($.cooldown_seconds),mode:I($.mode),systemPrompt:I($.system_prompt),providerId:I($.provider_id),modelId:I($.model_id),maxIterations:Yf($.max_iterations),timeoutSeconds:Yf($.timeout_seconds),maxParallel:Yf($.max_parallel),tools:N9(I($.tools_json),{preserveEmpty:!0}),notesDirectory:I($.notes_directory),extensions:N9(I($.extensions_json),{preserveEmpty:!0}),source:I($.source),tags:N9(I($.tags_json)),metadata:H5(I($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:I($.last_materialized_run_id),lastRunAt:I($.last_run_at),nextRunAt:I($.next_run_at),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function M9($){return{runId:t($.run_id),specId:t($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:t($.trigger_kind),status:t($.status),claimToken:I($.claim_token),claimStartedAt:I($.claim_started_at),claimUntilAt:I($.claim_until_at),scheduledFor:I($.scheduled_for),triggerEventId:I($.trigger_event_id),startedAt:I($.started_at),completedAt:I($.completed_at),sessionId:I($.session_id),reportPath:I($.report_path),error:I($.error),attemptCount:Number($.attempt_count??0),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function rY($){return{eventId:t($.event_id),eventType:t($.event_type),source:t($.source),subject:I($.subject),occurredAt:t($.occurred_at),receivedAt:t($.received_at),workspaceRoot:I($.workspace_root),dedupeKey:I($.dedupe_key),payload:H5(I($.payload_json)),attributes:H5(I($.attributes_json)),processingStatus:t($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:I($.error),createdAt:t($.created_at),updatedAt:t($.updated_at)}}function iY($){return $?JSON.stringify($):null}var NO=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function nY($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function MO($,f,J,W){for(let Z of NO){let Q=$[Z],j=f[Z];if(nY(Q)!==nY(j))return!0}if(J===!1&&W===!0)return!0;return!1}function yO($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function qO($){return`hub/schedules/${$}.cron.md`}function wO($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function y9($){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((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:wO($)}}function aY($){return JSON.stringify(y9($))}function SO($,f){let J=$.metadata?{...$.metadata}:{},W=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,Q=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:W,tags:f.tags??$.tags,runtimeOptions:Q,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class SJ{db;constructor($={}){let f=$.dbPath??TO();this.db=_O(f),pY(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?G1(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?G1(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?G1(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>G1(j))}createHubSchedule($){let f=`sched_${wJ()}`,J=this.upsertSpec({externalId:f,sourcePath:qO(f),triggerKind:"schedule",sourceHash:aY($),parseStatus:"valid",spec:y9($)});this.initializeScheduleNextRun(J.record.specId);let W=this.getSpec(J.record.specId);if(!W)throw Error("failed to create hub schedule");return W}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
334
334
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
335
335
  ORDER BY created_at ASC LIMIT 1`).get($);return f?G1(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let Q of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${Q.trim()}"%`);let W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
336
336
  WHERE ${f.join(" AND ")}
337
- ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>G1(Q))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let W=SO(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:aY(W),parseStatus:"valid",spec:yZ(W)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:R0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
337
+ ORDER BY created_at DESC LIMIT ?`).all(...J,W).map((Q)=>G1(Q))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let W=SO(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:aY(W),parseStatus:"valid",spec:y9(W)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:R0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
338
338
  WHERE trigger_kind = 'event'
339
339
  AND event_type = ?
340
340
  AND enabled = 1
@@ -372,7 +372,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
372
372
  last_run_at = ?,
373
373
  next_run_at = ?,
374
374
  updated_at = ?
375
- WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?MZ(f):void 0}insertEventLog($,f={}){let J=R0(),W=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let Q=$.eventType.trim();if(!Q)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||W,H=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
375
+ WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(W){throw this.db.exec("ROLLBACK;"),W}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?M9(f):void 0}insertEventLog($,f={}){let J=R0(),W=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let Q=$.eventType.trim();if(!Q)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||W,H=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
376
376
  event_id, event_type, source, subject,
377
377
  occurred_at, received_at, workspace_root, dedupe_key,
378
378
  payload_json, attributes_json, processing_status,
@@ -387,7 +387,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
387
387
  suppressed_count = COALESCE(?, suppressed_count),
388
388
  error = ?,
389
389
  updated_at = ?
390
- WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,R0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let H of j)J.push(H)}}let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>MZ(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
390
+ WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,R0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let H of j)J.push(H)}}let W=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${W} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>M9(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
391
391
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
392
392
  WHERE r.spec_id = ?
393
393
  AND r.trigger_kind = 'event'
@@ -405,7 +405,7 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
405
405
  AND r.status = 'queued'
406
406
  AND e.dedupe_key = ?
407
407
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
408
- LIMIT 1`).get($.specId,$.dedupeKey);return f?MZ(f):void 0}updateQueuedEventRunForDebounce($){let f=R0();if((this.db.prepare(`UPDATE cron_runs SET
408
+ LIMIT 1`).get($.specId,$.dedupeKey);return f?M9(f):void 0}updateQueuedEventRunForDebounce($){let f=R0();if((this.db.prepare(`UPDATE cron_runs SET
409
409
  trigger_event_id = ?,
410
410
  scheduled_for = ?,
411
411
  updated_at = ?
@@ -475,11 +475,11 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
475
475
  error = ?,
476
476
  scheduled_for = COALESCE(?, scheduled_for),
477
477
  updated_at = ?
478
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,R0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,R0(),$)}}class hJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new SJ({dbPath:$.dbPath});let f=$.specs;this.reconciler=new _Z({store:this.store,specs:f}),this.materializer=new NJ({store:this.store}),this.eventIngress=new BZ({store:this.store,logger:$.logger}),this.runner=new MJ({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new TZ({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var ZA={};w(ZA,{manifestToSessionRecord:()=>A5,listSessionHistoryFromBackend:()=>hZ,listSessionHistory:()=>V5,hydrateSessionHistory:()=>WA});import{readdir as bO,readFile as $A}from"node:fs/promises";import{join as fA}from"node:path";import{formatDisplayUserInput as kO,normalizeUserInput as IO}from"@cline/shared";import{resolveSessionDataDir as JA}from"@cline/shared/storage";import{existsSync as hO}from"node:fs";import{readFile as CO}from"node:fs/promises";import{formatDisplayUserInput as tY}from"@cline/shared";class CJ{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function P1($){let f=$?.trim();if(!f||!hO(f))return[];try{let J=(await CO(f,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return sY(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let Z=W.messages;if(Array.isArray(Z))return sY(Z)}return[]}catch{return[]}}function EO($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:tY($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:tY(f.text)}})}}function sY($){return $.map(EO)}function qZ($){return $?{...$}:void 0}async function oY($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let W=await f.upsertSubagentSessionFromHook($);if(!W)return;await f.appendSubagentHookAudit(W,$),await f.applySubagentStatus(W,$)}function EJ($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function u0($){let f=EJ($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function Y5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xO($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function SZ($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function mO($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function gO($){return $.isSubagent!==!0&&!EJ($.parentSessionId)}function vO($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let W of f){let Z=Number.parseInt(W,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function A5($){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 uO($){let f=SZ($);if(f===0)return[];let J=JA(),Z=(await bO(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:vO(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=fA(J,X,`${X}.json`),Y=await $A(H,"utf8").catch(()=>{return});if(!Y)return;let A;try{A=JSON.parse(Y)}catch{return}let V=y0.safeParse(A);if(!V.success)return;return A5(V.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function cO($,f,J){let W=SZ(f);if(W===0)return await $.listSessions(0),[];let Z=J.includeSubagents?W:mO(W),Q=await $.listSessions(Z);return(J.includeSubagents?Q:Q.filter(gO)).slice(0,W)}function dO($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let Z=W.text?.trim();if(Z)f.push(Z)}return f.join(`
478
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,R0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,R0(),$)}}class hJ{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new SJ({dbPath:$.dbPath});let f=$.specs;this.reconciler=new _9({store:this.store,specs:f}),this.materializer=new NJ({store:this.store}),this.eventIngress=new B9({store:this.store,logger:$.logger}),this.runner=new MJ({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new T9({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let W=$.logger;if(W)if(W.error)W.error("cron.watcher.failed",{error:J});else W.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var ZA={};w(ZA,{manifestToSessionRecord:()=>A5,listSessionHistoryFromBackend:()=>h9,listSessionHistory:()=>V5,hydrateSessionHistory:()=>WA});import{readdir as bO,readFile as $A}from"node:fs/promises";import{join as fA}from"node:path";import{formatDisplayUserInput as kO,normalizeUserInput as IO}from"@cline/shared";import{resolveSessionDataDir as JA}from"@cline/shared/storage";import{existsSync as hO}from"node:fs";import{readFile as CO}from"node:fs/promises";import{formatDisplayUserInput as tY}from"@cline/shared";class CJ{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function P1($){let f=$?.trim();if(!f||!hO(f))return[];try{let J=(await CO(f,"utf8")).trim();if(!J)return[];let W=JSON.parse(J);if(Array.isArray(W))return sY(W);if(W&&typeof W==="object"&&!Array.isArray(W)){let Z=W.messages;if(Array.isArray(Z))return sY(Z)}return[]}catch{return[]}}function EO($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:tY($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:tY(f.text)}})}}function sY($){return $.map(EO)}function q9($){return $?{...$}:void 0}async function oY($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let W=await f.upsertSubagentSessionFromHook($);if(!W)return;await f.appendSubagentHookAudit(W,$),await f.applySubagentStatus(W,$)}function EJ($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function u0($){let f=EJ($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function Y5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xO($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function S9($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function mO($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function gO($){return $.isSubagent!==!0&&!EJ($.parentSessionId)}function vO($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let W of f){let Z=Number.parseInt(W,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function A5($){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 uO($){let f=S9($);if(f===0)return[];let J=JA(),Z=(await bO(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:vO(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=fA(J,X,`${X}.json`),Y=await $A(H,"utf8").catch(()=>{return});if(!Y)return;let A;try{A=JSON.parse(Y)}catch{return}let V=y0.safeParse(A);if(!V.success)return;return A5(V.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function cO($,f,J){let W=S9(f);if(W===0)return await $.listSessions(0),[];let Z=J.includeSubagents?W:mO(W),Q=await $.listSessions(Z);return(J.includeSubagents?Q:Q.filter(gO)).slice(0,W)}function dO($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let W=J;if(W.type!=="text")continue;let Z=W.text?.trim();if(Z)f.push(Z)}return f.join(`
479
479
  `).trim()}function eY($){return $.replace(/\s+/g," ").trim()}function lO($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function pO($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let W=eY(dO(J.content));if(!W)continue;let Z=f==="user"?eY(kO(W)):W,Q=IO(Z.split(`
480
- `)[0]??Z);return lO(Q,50)}return}function rO($){let f=0;for(let J of $)f+=Y5(J.metrics?.cost)??0;return f}function iO($){let f,J;for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(!f)f=u0(Z.modelInfo?.provider);if(!J)J=u0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function nO($){return u0($?.provider)??u0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function aO($){return u0($?.model)??u0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function wZ($,f){let J=xO($.metadata),W=EJ(f?.title)??EJ(J?.title),Z=Y5(f?.totalCost)??Y5(J?.totalCost),Q=J||W!==void 0||Z!==void 0?{...J??{},...W!==void 0?{title:W}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:u0(f?.provider)??u0($.provider)??nO(J)??"",model:u0(f?.model)??u0($.model)??aO(J)??"",metadata:Q}}function tO($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function sO($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!tO(J)}async function oO($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let W=await $.readSessionMessages(J.sessionId);return sO(J,W)?{...J,status:"idle"}:J}))}async function WA($,f){return await Promise.all(f.map(async(J)=>{let W=wZ(J),Z=Boolean(EJ(W.metadata?.title)),Q=Boolean(u0(W.provider)),j=Boolean(u0(W.model)),X=Y5(W.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&Q&&j&&H)return W;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return W;let A=iO(Y),V=rO(Y);return wZ(J,{title:Z?void 0:pO(Y),provider:Q?void 0:A.provider,model:j?void 0:A.model,totalCost:H||V<=0?void 0:V})}))}async function V5($,f={}){let J=SZ(f.limit),W=f.includeSubagents===!0,Z=await cO($,J,{includeSubagents:W}),Q=f.includeManifestFallback===!0&&Z.length<J?await uO(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let Y of[...Z,...Q]){if(j.has(Y.sessionId))continue;j.set(Y.sessionId,Y)}let X=Q.length===0?Z:Array.from(j.values()).sort((Y,A)=>A.startedAt.localeCompare(Y.startedAt)).slice(0,J),H=await oO($,X);if(f.hydrate===!1)return H.map((Y)=>wZ(Y));return await WA($,H)}async function eO($){let f=$.trim();if(!f)return;let J=fA(JA(),f,`${f}.json`),W=await $A(J,"utf8").catch(()=>{return});if(!W)return;try{let Z=y0.safeParse(JSON.parse(W));return Z.success?Z.data.messages_path:void 0}catch{return}}async function hZ($,f={}){let J=new Map;return await V5({listSessions:async(Z)=>{let Q=await $.listSessions(Z);J.clear();for(let j of Q)J.set(j.sessionId,j);return Q.map(T8)},readSessionMessages:async(Z)=>{let Q=J.get(Z)?.messagesPath??await eO(Z);return await P1(Q)}},f)}var HV={};w(HV,{resolveSessionBackend:()=>BQ,createRuntimeHost:()=>y2});import{captureSdkError as jV}from"@cline/shared";import{createSessionId as d_,resolveHubCommandTimeoutMs as l_}from"@cline/shared";import{spawn as z_}from"node:child_process";import{closeSync as O_,mkdirSync as __,openSync as T_}from"node:fs";import{basename as N_,dirname as M_,join as y_}from"node:path";import{fileURLToPath as q_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as w_,isHubDaemonProcess as FA,withResolvedClineBuildEnv as S_}from"@cline/shared";import{createHash as $_,randomBytes as f_}from"node:crypto";import{existsSync as J_}from"node:fs";import{chmod as W_,mkdir as CZ,readFile as YA,rm as EZ,writeFile as AA}from"node:fs/promises";import{dirname as VA,join as bZ}from"node:path";import{resolveClineDataDir as kJ,resolveClineDir as BA}from"@cline/shared/storage";var jA="0.0.43-nightly.1780975055";var bJ={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:jA,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^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"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Z_="CLINE_HUB_DISCOVERY_PATH",Q_="CLINE_HUB_BUILD_ID",XA=30000,j_=15000,X_=100;function H_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Y_($){return $_("sha256").update($).digest("hex").slice(0,12)}function A_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function B5(){return f_(32).toString("hex")}function V_($){return new Promise((f)=>setTimeout(f,$))}function B_($){return`${$}.lock`}async function K_($){try{let f=JSON.parse(await YA(bZ($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function HA($){await EZ($,{recursive:!0,force:!0}).catch(()=>{return})}function U1(){return process.env[Q_]?.trim()||String(bJ.version)}function x$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${Y_($)}`,J=process.env[Z_]?.trim()||bZ(kJ(),"locks","hub","owners",`${H_(f)}.json`);return{ownerId:f,discoveryPath:J}}function KA($=`hub-${Date.now().toString(36)}`){return x$($)}async function K0($){try{let f=JSON.parse(await YA($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function K5($,f){await CZ(VA($),{recursive:!0}),await EZ($,{force:!0}).catch(()=>{return}),await AA($,`${JSON.stringify(f,null,2)}
481
- `,{encoding:"utf8",mode:384}),await W_($,384)}async function c0($){await EZ($,{force:!0}).catch(()=>{return})}async function G5($,f){let J=B_($);await CZ(VA(J),{recursive:!0});let W=Date.now()+j_;while(!0)try{await CZ(J,{recursive:!1}),await AA(bZ(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
482
- `,"utf8");try{return await f()}finally{await HA(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await K_(J),X=j?Date.now()-Date.parse(j.acquiredAt):XA+1;if(!j||!A_(j.pid)||X>XA){await HA(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await V_(X_)}}async function A$($){try{let f=await fetch(kZ($));if(!f.ok)return;return await f.json()}catch{return}}function $$($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function kZ($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function GA($){return J_($)}import{CLINE_HUB_DEV_PORT as G_,CLINE_HUB_PORT as P_,resolveClineBuildEnv as U_}from"@cline/shared";var F_="CLINE_HUB_HOST",R_="CLINE_HUB_PORT",D_="CLINE_HUB_PATHNAME",IZ="127.0.0.1",xZ=P_,mZ="/hub";function PA($){return U_($)==="development"?G_:xZ}function gZ($={}){return($.env??process.env)[F_]?.trim()||IZ}function R2($={}){let J=($.env??process.env)[R_]?.trim();if(!J)return PA($);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return PA($);return W}function vZ($={}){return($.env??process.env)[D_]?.trim()||mZ}function d0($={},f={}){return{host:$.host??gZ(f),port:$.port??R2(f),pathname:$.pathname??vZ(f)}}var L_="shared:cline";function UA($){let f=C$($.trim());return x$(`workspace:${f||$.trim()}`)}function Y0($=L_){return x$($)}var h_=8000,C_=200,E_=3000,b_=100,k_=[100,250,500,1000,2000],I_="--cline-hub-daemon";function x_($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function m_(){try{let $=y_(kJ(),"logs","hub-daemon.log");return __(M_($),{recursive:!0}),{fd:T_($,"a"),logPath:$}}catch{return}}function IJ($){let f=$.buildId?.trim();return!!f&&f===U1()}async function Af($){try{return await A$($)}catch{return}}async function g_($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await Af($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,b_))}return!1}async function xJ($,f){if(IJ($))return;if(await mJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await g_($.url,E_),await c0(f).catch(()=>{return})}function v_(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return q_(new URL(`./entry.${$}`,import.meta.url))}function u_($,f){let J=v_(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let Z=N_(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=Q?[I_]:[...j?["--conditions=development"]:[],J];return{launcher:W,args:[...X,"--cwd",$,...x_(f)],cwd:$,env:{...S_(process.env),CLINE_NO_INTERACTIVE:"1",[w_]:"1"}}}function c_($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function uZ($,f={}){if(FA())return;let J=u_($,f),W=m_();try{z_(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)O_(W.fd)}}async function D2($,f={}){for(let J=0;;J++)try{uZ($,f);return}catch(W){let Z=k_[J];if(!c_(W)||Z===void 0)throw W;await new Promise((Q)=>setTimeout(Q,Z))}}function P5($,f={}){if(FA())return;let J=Y0(),W=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=d0(f),Q=$$(Z.host,Z.port,Z.pathname);K0(J.discoveryPath).then(async(j)=>{if(j?.url){let A=await Af(j.url);if(A?.url&&IJ(A)&&await V$(A.url,{authToken:j.authToken}))return;if(A?.url)await xJ({...A,authToken:j.authToken},J.discoveryPath);else await c0(J.discoveryPath).catch(()=>{return})}let X=await Af(Q);if(X?.url)await xJ(X,J.discoveryPath);let Y=!W&&Z.port!==0?{...Z,port:0}:Z;await D2($,Y)}).catch(()=>{})}async function RA($,f={}){let J=Y0(),W=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=d0(f),j=$$(Q.host,Q.port,Q.pathname),X=(K)=>{if(!W)F1(K.url,K.authToken);return K},H=await K0(J.discoveryPath);if(H?.url){let K=await Af(H.url);if(K?.url&&IJ(K)&&await V$(K.url,{authToken:H.authToken}))return X({url:K.url,authToken:H.authToken});if(K?.url)await xJ({...K,authToken:H.authToken},J.discoveryPath);else await c0(J.discoveryPath).catch(()=>{return})}let Y=await Af(j);if(Y?.url)await xJ(Y,J.discoveryPath);let V=!Z&&Q.port!==0?{...Q,port:0}:Q;await D2($,V);let B=Date.now()+h_;while(Date.now()<B){let K=await K0(J.discoveryPath);if(K?.url){let R=await Af(K.url);if(R?.url&&IJ(R)&&await V$(R.url,{authToken:K.authToken}))return X({url:R.url,authToken:K.authToken})}let G=await Af(j);if(G?.url&&!IJ(G))await xJ(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,C_))}throw Error("Timed out waiting for detached hub startup.")}function p_(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function _A($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return _A($.data);return String($)}function r_($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function DA($){let f=$,J=r_(f.reason);return new T0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:cZ,{closeCode:f.code,closeReason:J||void 0})}function i_($,f){if($ instanceof T0)return $;if($ instanceof Error)return new T0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new T0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new T0("hub_connect_failed",J);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new T0("hub_connect_failed",W?`Failed to connect to hub at ${f.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var n_=8000,a_=200,LA="*",zA=8000,t_="cline-hub-auth.",TA=new Map,NA=new Set,s_=3000,o_=3000,e_=100,cZ="Hub connection closed",$T=250,fT=5000,OA=0.5;class T0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function pZ($){return $ instanceof T0}class L2 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function U5($,f){return $ instanceof L2&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function MA($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=rZ($.toString());return J?TA.get(J):void 0}function JT($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function rZ($){if(!JT($))return;let f=new URL(R1($));return f.search="",f.hash="",f.toString()}function dZ($){let f=rZ($);return!!f&&NA.has(f)}function F1($,f){let J=rZ($);if(J){if(NA.add(J),f?.trim())TA.set(J,f)}return $}class f${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new T0("hub_connection_closed",cZ);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||MA($);$.hash="";let W=new(p_())($.toString(),f?[`${t_}${f}`]:void 0);this.socket=W;let Z=!1;this.connectPromise=new Promise((Q,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new T0("hub_connect_timeout",`Timed out connecting to hub after ${zA}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}j(this.lastCloseError)},zA);W.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),Q()}),W.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=i_(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),W.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=DA(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(_A(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!Z)this.lastCloseError=DA(Q),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,W={listener:$,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,W){let Z=0,Q=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,W)}catch(j){if(!Q||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,W){await this.connect();let Z=d_("hubreq_"),Q=l_($,W?.timeoutMs),j=new Promise((H,Y)=>{let A=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new L2($,"hub_command_timeout",`Hub command ${$} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(Z,{resolve:(V)=>{if(A)clearTimeout(A);H(V)},reject:(V)=>{if(A)clearTimeout(A);Y(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok){if(X.error?.code===jf){let H=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new k$(H,X.error.message)}throw new L2($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!dZ(this.currentUrl)||!pZ($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await Vf({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min($T*2**this.reconnectAttempt,fT),f=Math.round($*(1-OA)+Math.random()*$*OA);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!dZ(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await Vf({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 T0("hub_connection_closed",cZ),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new T0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(J)??0)+f;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,W),f>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??LA}subscriptionSessionIdFromKey($){return $===LA?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function R1($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function V$($,f){let J=new f$({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function lZ($,f){let J=R1($),W=await A$(J);if(!W)return{status:"unreachable",url:J};let Z=U1(),Q=W.buildId?.trim();if(!Q||Q!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await V$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function WT($){let f=Date.now()+n_;while(Date.now()<f){let J=await K0($.discoveryPath);if(J?.url){let W=await lZ(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return F1(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,a_))}return}async function ZT($){let f=Date.now()+o_;while(Date.now()<f){if(!(await A$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,e_))}return!1}function QT($,f){try{return R1($)===R1(f)}catch{return!1}}function jT($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function XT($,f,J){let W=new f$({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await W.command("session.list",{limit:500},void 0,{timeoutMs:s_});return!jT(Z.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function gJ($={}){if($.endpoint?.trim()){let Z=await lZ($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=Y0(),J=await K0(f.discoveryPath);if(!J?.url)return;let W=await lZ(J.url);if(W.status==="compatible")return F1(W.url,J.authToken);if(W.status==="build_mismatch")await c0(f.discoveryPath).catch(()=>{return});return}async function Vf($={}){let f=await gJ($);if(f&&await V$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=Y0();return await D2($.workspaceRoot??process.cwd()),await WT(J)}async function mJ($,f){let J=new URL($),W=f?.trim()||MA(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function iZ(){let $=Y0(),f=await K0($.discoveryPath);if(!f?.url)return!1;try{if(await mJ(f.url,f.authToken))return!0}catch{}return!1}async function F5($){if(!dZ($.url))return;let f=Y0(),J=await K0(f.discoveryPath);if(!J?.url||!QT(J.url,$.url))return;if(!await XT(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await iZ())return;if(!await ZT(J.url))return;return await c0(f.discoveryPath).catch(()=>{return}),await Vf({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var gA={};w(gA,{HubRuntimeHost:()=>m$});import{captureSdkError as qA,createSessionId as wA,HUB_CHECKPOINT_CAPABILITY as VT,HUB_COMPACTION_CAPABILITY as BT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as KT,HUB_HOOK_CAPABILITY_PREFIX as GT,HUB_MISTAKE_LIMIT_CAPABILITY as PT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as UT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as FT,isHubToolExecutorName as RT}from"@cline/shared";var yA={};w(yA,{createCoreSessionSnapshot:()=>B$,coreSessionSnapshotToRecord:()=>R5});function HT($){return $?JSON.parse(JSON.stringify($)):void 0}function YT($){return $?JSON.parse(JSON.stringify($)):void 0}function AT($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=W.at(-1),Q=$?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...Z?{latest:Z}:{},history:W}}function B$($){let{session:f}=$,J=HT(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:YT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=AT(J);return W?{checkpoint:W}:{}})()}}function R5($){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 z2($){if(!$)return;return JSON.parse(JSON.stringify($))}var DT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function SA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function hA($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function CA($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function Bf($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function EA($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(RT)){let Q=f.toolExecutors?.[Z];if(typeof Q!=="function")continue;Bf(J,{kind:"toolExecutor",executor:Z,capabilityName:`${UT}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={...CA(j.context),signal:X};return{result:await Q(...H,Y)}})}for(let Z of $?.extraTools??[])Bf(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:z2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:z2(Z.lifecycle)}:{},capabilityName:`${KT}${Z.name}`},async({payload:Q,abortSignal:j,progress:X})=>{let H={...CA(Q.context),signal:j};return{result:await Z.execute(Q.input,{...H,emitUpdate:(A)=>{X({update:A})}})}});let W=$?.hooks;if(W)for(let Z of DT){let Q=W[Z];if(typeof Q!=="function")continue;Bf(J,{kind:"hook",name:Z,capabilityName:`${GT}${Z}`},async({payload:j})=>({control:await Q(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;Bf(J,{kind:"compaction",capabilityName:BT,config:SA($.compaction)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;Bf(J,{kind:"checkpoint",capabilityName:VT,config:SA($.checkpoint)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;Bf(J,{kind:"mistakeLimit",capabilityName:PT},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;Bf(J,{kind:"userInstructionService",capabilityName:FT},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function xA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function LT($){return xA($)??"Capability request was cancelled."}function zT($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function OT($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function _T($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,W=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function bA($){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 nZ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function D1($,f){return nZ($?.[f])??0}function TT($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=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:D1(f,"inputTokens"),outputTokens:D1(f,"outputTokens"),cacheReadTokens:D1(f,"cacheReadTokens"),cacheWriteTokens:D1(f,"cacheWriteTokens"),cost:nZ(f?.totalCost),totalInputTokens:D1(J,"inputTokens"),totalOutputTokens:D1(J,"outputTokens"),totalCacheReadTokens:D1(J,"cacheReadTokens"),totalCacheWriteTokens:D1(J,"cacheWriteTokens"),totalCost:nZ(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:Z}}function NT($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,W=OT(J)?J:J==="failed"?"error":"completed",Z=_T($?.usage??f?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function D5($,f){return $.error?.message??`hub command failed: ${f}`}function vJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function mA($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:G0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:vJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:vJ($.status)==="completed"?0:vJ($.status)==="failed"?1:void 0,status:vJ($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function L1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function MT($){let f=L1($?.snapshot);if(f)return R5(f);let J=$?.session;return J?mA(J):void 0}function kA($,f,J){let W=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??G0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:vJ(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:W,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function IA($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class m${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new CJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=F0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new f$({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!U5($,"session.create"))return!1;let f=await F5({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=EA($.localRuntime,f),W=$.config.sessionId?.trim()||wA(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:z2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??G0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:z2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,f,J.handlers);let Q;try{Q=await Z()}catch(Y){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(W,f,J.handlers);try{Q=await Z()}catch(A){throw this.cleanupPlannedSession(W),A}}else throw Y}let j=L1(Q.payload?.snapshot),X=Q.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(H!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?IA(j,$):kA(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,Z=W?this.resolveCapabilities(W):void 0,Q=W?EA(W.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=W?W.config.sessionId?.trim()||wA():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(j,Q.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:z2({...W.config,sessionId:j}),metadata:{...W.sessionMetadata??{},source:W.source??G0.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:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:z2(W.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let H=L1(X.payload?.snapshot),Y=X.payload?.session,A=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!A){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(A&&j&&A!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(A&&Z)this.sessionCapabilities.set(A,Z);if(A&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(A,Q.handlers);if(A)this.ensureSessionSubscription(A);let V=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:A,startResult:A?{sessionId:A,manifest:H?IA(H,W??{}):kA(A,W??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=L1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let W=f.payload?.session,Z=bA(W?.usage),Q=bA(W?.aggregateUsage);return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:xA(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(I$(J))return;throw J}return MT(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let Q=L1(Z);return Q?[R5(Q)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(mA)}async listSettings($){let f=await this.client.command("settings.list",hA($));if(!f.ok)throw Error(D5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",hA($));if(!f.ok)throw Error(D5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw qA(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(D5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(D5(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return F0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:NT($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=TT($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=L1($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:W}}),J?.interactive===!0&&W0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{qA(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(W,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:W,payload:Y},f).catch((A)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",A,$)})};try{let Y=await Q({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(LT($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Q=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!Z||!Q)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=zT($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:Q,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:Q,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:W,approved:H.approved,reason:H.reason},f).catch(()=>{})}}var vA={};w(vA,{RemoteRuntimeHost:()=>O2});class O2 extends m${constructor($){super({url:R1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var uA={};w(uA,{SqliteSessionStore:()=>G$});import{existsSync as yT,mkdirSync as qT}from"node:fs";import{join as wT}from"node:path";import{asBool as uJ,asOptionalString as K$,asString as g$,ensureSessionSchema as ST,loadSqliteDb as hT,nowIso as L5,toBoolInt as cJ}from"@cline/shared/db";import{resolveDbDataDir as CT}from"@cline/shared/storage";class G${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??CT()}init(){this.getRawDb()}ensureSessionsDir(){if(!yT(this.sessionsDirPath))qT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return wT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=hT(this.sessionDbPath());return ST($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=L5();this.run(`INSERT OR REPLACE INTO sessions (
480
+ `)[0]??Z);return lO(Q,50)}return}function rO($){let f=0;for(let J of $)f+=Y5(J.metrics?.cost)??0;return f}function iO($){let f,J;for(let W=$.length-1;W>=0;W-=1){let Z=$[W];if(!f)f=u0(Z.modelInfo?.provider);if(!J)J=u0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function nO($){return u0($?.provider)??u0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function aO($){return u0($?.model)??u0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function w9($,f){let J=xO($.metadata),W=EJ(f?.title)??EJ(J?.title),Z=Y5(f?.totalCost)??Y5(J?.totalCost),Q=J||W!==void 0||Z!==void 0?{...J??{},...W!==void 0?{title:W}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:u0(f?.provider)??u0($.provider)??nO(J)??"",model:u0(f?.model)??u0($.model)??aO(J)??"",metadata:Q}}function tO($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function sO($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!tO(J)}async function oO($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let W=await $.readSessionMessages(J.sessionId);return sO(J,W)?{...J,status:"idle"}:J}))}async function WA($,f){return await Promise.all(f.map(async(J)=>{let W=w9(J),Z=Boolean(EJ(W.metadata?.title)),Q=Boolean(u0(W.provider)),j=Boolean(u0(W.model)),X=Y5(W.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&Q&&j&&H)return W;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return W;let A=iO(Y),V=rO(Y);return w9(J,{title:Z?void 0:pO(Y),provider:Q?void 0:A.provider,model:j?void 0:A.model,totalCost:H||V<=0?void 0:V})}))}async function V5($,f={}){let J=S9(f.limit),W=f.includeSubagents===!0,Z=await cO($,J,{includeSubagents:W}),Q=f.includeManifestFallback===!0&&Z.length<J?await uO(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let Y of[...Z,...Q]){if(j.has(Y.sessionId))continue;j.set(Y.sessionId,Y)}let X=Q.length===0?Z:Array.from(j.values()).sort((Y,A)=>A.startedAt.localeCompare(Y.startedAt)).slice(0,J),H=await oO($,X);if(f.hydrate===!1)return H.map((Y)=>w9(Y));return await WA($,H)}async function eO($){let f=$.trim();if(!f)return;let J=fA(JA(),f,`${f}.json`),W=await $A(J,"utf8").catch(()=>{return});if(!W)return;try{let Z=y0.safeParse(JSON.parse(W));return Z.success?Z.data.messages_path:void 0}catch{return}}async function h9($,f={}){let J=new Map;return await V5({listSessions:async(Z)=>{let Q=await $.listSessions(Z);J.clear();for(let j of Q)J.set(j.sessionId,j);return Q.map(T8)},readSessionMessages:async(Z)=>{let Q=J.get(Z)?.messagesPath??await eO(Z);return await P1(Q)}},f)}var HV={};w(HV,{resolveSessionBackend:()=>BQ,createRuntimeHost:()=>y2});import{captureSdkError as jV}from"@cline/shared";import{createSessionId as d_,resolveHubCommandTimeoutMs as l_}from"@cline/shared";import{spawn as z_}from"node:child_process";import{closeSync as O_,mkdirSync as __,openSync as T_}from"node:fs";import{basename as N_,dirname as M_,join as y_}from"node:path";import{fileURLToPath as q_}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as w_,isHubDaemonProcess as FA,withResolvedClineBuildEnv as S_}from"@cline/shared";import{createHash as $_,randomBytes as f_}from"node:crypto";import{existsSync as J_}from"node:fs";import{chmod as W_,mkdir as C9,readFile as YA,rm as E9,writeFile as AA}from"node:fs/promises";import{dirname as VA,join as b9}from"node:path";import{resolveClineDataDir as kJ,resolveClineDir as BA}from"@cline/shared/storage";var jA="0.0.44";var bJ={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:jA,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^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"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Z_="CLINE_HUB_DISCOVERY_PATH",Q_="CLINE_HUB_BUILD_ID",XA=30000,j_=15000,X_=100;function H_($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function Y_($){return $_("sha256").update($).digest("hex").slice(0,12)}function A_($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function B5(){return f_(32).toString("hex")}function V_($){return new Promise((f)=>setTimeout(f,$))}function B_($){return`${$}.lock`}async function K_($){try{let f=JSON.parse(await YA(b9($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function HA($){await E9($,{recursive:!0,force:!0}).catch(()=>{return})}function U1(){return process.env[Q_]?.trim()||String(bJ.version)}function x$($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${Y_($)}`,J=process.env[Z_]?.trim()||b9(kJ(),"locks","hub","owners",`${H_(f)}.json`);return{ownerId:f,discoveryPath:J}}function KA($=`hub-${Date.now().toString(36)}`){return x$($)}async function K0($){try{let f=JSON.parse(await YA($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,coreVersion:typeof f.coreVersion==="string"?f.coreVersion:void 0,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function K5($,f){await C9(VA($),{recursive:!0}),await E9($,{force:!0}).catch(()=>{return}),await AA($,`${JSON.stringify(f,null,2)}
481
+ `,{encoding:"utf8",mode:384}),await W_($,384)}async function c0($){await E9($,{force:!0}).catch(()=>{return})}async function G5($,f){let J=B_($);await C9(VA(J),{recursive:!0});let W=Date.now()+j_;while(!0)try{await C9(J,{recursive:!1}),await AA(b9(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
482
+ `,"utf8");try{return await f()}finally{await HA(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await K_(J),X=j?Date.now()-Date.parse(j.acquiredAt):XA+1;if(!j||!A_(j.pid)||X>XA){await HA(J);continue}if(Date.now()>=W)throw Error(`Timed out waiting for hub startup lock ${J}`);await V_(X_)}}async function A$($){try{let f=await fetch(k9($));if(!f.ok)return;return await f.json()}catch{return}}function $$($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function k9($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function GA($){return J_($)}import{CLINE_HUB_DEV_PORT as G_,CLINE_HUB_PORT as P_,resolveClineBuildEnv as U_}from"@cline/shared";var F_="CLINE_HUB_HOST",R_="CLINE_HUB_PORT",D_="CLINE_HUB_PATHNAME",I9="127.0.0.1",x9=P_,m9="/hub";function PA($){return U_($)==="development"?G_:x9}function g9($={}){return($.env??process.env)[F_]?.trim()||I9}function R2($={}){let J=($.env??process.env)[R_]?.trim();if(!J)return PA($);let W=Number.parseInt(J,10);if(!Number.isInteger(W)||W<1||W>65535)return PA($);return W}function v9($={}){return($.env??process.env)[D_]?.trim()||m9}function d0($={},f={}){return{host:$.host??g9(f),port:$.port??R2(f),pathname:$.pathname??v9(f)}}var L_="shared:cline";function UA($){let f=C$($.trim());return x$(`workspace:${f||$.trim()}`)}function Y0($=L_){return x$($)}var h_=8000,C_=200,E_=3000,b_=100,k_=[100,250,500,1000,2000],I_="--cline-hub-daemon";function x_($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function m_(){try{let $=y_(kJ(),"logs","hub-daemon.log");return __(M_($),{recursive:!0}),{fd:T_($,"a"),logPath:$}}catch{return}}function IJ($){let f=$.buildId?.trim();return!!f&&f===U1()}async function Af($){try{return await A$($)}catch{return}}async function g_($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await Af($))?.url)return!0;await new Promise((Z)=>setTimeout(Z,b_))}return!1}async function xJ($,f){if(IJ($))return;if(await mJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await g_($.url,E_),await c0(f).catch(()=>{return})}function v_(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return q_(new URL(`./entry.${$}`,import.meta.url))}function u_($,f){let J=v_(),W=process.execPath?.trim();if(!W)throw Error("unable to resolve runtime executable for hub daemon");let Z=N_(W).toLowerCase().includes("bun"),Q=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=Q?[I_]:[...j?["--conditions=development"]:[],J];return{launcher:W,args:[...X,"--cwd",$,...x_(f)],cwd:$,env:{...S_(process.env),CLINE_NO_INTERACTIVE:"1",[w_]:"1"}}}function c_($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function u9($,f={}){if(FA())return;let J=u_($,f),W=m_();try{z_(J.launcher,J.args,{detached:!0,stdio:W?["ignore",W.fd,W.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(W)O_(W.fd)}}async function D2($,f={}){for(let J=0;;J++)try{u9($,f);return}catch(W){let Z=k_[J];if(!c_(W)||Z===void 0)throw W;await new Promise((Q)=>setTimeout(Q,Z))}}function P5($,f={}){if(FA())return;let J=Y0(),W=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=d0(f),Q=$$(Z.host,Z.port,Z.pathname);K0(J.discoveryPath).then(async(j)=>{if(j?.url){let A=await Af(j.url);if(A?.url&&IJ(A)&&await V$(A.url,{authToken:j.authToken}))return;if(A?.url)await xJ({...A,authToken:j.authToken},J.discoveryPath);else await c0(J.discoveryPath).catch(()=>{return})}let X=await Af(Q);if(X?.url)await xJ(X,J.discoveryPath);let Y=!W&&Z.port!==0?{...Z,port:0}:Z;await D2($,Y)}).catch(()=>{})}async function RA($,f={}){let J=Y0(),W=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=d0(f),j=$$(Q.host,Q.port,Q.pathname),X=(K)=>{if(!W)F1(K.url,K.authToken);return K},H=await K0(J.discoveryPath);if(H?.url){let K=await Af(H.url);if(K?.url&&IJ(K)&&await V$(K.url,{authToken:H.authToken}))return X({url:K.url,authToken:H.authToken});if(K?.url)await xJ({...K,authToken:H.authToken},J.discoveryPath);else await c0(J.discoveryPath).catch(()=>{return})}let Y=await Af(j);if(Y?.url)await xJ(Y,J.discoveryPath);let V=!Z&&Q.port!==0?{...Q,port:0}:Q;await D2($,V);let B=Date.now()+h_;while(Date.now()<B){let K=await K0(J.discoveryPath);if(K?.url){let R=await Af(K.url);if(R?.url&&IJ(R)&&await V$(R.url,{authToken:K.authToken}))return X({url:R.url,authToken:K.authToken})}let G=await Af(j);if(G?.url&&!IJ(G))await xJ(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,C_))}throw Error("Timed out waiting for detached hub startup.")}function p_(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function _A($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return _A($.data);return String($)}function r_($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function DA($){let f=$,J=r_(f.reason);return new T0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:c9,{closeCode:f.code,closeReason:J||void 0})}function i_($,f){if($ instanceof T0)return $;if($ instanceof Error)return new T0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new T0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new T0("hub_connect_failed",J);let W=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new T0("hub_connect_failed",W?`Failed to connect to hub at ${f.toString()} (${W} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var n_=8000,a_=200,LA="*",zA=8000,t_="cline-hub-auth.",TA=new Map,NA=new Set,s_=3000,o_=3000,e_=100,c9="Hub connection closed",$T=250,fT=5000,OA=0.5;class T0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function p9($){return $ instanceof T0}class L2 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function U5($,f){return $ instanceof L2&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function MA($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=r9($.toString());return J?TA.get(J):void 0}function JT($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function r9($){if(!JT($))return;let f=new URL(R1($));return f.search="",f.hash="",f.toString()}function d9($){let f=r9($);return!!f&&NA.has(f)}function F1($,f){let J=r9($);if(J){if(NA.add(J),f?.trim())TA.set(J,f)}return $}class f${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new T0("hub_connection_closed",c9);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||MA($);$.hash="";let W=new(p_())($.toString(),f?[`${t_}${f}`]:void 0);this.socket=W;let Z=!1;this.connectPromise=new Promise((Q,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new T0("hub_connect_timeout",`Timed out connecting to hub after ${zA}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{W.close()}catch{}j(this.lastCloseError)},zA);W.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),Q()}),W.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=i_(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),W.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=DA(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),W.addEventListener("message",(Q)=>{this.handleFrame(JSON.parse(_A(Q)))}),W.addEventListener("close",(Q)=>{if(this.socket!==W)return;if(!Z)this.lastCloseError=DA(Q),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let Q of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(Q));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,W={listener:$,sessionId:J};return this.listeners.add(W),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(W))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,W){let Z=0,Q=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,W)}catch(j){if(!Q||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,W){await this.connect();let Z=d_("hubreq_"),Q=l_($,W?.timeoutMs),j=new Promise((H,Y)=>{let A=Q===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new L2($,"hub_command_timeout",`Hub command ${$} timed out after ${Q}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},Q);this.pendingReplies.set(Z,{resolve:(V)=>{if(A)clearTimeout(A);H(V)},reject:(V)=>{if(A)clearTimeout(A);Y(V)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:Q,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok){if(X.error?.code===jf){let H=J??(typeof f?.sessionId==="string"?f.sessionId:void 0);throw new k$(H,X.error.message)}throw new L2($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!d9(this.currentUrl)||!p9($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await Vf({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min($T*2**this.reconnectAttempt,fT),f=Math.round($*(1-OA)+Math.random()*$*OA);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!d9(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await Vf({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 T0("hub_connection_closed",c9),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new T0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),W=(this.subscriptionCounts.get(J)??0)+f;if(W<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,W),f>0&&W===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??LA}subscriptionSessionIdFromKey($){return $===LA?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function R1($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function V$($,f){let J=new f$({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function l9($,f){let J=R1($),W=await A$(J);if(!W)return{status:"unreachable",url:J};let Z=U1(),Q=W.buildId?.trim();if(!Q||Q!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await V$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function WT($){let f=Date.now()+n_;while(Date.now()<f){let J=await K0($.discoveryPath);if(J?.url){let W=await l9(J.url,{verifyConnection:!0,authToken:J.authToken});if(W.status==="compatible")return F1(W.url,J.authToken)}await new Promise((W)=>setTimeout(W,a_))}return}async function ZT($){let f=Date.now()+o_;while(Date.now()<f){if(!(await A$($).catch(()=>{return}))?.url)return!0;await new Promise((W)=>setTimeout(W,e_))}return!1}function QT($,f){try{return R1($)===R1(f)}catch{return!1}}function jT($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let W=J;if(W.status==="running"||W.status==="idle"||W.status==="pending")return!0;return Array.isArray(W.participants)&&W.participants.length>0})}async function XT($,f,J){let W=new f$({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await W.command("session.list",{limit:500},void 0,{timeoutMs:s_});return!jT(Z.payload)}catch{return!1}finally{await W.dispose().catch(()=>{return})}}async function gJ($={}){if($.endpoint?.trim()){let Z=await l9($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=Y0(),J=await K0(f.discoveryPath);if(!J?.url)return;let W=await l9(J.url);if(W.status==="compatible")return F1(W.url,J.authToken);if(W.status==="build_mismatch")await c0(f.discoveryPath).catch(()=>{return});return}async function Vf($={}){let f=await gJ($);if(f&&await V$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=Y0();return await D2($.workspaceRoot??process.cwd()),await WT(J)}async function mJ($,f){let J=new URL($),W=f?.trim()||MA(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:W?{authorization:`Bearer ${W}`}:void 0})).ok}async function i9(){let $=Y0(),f=await K0($.discoveryPath);if(!f?.url)return!1;try{if(await mJ(f.url,f.authToken))return!0}catch{}return!1}async function F5($){if(!d9($.url))return;let f=Y0(),J=await K0(f.discoveryPath);if(!J?.url||!QT(J.url,$.url))return;if(!await XT(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await i9())return;if(!await ZT(J.url))return;return await c0(f.discoveryPath).catch(()=>{return}),await Vf({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var gA={};w(gA,{HubRuntimeHost:()=>m$});import{captureSdkError as qA,createSessionId as wA,HUB_CHECKPOINT_CAPABILITY as VT,HUB_COMPACTION_CAPABILITY as BT,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as KT,HUB_HOOK_CAPABILITY_PREFIX as GT,HUB_MISTAKE_LIMIT_CAPABILITY as PT,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as UT,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as FT,isHubToolExecutorName as RT}from"@cline/shared";var yA={};w(yA,{createCoreSessionSnapshot:()=>B$,coreSessionSnapshotToRecord:()=>R5});function HT($){return $?JSON.parse(JSON.stringify($)):void 0}function YT($){return $?JSON.parse(JSON.stringify($)):void 0}function AT($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,W=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=W.at(-1),Q=$?.checkpointEnabled===!0?!0:void 0;if(!Q&&W.length===0)return;return{...Q?{enabled:Q}:{},...Z?{latest:Z}:{},history:W}}function B$($){let{session:f}=$,J=HT(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:YT($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let W=AT(J);return W?{checkpoint:W}:{}})()}}function R5($){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 z2($){if(!$)return;return JSON.parse(JSON.stringify($))}var DT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function SA($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function hA($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function CA($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function Bf($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function EA($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(RT)){let Q=f.toolExecutors?.[Z];if(typeof Q!=="function")continue;Bf(J,{kind:"toolExecutor",executor:Z,capabilityName:`${UT}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={...CA(j.context),signal:X};return{result:await Q(...H,Y)}})}for(let Z of $?.extraTools??[])Bf(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:z2(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:z2(Z.lifecycle)}:{},capabilityName:`${KT}${Z.name}`},async({payload:Q,abortSignal:j,progress:X})=>{let H={...CA(Q.context),signal:j};return{result:await Z.execute(Q.input,{...H,emitUpdate:(A)=>{X({update:A})}})}});let W=$?.hooks;if(W)for(let Z of DT){let Q=W[Z];if(typeof Q!=="function")continue;Bf(J,{kind:"hook",name:Z,capabilityName:`${GT}${Z}`},async({payload:j})=>({control:await Q(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;Bf(J,{kind:"compaction",capabilityName:BT,config:SA($.compaction)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;Bf(J,{kind:"checkpoint",capabilityName:VT,config:SA($.checkpoint)},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;Bf(J,{kind:"mistakeLimit",capabilityName:PT},async({payload:Q})=>({result:await Z(Q.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;Bf(J,{kind:"userInstructionService",capabilityName:FT},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function xA($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function LT($){return xA($)??"Capability request was cancelled."}function zT($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function OT($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function _T($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,W=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||W===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function bA($){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 n9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function D1($,f){return n9($?.[f])??0}function TT($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,W=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=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:D1(f,"inputTokens"),outputTokens:D1(f,"outputTokens"),cacheReadTokens:D1(f,"cacheReadTokens"),cacheWriteTokens:D1(f,"cacheWriteTokens"),cost:n9(f?.totalCost),totalInputTokens:D1(J,"inputTokens"),totalOutputTokens:D1(J,"outputTokens"),totalCacheReadTokens:D1(J,"cacheReadTokens"),totalCacheWriteTokens:D1(J,"cacheWriteTokens"),totalCost:n9(J?.totalCost)},teamAgentId:typeof W?.teamAgentId==="string"?W.teamAgentId:void 0,teamRole:Z}}function NT($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,W=OT(J)?J:J==="failed"?"error":"completed",Z=_T($?.usage??f?.usage);return{type:"done",reason:W,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function D5($,f){return $.error?.message??`hub command failed: ${f}`}function vJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function mA($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:G0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:vJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:vJ($.status)==="completed"?0:vJ($.status)==="failed"?1:void 0,status:vJ($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function L1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function MT($){let f=L1($?.snapshot);if(f)return R5(f);let J=$?.session;return J?mA(J):void 0}function kA($,f,J){let W=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return y0.parse({version:1,session_id:$,source:f.source??G0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:vJ(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:W,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function IA($,f){return y0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class m${runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new CJ;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=F0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new f$({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!U5($,"session.create"))return!1;let f=await F5({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=EA($.localRuntime,f),W=$.config.sessionId?.trim()||wA(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:z2({...$.config,sessionId:W}),metadata:{...$.sessionMetadata??{},source:$.source??G0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:z2($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(W,f,J.handlers);let Q;try{Q=await Z()}catch(Y){if(this.cleanupPlannedSession(W),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(W,f,J.handlers);try{Q=await Z()}catch(A){throw this.cleanupPlannedSession(W),A}}else throw Y}let j=L1(Q.payload?.snapshot),X=Q.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(W),Error("Hub runtime did not return a session id.");if(H!==W)this.cleanupPlannedSession(W),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?IA(j,$):kA(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let W=$.start,Z=W?this.resolveCapabilities(W):void 0,Q=W?EA(W.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=W?W.config.sessionId?.trim()||wA():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(j,Q.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...W?{workspaceRoot:W.config.workspaceRoot?.trim()||W.config.cwd,cwd:W.config.cwd??$.cwd,sessionConfig:z2({...W.config,sessionId:j}),metadata:{...W.sessionMetadata??{},source:W.source??G0.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:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...W.localRuntime?.configExtensions?{configExtensions:W.localRuntime.configExtensions}:{}},toolPolicies:z2(W.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let H=L1(X.payload?.snapshot),Y=X.payload?.session,A=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!A){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(A&&j&&A!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(A&&Z)this.sessionCapabilities.set(A,Z);if(A&&Q.handlers.size>0)this.sessionClientContributionHandlers.set(A,Q.handlers);if(A)this.ensureSessionSubscription(A);let V=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:A,startResult:A?{sessionId:A,manifest:H?IA(H,W??{}):kA(A,W??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:V,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=L1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let W=f.payload?.session,Z=bA(W?.usage),Q=bA(W?.aggregateUsage);return Z||Q?{usage:Z,aggregateUsage:Q}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:xA(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(I$(J))return;throw J}return MT(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let Q=L1(Z);return Q?[R5(Q)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(mA)}async listSettings($){let f=await this.client.command("settings.list",hA($));if(!f.ok)throw Error(D5(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",hA($));if(!f.ok)throw Error(D5(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw qA(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(D5(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(D5(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((W)=>{this.handleHubEvent(W)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return F0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:NT($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",W=$.payload?.redacted===!0;if(!J&&!W)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:W}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=TT($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=L1($.payload?.snapshot),W=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:W?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=L1($.payload?.snapshot),W=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:W}}),J?.interactive===!0&&W0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:W,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{qA(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let W=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!W)return;let Q=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!Q){await this.client.command("capability.respond",{requestId:W,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(W,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:W,payload:Y},f).catch((A)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",A,$)})};try{let Y=await Q({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:W,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(W)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(LT($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let W=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",Q=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!W||!Z||!Q)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=zT($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:Q,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:Q,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:W,approved:H.approved,reason:H.reason},f).catch(()=>{})}}var vA={};w(vA,{RemoteRuntimeHost:()=>O2});class O2 extends m${constructor($){super({url:R1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var uA={};w(uA,{SqliteSessionStore:()=>G$});import{existsSync as yT,mkdirSync as qT}from"node:fs";import{join as wT}from"node:path";import{asBool as uJ,asOptionalString as K$,asString as g$,ensureSessionSchema as ST,loadSqliteDb as hT,nowIso as L5,toBoolInt as cJ}from"@cline/shared/db";import{resolveDbDataDir as CT}from"@cline/shared/storage";class G${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??CT()}init(){this.getRawDb()}ensureSessionsDir(){if(!yT(this.sessionsDirPath))qT(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return wT(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=hT(this.sessionDbPath());return ST($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=L5();this.run(`INSERT OR REPLACE INTO sessions (
483
483
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
484
484
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
485
485
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -489,25 +489,25 @@ ${JSON.stringify(W,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
489
489
  enable_tools, enable_spawn, enable_teams,
490
490
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
491
491
  prompt, metadata_json, hook_path, messages_path, updated_at
492
- FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:g$(f.session_id),source:g$(f.source),pid:Number(f.pid??0),startedAt:g$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:g$(f.status),interactive:uJ(f.interactive),provider:g$(f.provider),model:g$(f.model),cwd:g$(f.cwd),workspaceRoot:g$(f.workspace_root),teamName:K$(f.team_name),enableTools:uJ(f.enable_tools),enableSpawn:uJ(f.enable_spawn),enableTeams:uJ(f.enable_teams),parentSessionId:K$(f.parent_session_id),parentAgentId:K$(f.parent_agent_id),agentId:K$(f.agent_id),conversationId:K$(f.conversation_id),isSubagent:uJ(f.is_subagent),prompt:K$(f.prompt),metadata:(()=>{let J=K$(f.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:K$(f.hook_path),messagesPath:K$(f.messages_path),updatedAt:K$(f.updated_at)??L5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let W of f){let Z=this.get(g$(W.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}z5();import{existsSync as jQ,mkdirSync as YN,readFileSync as oA,renameSync as AN,writeFileSync as VN}from"node:fs";import{join as eA}from"node:path";import{resolveSessionDataDir as BN}from"@cline/shared/storage";import{dirname as XN}from"node:path";import{nanoid as HN}from"nanoid";import{appendFileSync as pT,existsSync as rT,mkdirSync as cA,readFileSync as iT,writeFileSync as dA}from"node:fs";import{dirname as lA,join as nT}from"node:path";import{ensureHookLogDir as aT}from"@cline/shared/storage";class aZ{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new gW(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){dj(f,J,o9($))}writeSessionManifest($,f){cA(lA($),{recursive:!0}),dA($,`${JSON.stringify(y0.parse(f),null,2)}
493
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!rT(f))return{path:f};try{return{path:f,manifest:y0.parse(JSON.parse(iT(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let W=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=e9({updatedAt:s(),context:o9($),messages:f,systemPrompt:J}),Q=`${JSON.stringify(Z,null,2)}
492
+ FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:g$(f.session_id),source:g$(f.source),pid:Number(f.pid??0),startedAt:g$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:g$(f.status),interactive:uJ(f.interactive),provider:g$(f.provider),model:g$(f.model),cwd:g$(f.cwd),workspaceRoot:g$(f.workspace_root),teamName:K$(f.team_name),enableTools:uJ(f.enable_tools),enableSpawn:uJ(f.enable_spawn),enableTeams:uJ(f.enable_teams),parentSessionId:K$(f.parent_session_id),parentAgentId:K$(f.parent_agent_id),agentId:K$(f.agent_id),conversationId:K$(f.conversation_id),isSubagent:uJ(f.is_subagent),prompt:K$(f.prompt),metadata:(()=>{let J=K$(f.metadata_json);if(!J)return;try{let W=JSON.parse(J);if(W&&typeof W==="object"&&!Array.isArray(W))return W}catch{}return})(),hookPath:K$(f.hook_path),messagesPath:K$(f.messages_path),updatedAt:K$(f.updated_at)??L5()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let W of f){let Z=this.get(g$(W.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}z5();import{existsSync as jQ,mkdirSync as YN,readFileSync as oA,renameSync as AN,writeFileSync as VN}from"node:fs";import{join as eA}from"node:path";import{resolveSessionDataDir as BN}from"@cline/shared/storage";import{dirname as XN}from"node:path";import{nanoid as HN}from"nanoid";import{appendFileSync as pT,existsSync as rT,mkdirSync as cA,readFileSync as iT,writeFileSync as dA}from"node:fs";import{dirname as lA,join as nT}from"node:path";import{ensureHookLogDir as aT}from"@cline/shared/storage";class a9{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new gZ(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){dj(f,J,oW($))}writeSessionManifest($,f){cA(lA($),{recursive:!0}),dA($,`${JSON.stringify(y0.parse(f),null,2)}
493
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!rT(f))return{path:f};try{return{path:f,manifest:y0.parse(JSON.parse(iT(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let W=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=eW({updatedAt:s(),context:oW($),messages:f,systemPrompt:J}),Q=`${JSON.stringify(Z,null,2)}
494
494
  `;if(cA(lA(W),{recursive:!0}),dA(W,Q,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:W,contents:Q,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,W,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??nT(aT(),"hooks.jsonl");pT(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:W,sessionId:f,pid:J,source:Z})}
495
- `,"utf8")}}import{appendFileSync as tT}from"node:fs";import{join as sT}from"node:path";import{resolveRootSessionId as pA}from"@cline/shared";import{ensureHookLogDir as oT}from"@cline/shared/storage";import{z as tZ}from"zod";var eT="subagent",$N=tZ.looseObject({task:tZ.string().optional(),systemPrompt:tZ.string().optional()});class O5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,W){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:eT,pid:process.ppid,startedAt:f.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:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:N8({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=pA($.sessionContext);if(!f)return;let J=$N.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let W=xf(f,$.agentId),Z=await this.adapter.getSession(W),Q=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:Q,...j})),this.manifestStore.initializeMessagesFile(W,j.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:N8({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=pA($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=xf(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,O8(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let W=W0(f)?null:s(),Z=W0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:W,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,f)}async onTeamTaskStart($,f,J){let W=await this.adapter.getSession($);if(!W)return;let Z=L8($,f),Q=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:Q,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,Q);let X=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(X)??[];H.push(Z),this.teamTaskSessionsByAgent.set(X,H)}async onTeamTaskEnd($,f,J,W,Z,Q){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let H=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!H)return;let Y=Z?.messages??Q,A=this.toPersistedMessages(Y,Z,Q);if(A)await this.manifestStore.persistSessionMessages(H,A);await this.applySubagentStatusBySessionId(H,J),this.teamTaskLastHeartbeatBySession.delete(H),this.teamTaskLastProgressLineBySession.delete(H)}async onTeamTaskProgress($,f,J,W){let Z=this.teamTaskQueueKey($,f),Q=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!Q)return;let j=J.trim();if(!j)return;let X=W?.kind??"progress";if(X==="heartbeat"){let Y=Date.now(),A=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(Y-A<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,Y)}let H=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(Q)===H)return;this.teamTaskLastProgressLineBySession.set(Q,H)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??sT(oT(),"hooks.jsonl");tT(J,`${JSON.stringify({ts:s(),...$})}
496
- `,"utf8")}}import{formatUserInputBlock as jN}from"@cline/shared";var sA={};w(sA,{toTeamProgressLifecycleEvent:()=>T2,sanitizeTeamName:()=>Ej,reviveTeamStateDates:()=>x4,createWorkerReviewerTeam:()=>tA,createSpawnAgentTool:()=>$1,createDelegatedAgentConfigProvider:()=>Ef,createDelegatedAgent:()=>bf,createAgentTeamsTools:()=>k1,createAgentTeam:()=>oZ,buildTeamProgressSummary:()=>_2,buildDelegatedAgentConfig:()=>E1,bootstrapAgentTeams:()=>If,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>M2});function P$(){return new Date().toISOString()}function rA($,f){if(f<=0)return 0;return Math.round($/f*100)}function fN($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let W=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let Q of Z.requiredSections)if(!J.has(`${Z.id}:${Q}`))W.add(`${Z.id}:${Q}`)}return[...W].sort((Z,Q)=>Z.localeCompare(Q))}function _2($,f){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,H=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")X+=1;else H+=1;let Y=[],A=[],V=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(W[P.status]+=1,P.status==="blocked"){Y.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((F)=>{return B.get(F)?.status==="completed"}))A.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let U=P.startedAt.getTime();if(U>=R)R=U,G=P.id}for(let P of f.outcomes)Q[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:P$(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:H},tasks:{total:f.tasks.length,byStatus:W,blockedTaskIds:Y,readyTaskIds:A,completionPct:rA(V,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:Q,finalizedPct:rA(Q.finalized,f.outcomes.length),missingRequiredSections:fN(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function T2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.task.id,agentId:f.task.assignee??f.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:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$()}}import{sanitizeFileName as JN,TeamMessageType as b}from"@cline/shared";import{nanoid as WN}from"nanoid";import{TeamMessageType as _g}from"@cline/shared";function sZ($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function iA($,f){return $?.status==="stopped"&&sZ(f)}var ZN=600000,nA="recovered_queued";function QN($){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.
495
+ `,"utf8")}}import{appendFileSync as tT}from"node:fs";import{join as sT}from"node:path";import{resolveRootSessionId as pA}from"@cline/shared";import{ensureHookLogDir as oT}from"@cline/shared/storage";import{z as t9}from"zod";var eT="subagent",$N=t9.looseObject({task:t9.string().optional(),systemPrompt:t9.string().optional()});class O5{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,W){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=W}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:eT,pid:process.ppid,startedAt:f.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:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:N8({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=pA($.sessionContext);if(!f)return;let J=$N.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let W=xf(f,$.agentId),Z=await this.adapter.getSession(W),Q=s(),j=this.manifestStore.artifacts.subagentArtifactPaths(W,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:W,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:Q,...j})),this.manifestStore.initializeMessagesFile(W,j.messagesPath,Q),W;return await this.adapter.updateSession({sessionId:W,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:N8({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),W}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=pA($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=xf(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,O8(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let W=W0(f)?null:s(),Z=W0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:W,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let W of J)await this.applySubagentStatusBySessionId(W.sessionId,f)}async onTeamTaskStart($,f,J){let W=await this.adapter.getSession($);if(!W)return;let Z=L8($,f),Q=s(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(W,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:Q,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,Q);let X=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(X)??[];H.push(Z),this.teamTaskSessionsByAgent.set(X,H)}async onTeamTaskEnd($,f,J,W,Z,Q){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let H=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!H)return;let Y=Z?.messages??Q,A=this.toPersistedMessages(Y,Z,Q);if(A)await this.manifestStore.persistSessionMessages(H,A);await this.applySubagentStatusBySessionId(H,J),this.teamTaskLastHeartbeatBySession.delete(H),this.teamTaskLastProgressLineBySession.delete(H)}async onTeamTaskProgress($,f,J,W){let Z=this.teamTaskQueueKey($,f),Q=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!Q)return;let j=J.trim();if(!j)return;let X=W?.kind??"progress";if(X==="heartbeat"){let Y=Date.now(),A=this.teamTaskLastHeartbeatBySession.get(Q)??0;if(Y-A<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(Q,Y)}let H=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(Q)===H)return;this.teamTaskLastProgressLineBySession.set(Q,H)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let W=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(W)await this.manifestStore.persistSessionMessages(J,W);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??sT(oT(),"hooks.jsonl");tT(J,`${JSON.stringify({ts:s(),...$})}
496
+ `,"utf8")}}import{formatUserInputBlock as jN}from"@cline/shared";var sA={};w(sA,{toTeamProgressLifecycleEvent:()=>T2,sanitizeTeamName:()=>Ej,reviveTeamStateDates:()=>x4,createWorkerReviewerTeam:()=>tA,createSpawnAgentTool:()=>$1,createDelegatedAgentConfigProvider:()=>Ef,createDelegatedAgent:()=>bf,createAgentTeamsTools:()=>k1,createAgentTeam:()=>o9,buildTeamProgressSummary:()=>_2,buildDelegatedAgentConfig:()=>E1,bootstrapAgentTeams:()=>If,AgentTeamsRuntime:()=>Gf,AgentTeam:()=>M2});function P$(){return new Date().toISOString()}function rA($,f){if(f<=0)return 0;return Math.round($/f*100)}function fN($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let W=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let Q of Z.requiredSections)if(!J.has(`${Z.id}:${Q}`))W.add(`${Z.id}:${Q}`)}return[...W].sort((Z,Q)=>Z.localeCompare(Q))}function _2($,f){let J={idle:0,running:0,stopped:0},W={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},Q={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,H=0;for(let P of f.members)if(J[P.status]+=1,P.role==="lead")X+=1;else H+=1;let Y=[],A=[],V=f.tasks.filter((P)=>P.status==="completed").length,B=new Map(f.tasks.map((P)=>[P.id,P]));for(let P of f.tasks){if(W[P.status]+=1,P.status==="blocked"){Y.push(P.id);continue}if(P.status!=="pending")continue;if(P.dependsOn.every((F)=>{return B.get(F)?.status==="completed"}))A.push(P.id)}let K=[],G,R=0;for(let P of f.runs){if(Z[P.status]+=1,P.status==="queued"||P.status==="running")K.push(P.id);let U=P.startedAt.getTime();if(U>=R)R=U,G=P.id}for(let P of f.outcomes)Q[P.status]+=1;for(let P of f.outcomeFragments)j[P.status]+=1;return{teamName:$,updatedAt:P$(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:H},tasks:{total:f.tasks.length,byStatus:W,blockedTaskIds:Y,readyTaskIds:A,completionPct:rA(V,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:Q,finalizedPct:rA(Q.finalized,f.outcomes.length),missingRequiredSections:fN(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function T2($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.task.id,agentId:f.task.assignee??f.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:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:P$()}}import{sanitizeFileName as JN,TeamMessageType as b}from"@cline/shared";import{nanoid as WN}from"nanoid";import{TeamMessageType as _g}from"@cline/shared";function s9($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function iA($,f){return $?.status==="stopped"&&s9(f)}var ZN=600000,nA="recovered_queued";function QN($){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.
497
497
 
498
498
  ${$.message}`}class M2{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,W]of Object.entries($))this.addAgent(J,W)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:b.AgentEvent,agentId:$,event:Z})}},W=new e$(J);if(J.onEvent)W.subscribeEvents(J.onEvent);this.agents.set($,W),this.configs.set($,f)}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($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.run(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:b.TaskStart,agentId:$,message:f});try{let W=await J.continue(f);return this.emitEvent({type:b.TaskEnd,agentId:$,result:W}),W}catch(W){let Z=W instanceof Error?W:Error(String(W));throw this.emitEvent({type:b.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),W}}async runParallel($){let f=$.map(async(J)=>{let W=this.agents.get(J.agentId);if(!W)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),{agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let W=this.agents.get(J.agentId);if(!W){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:b.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await W.run(J.message);this.emitEvent({type:b.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:b.TaskEnd,agentId:J.agentId,error:Q,messages:W.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:Q,metadata:J.metadata})}}return f}async runPipeline($,f,J){let W=[],Z=f;for(let Q of $){let j=this.agents.get(Q);if(!j){W.push({agentId:Q,result:void 0,error:Error(`Agent "${Q}" not found in team`)});break}this.emitEvent({type:b.TaskStart,agentId:Q,message:Z});try{let X=await j.run(Z);this.emitEvent({type:b.TaskEnd,agentId:Q,result:X}),W.push({agentId:Q,result:X});let H=$.indexOf(Q)+1;if(H<$.length){let Y=$[H];Z=J?J(X,Y):`Previous agent output:
499
499
  ${X.text}
500
500
 
501
- Please continue from here.`}}catch(X){let H=X instanceof Error?X:Error(String(X));this.emitEvent({type:b.TaskEnd,agentId:Q,error:H,messages:j.getMessages()}),W.push({agentId:Q,result:void 0,error:H});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{}}}function oZ($,f){return new M2($,f)}function tA($){let f=oZ({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(W)=>{let Z=await f.routeTo("worker",W),Q=await f.routeTo("reviewer",`Please review this work:
501
+ Please continue from here.`}}catch(X){let H=X instanceof Error?X:Error(String(X));this.emitEvent({type:b.TaskEnd,agentId:Q,error:H,messages:j.getMessages()}),W.push({agentId:Q,result:void 0,error:H});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{}}}function o9($,f){return new M2($,f)}function tA($){let f=o9({worker:$.worker,reviewer:$.reviewer}),J=f;return J.doAndReview=async(W)=>{let Z=await f.routeTo("worker",W),Q=await f.routeTo("reviewer",`Please review this work:
502
502
 
503
- ${Z.text}`);return{workerResult:Z,reviewResult:Q}},J}class Gf{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_${JN(WN(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 f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,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((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,W=f?.markRead??!0,Z=f?.limit,Q=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?Q.slice(Math.max(0,Q.length-Z)):Q;if(W){let X=new Date;for(let H of j)if(!H.readAt)H.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}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 J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,N2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,N2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,N2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,N2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,N2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,N2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...f,apiTimeoutMs:ZN,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:b.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new e$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);let Q={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,Q),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(W){if(!sZ(W))throw W}J.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,W),this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...W}}completeTask($,f,J){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=f;return this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...W}}async routeToTeammate($,f,J){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:b.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),Q=Z.length>0?`${this.buildMailboxNotification(Z)}
503
+ ${Z.text}`);return{workerResult:Z,reviewResult:Q}},J}class Gf{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_${JN(WN(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 f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,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((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,W=f?.markRead??!0,Z=f?.limit,Q=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?Q.slice(Math.max(0,Q.length-Z)):Q;if(W){let X=new Date;for(let H of j)if(!H.readAt)H.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}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 J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,N2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,N2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,N2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,N2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,N2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,N2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let W={...f,apiTimeoutMs:ZN,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:b.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new e$(W);if(W.onEvent)Z.subscribeEvents(W.onEvent);let Q={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,Q),this.emitEvent({type:b.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(W){if(!s9(W))throw W}J.status="stopped",this.emitEvent({type:b.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,W={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,W),this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),{...W}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:b.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let W=this.requireTask($);return W.status="blocked",W.updatedAt=new Date,W.summary=J,this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...W}}completeTask($,f,J){let W=this.requireTask($);if(W.status="completed",W.updatedAt=new Date,W.summary=J,!W.assignee)W.assignee=f;return this.emitEvent({type:b.TeamTaskUpdated,task:{...W}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...W}}async routeToTeammate($,f,J){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:b.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),Q=Z.length>0?`${this.buildMailboxNotification(Z)}
504
504
 
505
- ${f}`:f,j=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:b.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:Q,messages:W.agent.getMessages()}),!iA(W,Q))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,f,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:W,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,Z),this.runQueue.push(W),this.emitEvent({type:b.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(J,1),Z=W?this.runs.get(W):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let Q=this.runs.get(this.runQueue[Z]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>f)f=Q.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===nA;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=f?QN($):$.message,Z=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(W){let Z=W instanceof Error?W.message:String(W??"Unknown error");$.error=Z,$.endedAt=new Date;let Q=this.members.get($.agentId);if(iA(Q,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.RunCancelled,run:{...$},reason:Z});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:b.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await aA(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await aA($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:b.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:b.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=nA,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:b.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:b.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,W,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let Q=this.members.get(f);if(!Q)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:W,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:b.TeamMessage,message:{...j}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,W){let Z=[];for(let Q of this.members.values()){if(Q.agentId===$)continue;if(Q.role==="lead")continue;Z.push(this.sendMessage($,Q.agentId,f,J,W?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={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(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={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(f.id,f),this.emitEvent({type:b.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={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(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:b.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:b.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let W of f.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:b.OutcomeFinalized,outcome:{...f}}),{...f}}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(f){if(!sZ(f))throw f}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[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:b.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${W}`}recordProgressStep($,f,J,W=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let Q=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
506
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function aA($){return new Promise((f)=>setTimeout(f,$))}function N2($,f){let J=0;for(let W of $){if(!W.startsWith(f))continue;let Z=Number.parseInt(W.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function eZ($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),_5($);break}default:break}}async function $Q($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let W=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",$,f.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function fQ($,f,J,W){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:T2({teamName:Z,sessionId:f,event:J}),summary:_2(Z,$.runtime.teamRuntime.exportState())}})}function dJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function JQ($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&dJ($)}function _5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function WQ($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function ZQ($,f){let J=f.map((Q)=>{let j=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)j.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")j.push(` iterations=${Q.iterations}`);if(Q.error)j.push(` error=${Q.error}`);return j.join("")}),W=$.activeTeamRunIds.size,Z=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 lJ(`System-delivered teammate async run updates:
505
+ ${f}`:f,j=J?.continueConversation?await W.agent.continue(Q):await W.agent.run(Q);return this.emitEvent({type:b.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let Q=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:b.TaskEnd,agentId:$,error:Q,messages:W.agent.getMessages()}),!iA(W,Q))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:Q.message});throw Q}finally{if(W.runningCount--,W.runningCount<=0&&this.members.get($)?.status!=="stopped")W.status="idle"}}startTeammateRun($,f,J){let W=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:W,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(W,Z),this.runQueue.push(W),this.emitEvent({type:b.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[W]=this.runQueue.splice(J,1),Z=W?this.runs.get(W):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,W=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let Q=this.runs.get(this.runQueue[Z]);if(!Q||Q.status!=="queued")continue;if(Q.nextAttemptAt&&Q.nextAttemptAt.getTime()>W){if(!J||Q.nextAttemptAt<J)J=Q.nextAttemptAt;continue}if(Q.priority>f)f=Q.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===nA;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:b.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let W=f?QN($):$.message,Z=await this.routeToTeammate($.agentId,W,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:b.RunCompleted,run:{...$}})}catch(W){let Z=W instanceof Error?W.message:String(W??"Unknown error");$.error=Z,$.endedAt=new Date;let Q=this.members.get($.agentId);if(iA(Q,W))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:b.RunCancelled,run:{...$},reason:Z});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:b.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await aA(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await aA($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let W=this.runQueue.indexOf($);if(W>=0)this.runQueue.splice(W,1);return this.emitEvent({type:b.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let W=this.members.get(J.agentId);if(!W||W.role!=="teammate"||!W.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:b.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=nA,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:b.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:b.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,W,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let Q=this.members.get(f);if(!Q)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:W,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:b.TeamMessage,message:{...j}}),Q.role==="teammate"&&Q.runningCount>0&&Q.agent)Q.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,W){let Z=[];for(let Q of this.members.values()){if(Q.agentId===$)continue;if(Q.role==="lead")continue;Z.push(this.sendMessage($,Q.agentId,f,J,W?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={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(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:b.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={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(f.id,f),this.emitEvent({type:b.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={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(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:b.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:b.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let W of f.requiredSections)if(!J.some((Q)=>Q.section===W&&Q.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${W}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:b.OutcomeFinalized,outcome:{...f}}),{...f}}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(f){if(!s9(f))throw f}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[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let W of this.runs.values()){if(W.agentId!==$||W.status!=="running")continue;this.recordRunProgress(W,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:b.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let W=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${W}`}recordProgressStep($,f,J,W=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let Q=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!W&&Q<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
506
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function aA($){return new Promise((f)=>setTimeout(f,$))}function N2($,f){let J=0;for(let W of $){if(!W.startsWith(f))continue;let Z=Number.parseInt(W.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function e9($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),_5($);break}default:break}}async function $Q($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let W=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(W)await J("onTeamTaskProgress",$,f.agentId,W,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function fQ($,f,J,W){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();W({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:T2({teamName:Z,sessionId:f,event:J}),summary:_2(Z,$.runtime.teamRuntime.exportState())}})}function dJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function JQ($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&dJ($)}function _5($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function WQ($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function ZQ($,f){let J=f.map((Q)=>{let j=[`- ${Q.runId} (${Q.agentId}) -> ${Q.status}`];if(Q.taskId)j.push(` task=${Q.taskId}`);if(typeof Q.iterations==="number")j.push(` iterations=${Q.iterations}`);if(Q.error)j.push(` error=${Q.error}`);return j.join("")}),W=$.activeTeamRunIds.size,Z=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 lJ(`System-delivered teammate async run updates:
507
507
  ${J.join(`
508
508
  `)}
509
509
 
510
- ${Z}`,$.config.mode)}function lJ($,f){return jN($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var QQ=4;class v${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new aZ($,f.messagesArtifactUploader,f.logger),this.teamChildren=new O5($,this.manifestStore,(J,W,Z)=>this.toPersistedMessages(J,W,Z),v$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?c4(f.messages,f,J):u4($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??s(),J=$.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${HN(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),j=N8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:W,source:$.source,pid:$.pid,started_at:f,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:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:W,source:$.source,pid:$.pid,startedAt:f,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:X.prompt??null,metadata:f1(X.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,Z,f),this.manifestStore.writeSessionManifest(Q,X),{manifestPath:Q,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let W;if((await pj(()=>this.adapter.getSession($),async(Q)=>{return W=W0(f)?void 0:s(),this.adapter.updateSession({sessionId:$,status:f,endedAt:W??null,exitCode:W0(f)?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},QQ)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let f=0;f<QQ;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,Z=$.metadata!==void 0?f1($.metadata)??{}:f1(W)??{},Q=g1(typeof W?.title==="string"?W.title:void 0),j=$.title!==void 0?g1($.title):Q??s9($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:Y,manifest:A}=this.manifestStore.readManifestFile($.sessionId);if(A){if($.prompt!==void 0)A.prompt=$.prompt??void 0;let V=$.metadata!==void 0?f1($.metadata)??{}:f1(A.metadata)??{};if(j)V.title=j;A.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(Y,A)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let W=u4(f);return this.manifestStore.persistSessionMessages($,W,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,W,Z,Q){return this.teamChildren.onTeamTaskEnd($,f,J,W,Z,Q)}onTeamTaskProgress($,f,J,W){return this.teamChildren.onTeamTaskProgress($,f,J,W)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(W0($.status)===!1||this.isPidAlive($.pid))return $;let f=s(),J=v$.STALE_REASON;for(let W=0;W<QQ;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(W0(Z.status)===!1)return Z;let Q={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:v$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:Q,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=lj(Z,{status:"failed",endedAt:f,exitCode:1,metadata:Q}),{path:H}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(H,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,v$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:Q,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let Q=f1(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=g1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),H=X?{...Q??{},title:X}:Q;return{...Z,metadata:H}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),W=0;for(let Z of J){let Q=await this.reconcileDeadRunningSession(Z);if(Q&&Q.status!==Z.status)W++}return W}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(W.map(async(Z)=>{await DW(Z.cwd,Z.sessionId),t8(Z.messagesPath),t8(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await DW(J.cwd,f),t8(J.messagesPath),t8(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)W.add(XN(Z));for(let Z of W)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function XQ(){return new Date().toISOString()}function $V($,f){let J=`${$}.tmp`;VN(J,`${JSON.stringify(f,null,2)}
510
+ ${Z}`,$.config.mode)}function lJ($,f){return jN($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var QQ=4;class v${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new a9($,f.messagesArtifactUploader,f.logger),this.teamChildren=new O5($,this.manifestStore,(J,W,Z)=>this.toPersistedMessages(J,W,Z),v$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?c4(f.messages,f,J):u4($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??s(),J=$.sessionId.trim(),W=J.length>0?J:`${Date.now()}_${HN(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(W),Q=this.manifestStore.artifacts.sessionManifestPath(W),j=N8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:W,source:$.source,pid:$.pid,started_at:f,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:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:W,source:$.source,pid:$.pid,startedAt:f,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:X.prompt??null,metadata:f1(X.metadata),hookPath:"",messagesPath:Z,updatedAt:s()}),this.manifestStore.initializeMessagesFile(W,Z,f),this.manifestStore.writeSessionManifest(Q,X),{manifestPath:Q,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let W;if((await pj(()=>this.adapter.getSession($),async(Q)=>{return W=W0(f)?void 0:s(),this.adapter.updateSession({sessionId:$,status:f,endedAt:W??null,exitCode:W0(f)?null:typeof J==="number"?J:null,expectedStatusLock:Q.statusLock})},QQ)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:W}}return{updated:!1}}async updateSession($){for(let f=0;f<QQ;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let W=J.metadata??void 0,Z=$.metadata!==void 0?f1($.metadata)??{}:f1(W)??{},Q=g1(typeof W?.title==="string"?W.title:void 0),j=$.title!==void 0?g1($.title):Q??sW($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:Y,manifest:A}=this.manifestStore.readManifestFile($.sessionId);if(A){if($.prompt!==void 0)A.prompt=$.prompt??void 0;let V=$.metadata!==void 0?f1($.metadata)??{}:f1(A.metadata)??{};if(j)V.title=j;A.metadata=Object.keys(V).length>0?V:void 0,this.manifestStore.writeSessionManifest(Y,A)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let W=u4(f);return this.manifestStore.persistSessionMessages($,W,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,W,Z,Q){return this.teamChildren.onTeamTaskEnd($,f,J,W,Z,Q)}onTeamTaskProgress($,f,J,W){return this.teamChildren.onTeamTaskProgress($,f,J,W)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(W0($.status)===!1||this.isPidAlive($.pid))return $;let f=s(),J=v$.STALE_REASON;for(let W=0;W<QQ;W++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(W0(Z.status)===!1)return Z;let Q={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:v$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:Q,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=lj(Z,{status:"failed",endedAt:f,exitCode:1,metadata:Q}),{path:H}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(H,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,v$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:Q,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let Q=f1(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=g1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),H=X?{...Q??{},title:X}:Q;return{...Z,metadata:H}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),W=0;for(let Z of J){let Q=await this.reconcileDeadRunningSession(Z);if(Q&&Q.status!==Z.status)W++}return W}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let W=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(W.map(async(Z)=>{await DZ(Z.cwd,Z.sessionId),t8(Z.messagesPath),t8(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await DZ(J.cwd,f),t8(J.messagesPath),t8(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let W=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)W.add(XN(Z));for(let Z of W)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function XQ(){return new Date().toISOString()}function $V($,f){let J=`${$}.tmp`;VN(J,`${JSON.stringify(f,null,2)}
511
511
  `,"utf8"),AN(J,$)}class fV{sessionsDirPath;constructor($=BN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!jQ(this.sessionsDirPath))YN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return eA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return eA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!jQ($))return{version:1,sessions:{}};try{let f=JSON.parse(oA($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){$V(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!jQ($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(oA($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){$V(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let W=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:W,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:XQ()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:XQ()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),W=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!W)return;return W.consumedAt=XQ(),this.writeQueue(J),W.task}}class HQ extends v${constructor($,f={}){super(new fV($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}var ZV={};w(ZV,{CoreSessionService:()=>U$});import{existsSync as KN,mkdirSync as GN}from"node:fs";import{resolveSessionDataDir as PN}from"@cline/shared/storage";var YQ=`
512
512
  session_id AS sessionId,
513
513
  source,
@@ -556,8 +556,8 @@ ${Z}`,$.config.mode)}function lJ($,f){return jN($,f==="plan"?"plan":f==="yolo"?"
556
556
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
557
557
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
558
558
  metadata_json, transcript_path, hook_path, messages_path, updated_at
559
- ) 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,s()])}}function UN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var pJ,rJ;function FN($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;P5(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function RN($){await $.reconcileDeadSessions?.().catch(()=>{})}function XV($){try{let f=new G$;return f.init(),new U$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),jV($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new HQ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function QV($,f,J){return new F$({sessionService:J??$.sessionService??XV($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function BQ($){if(pJ)return pJ;if(rJ)return await rJ;return rJ=(async()=>{return pJ=XV($),await RN(pJ),pJ})().finally(()=>{rJ=void 0}),await rJ}async function y2($){let f=Kf($.distinctId);$.telemetry?.setDistinctId(f);let J=UN($);if(FN(J,$),J==="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 O2({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let W=$.hub?.endpoint?.trim(),Z=W||await Vf({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:W||void 0}),new m$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let W=await gJ({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 Z=new m$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(Q){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q}),jV($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:Q,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),QV($,f)}return QV($,f)}class iJ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,W,Z,Q,j,X,H){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=W,this.capabilities=Z,this.logger=Q,this.telemetry=j,this.distinctId=X,this.settings=yY($),this.pendingPrompts=qY($),this.automation=new sW(()=>{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 hJ({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:xH(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:mH({host:$,getExtensionContext:()=>c6({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((Y)=>{if(Y.type!=="ended")return;this.disposeSessionBootstrap(Y.payload.sessionId)})}static async create($={}){let f=F0($.capabilities),J=await y2({...$,capabilities:f}),W=IH($.automation),Z=new iJ(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=SY($),J=await this.prepare?.(f);try{let W=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(YZ(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>c6({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return hY({input:W,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(W){throw await Promise.resolve(J?.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 f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await V5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?YZ($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>c6({automationService:this.automationService,automation:this.automation,context:J,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:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var AV={};w(AV,{resolvePluginSkillDirectoriesFromPaths:()=>r1,resolvePluginConfigSearchPaths:()=>E8,resolveAndLoadAgentPlugins:()=>tf,resolveAgentPluginPaths:()=>p1,loadAgentPluginsFromPathsWithDiagnostics:()=>l1,loadAgentPluginsFromPaths:()=>o4,loadAgentPluginFromPath:()=>h8,discoverPluginModulePaths:()=>b8});var KV={};w(KV,{toHookConfigFileName:()=>x8,runSubprocessEvent:()=>q2,runHook:()=>S2,resolveHooksConfigSearchPaths:()=>k8,parseHookEventPayload:()=>w2,mergeAgentHooks:()=>t1,listHookConfigFiles:()=>Z1,createSubprocessHooks:()=>M5,createHookConfigFileHooks:()=>m8,createHookConfigFileExtension:()=>$2,createHookAuditHooks:()=>ef,createAgentHooksExtension:()=>sf,HookEventPayloadSchema:()=>N5,HookEventNameSchema:()=>T5,HookConfigFileName:()=>of,HOOK_CONFIG_FILE_EVENT_MAP:()=>I8,HOOKS_CONFIG_DIRECTORY_NAME:()=>Q6});import{HookEventNameSchema as T5,HookEventPayloadSchema as N5,parseHookEventPayload as w2,resolveHookSessionContext as NN}from"@cline/shared";import{z as Pf}from"zod";import{spawn as DN}from"node:child_process";import{augmentNodeCommandForDebug as LN,withResolvedClineBuildEnv as zN}from"@cline/shared";function ON($){let f=$.trim();if(!f)return{};let W=f.split(`
560
- `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function _N($,f){let J=$ instanceof Error?$:Error(String($)),W=J,Z=f.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (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 "${Z}": ${J.message}`)}async function TN($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,Z)=>{let Q=(j)=>{J.off("error",Q);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){W();return}Z(j)};J.once("error",Q),J.end(f,(j)=>{if(J.off("error",Q),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){W();return}Z(j);return}W()})})}async function q2($,f){let J=LN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!f.detached,Z=DN(J[0],J.slice(1),{cwd:f.cwd,env:zN(f.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:W})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(_N(G,J))})});if(await TN(Z,JSON.stringify($)),W){await Promise.race([Q,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",H="",Y=!1,A;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{H+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=ON(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,j])}var MN=Pf.object({contextModification:Pf.string().optional(),cancel:Pf.boolean().optional(),review:Pf.boolean().optional(),errorMessage:Pf.string().optional(),context:Pf.string().optional(),overrideInput:Pf.unknown().optional()}).passthrough();var yN=["agent","hook"];async function S2($,f={}){let J=f.command??yN;return await q2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function BV($){return $ instanceof Error?$:Error(String($))}function qN($){if(!$||typeof $!=="object")return;let f=MN.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function VV($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))if(typeof W==="string")f[J]=W;else f[J]=JSON.stringify(W);return f}function u$($,f,J){let W=J.env??process.env,Z=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:NN(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function wN($){return{name:$.name,message:$.message,stack:$.stack}}function SN($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function hN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function CN($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function EN($){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 bN($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function Uf($,f){try{let J=await S2($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(BV(J),$)}}function M5($={}){return{hooks:{beforeRun:async(X)=>{let H=hN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let A={...u$("agent_resume",H,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Uf(A,$)}else{let A={...u$("agent_start",H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Uf(A,$)}return},beforeTool:async(X)=>{let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...u$("tool_call",H,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:VV(X.input)}};try{let A=await S2(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,result:A,detached:!1}),A?.timedOut)throw Error("tool_call hook command timed out");if(A?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${A.parseError}`);return bN(qN(A?.parsedJson))}catch(A){$.onDispatchError?.(BV(A),Y);return}},afterTool:async(X)=>{let H=EN(X),Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},A={...u$("tool_result",Y,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:H,postToolUse:{toolName:H.name,parameters:VV(H.input),result:typeof H.output==="string"?H.output:JSON.stringify(H.output),success:!H.error,executionTimeMs:H.durationMs}};await Uf(A,$);return},afterRun:async({snapshot:X,result:H})=>{let Y={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(H.status==="completed"){let B={...u$("agent_end",Y,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}};await Uf(B,$);return}let A=H.status==="aborted"||SN(H.error?.message)?"agent_abort":"agent_error",V=A==="agent_error"?{...u$(A,Y,$),hookName:A,iteration:H.iterations,error:wN(H.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...u$(A,Y,$),hookName:A,reason:H.error?.message,taskCancel:{taskMetadata:{}}};await Uf(V,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...u$("prompt_submit",H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:CN(X.message.content),attachments:[]}};await Uf(Y,$)}},shutdown:async({agentId:X,conversationId:H,parentAgentId:Y,reason:A})=>{let V={...u$("session_shutdown",{agentId:X,conversationId:H,parentAgentId:Y},$),hookName:"session_shutdown",reason:A};await Uf(V,$)}}}var PB={};w(PB,{writeHubDiscovery:()=>K5,withHubStartupLock:()=>G5,verifyHubConnection:()=>V$,truncateNotificationBody:()=>sJ,toHubHealthUrl:()=>kZ,stopLocalHubServerGracefully:()=>iZ,startHubWebSocketServer:()=>Df,startHubServer:()=>KB,spawnDetachedHubServerWithRetry:()=>D2,spawnDetachedHubServer:()=>uZ,sendHubCommand:()=>RV,restartLocalHubIfIdleAfterStartupTimeout:()=>F5,resolveWorkspaceHubOwnerContext:()=>UA,resolveSharedHubOwnerContext:()=>Y0,resolveHubUrl:()=>FQ,resolveHubOwnerContext:()=>x$,resolveHubEndpointOptions:()=>d0,resolveHubBuildId:()=>U1,resolveDefaultHubPort:()=>R2,resolveDefaultHubPathname:()=>vZ,resolveDefaultHubHost:()=>gZ,resolveCompatibleLocalHubUrl:()=>gJ,resolveClineDir:()=>BA,resolveClineDataDir:()=>kJ,requestHubShutdown:()=>mJ,rememberRecoverableLocalHubUrl:()=>F1,readHubDiscovery:()=>K0,probeHubServer:()=>A$,probeHubConnection:()=>FV,prewarmDetachedHubServer:()=>P5,normalizeHubWebSocketUrl:()=>R1,isHubReconnectableTransportError:()=>pZ,isHubCommandTimeoutError:()=>U5,isDiscoveryFilePresent:()=>GA,ensureHubWebSocketServer:()=>I5,ensureHubServer:()=>GB,ensureDetachedHubServer:()=>RA,ensureCompatibleLocalHubUrl:()=>Vf,createLocalHubScheduleRuntimeHandlers:()=>x5,createInMemoryHubOwnerContext:()=>KA,createHubServerUrl:()=>$$,createHubAuthToken:()=>B5,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,connectToHub:()=>S5,clearHubDiscovery:()=>c0,NodeHubClient:()=>f$,NativeHubTransportAdapter:()=>J4,HubUIClient:()=>LQ,HubTransportError:()=>T0,HubSessionClient:()=>DQ,HubServerTransport:()=>x2,HubScheduleService:()=>C2,HubScheduleCommandService:()=>h2,HubCommandError:()=>L2,DEFAULT_HUB_PORT:()=>xZ,DEFAULT_HUB_PATHNAME:()=>mZ,DEFAULT_HUB_HOST:()=>IZ,BrowserWebSocketHubAdapter:()=>f4});import{createSessionId as kN}from"@cline/shared";function l0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function GV($,f,J){return{version:$.version,requestId:$.requestId??kN("hubreq_"),ok:!1,error:{code:f,message:J}}}class h2{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return l0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return l0($,{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 l0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return l0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return l0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return l0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return l0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return l0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return l0($,{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 l0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return l0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return l0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return GV($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return GV($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}function q5($){return $?new Date($).getTime():void 0}function IN($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function y5($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__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:q5($.nextRunAt),lastRunAt:q5($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:IN($)}}function xN($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function KQ($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:q5($.startedAt),endedAt:q5($.completedAt),status:xN($.status),errorMessage:$.error}}class C2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new SJ({dbPath:$.dbPath}),this.materializer=new NJ({store:this.store}),this.runner=new MJ({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(RZ($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return y5(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?y5(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>y5(f))}updateSchedule($,f){if(f.cronPattern!==void 0)RZ(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let W=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule($,{...f,scheduleId:$});return Q?y5(Q):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return KQ(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),KQ(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let Q=f??this.store.getSpec(Z.specId);if(!Q||Q.source!=="hub-schedule")return;return KQ(Z,Q.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,Z=0,Q;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!Q&&j.status!=="success"&&j.status!=="completed")Q=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,W+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:W>0?Z/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}w5();function jM($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var XM="cline-hub-auth.";function HM($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function YM($,f){let J=new URL($),W=new URL(f);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function AM($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=Y0(),W=await K0(J.discoveryPath);if(W?.url&&YM($.toString(),W.url))return W.authToken;return}async function FQ($={}){let f=d0($);if(!HM($)){let J=Y0(),W=await K0(J.discoveryPath);if(W?.url)return W.url}return $$(f.host,f.port,f.pathname)}async function S5($){return await new Promise((f,J)=>{(async()=>{let W=new URL($),Z=await AM(W);W.hash="";let Q=new WebSocket(W.toString(),Z?[`${XM}${Z}`]:void 0),j=new Map,X=0;Q.addEventListener("open",()=>{f({send(H){let Y=H.requestId??`hub-client-${++X}`;return new Promise((A,V)=>{j.set(Y,{resolve:A,reject:V});let B={kind:"command",envelope:{...H,requestId:Y}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(H)=>{let Y=JSON.parse(String(H.data));if(Y.kind==="reply"&&Y.envelope.requestId){let A=j.get(Y.envelope.requestId);if(A)j.delete(Y.envelope.requestId),A.resolve(Y.envelope)}}),Q.addEventListener("close",()=>{for(let H of j.values())H.reject(Error("Hub connection closed"));j.clear()}),Q.addEventListener("error",(H)=>{J(jM(H,$))})})().catch(J)})}async function FV($){try{return(await S5($)).close(),!0}catch{return!1}}async function RV($,f){let J=await FQ($),W=await S5(J);try{return await W.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{W.close()}}function RQ($){return $?JSON.parse(JSON.stringify($)):{}}function h5($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?RQ(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function DV($,f){return $.error?.message??`hub command failed: ${f}`}function VM($){let f=RQ($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...f,error:W.message.trim()};return f}function LV($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function BM($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function KM($){let f=RQ($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||LV(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||LV(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:VM($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class DQ{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new f$({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 f=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}),J=h5(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).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 f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(I$(J))return;throw J}return h5(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(DV(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,Z=await this.client.command("session.restore",{sessionId:f,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}:{}},f);if(!Z.ok)throw Error(DV(Z,"session.restore"));let Q=h5(Z.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=BM(Z.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((W)=>h5({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).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($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),W=this.client.subscribe((Z)=>{let Q=KM(Z);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;f.onEvent?.(Q)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),W}streamTeamProgress($,f){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;f.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{f.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).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($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.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 f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class LQ{client;constructor($){this.client=new f$({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 f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}function GM($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
559
+ ) 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,s()])}}function UN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var pJ,rJ;function FN($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;P5(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function RN($){await $.reconcileDeadSessions?.().catch(()=>{})}function XV($){try{let f=new G$;return f.init(),new U$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),jV($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new HQ(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function QV($,f,J){return new F$({sessionService:J??$.sessionService??XV($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function BQ($){if(pJ)return pJ;if(rJ)return await rJ;return rJ=(async()=>{return pJ=XV($),await RN(pJ),pJ})().finally(()=>{rJ=void 0}),await rJ}async function y2($){let f=Kf($.distinctId);$.telemetry?.setDistinctId(f);let J=UN($);if(FN(J,$),J==="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 O2({endpoint:W,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let W=$.hub?.endpoint?.trim(),Z=W||await Vf({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:W||void 0}),new m$({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let W=await gJ({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 Z=new m$({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(Q){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:Q}),jV($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:Q,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),QV($,f)}return QV($,f)}class iJ{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,W,Z,Q,j,X,H){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=W,this.capabilities=Z,this.logger=Q,this.telemetry=j,this.distinctId=X,this.settings=yY($),this.pendingPrompts=qY($),this.automation=new sZ(()=>{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 hJ({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:xH(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:mH({host:$,getExtensionContext:()=>c6({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((Y)=>{if(Y.type!=="ended")return;this.disposeSessionBootstrap(Y.payload.sessionId)})}static async create($={}){let f=F0($.capabilities),J=await y2({...$,capabilities:f}),W=IH($.automation),Z=new iJ(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,W?{...W,logger:$.logger}:void 0);if(W&&W.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=SY($),J=await this.prepare?.(f);try{let W=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(Y9(W,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>c6({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return hY({input:W,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(W){throw await Promise.resolve(J?.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 f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await V5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?Y9($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>c6({automationService:this.automationService,automation:this.automation,context:J,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:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var AV={};w(AV,{resolvePluginSkillDirectoriesFromPaths:()=>r1,resolvePluginConfigSearchPaths:()=>E8,resolveAndLoadAgentPlugins:()=>tf,resolveAgentPluginPaths:()=>p1,loadAgentPluginsFromPathsWithDiagnostics:()=>l1,loadAgentPluginsFromPaths:()=>o4,loadAgentPluginFromPath:()=>h8,discoverPluginModulePaths:()=>b8});var KV={};w(KV,{toHookConfigFileName:()=>x8,runSubprocessEvent:()=>q2,runHook:()=>S2,resolveHooksConfigSearchPaths:()=>k8,parseHookEventPayload:()=>w2,mergeAgentHooks:()=>t1,listHookConfigFiles:()=>Z1,createSubprocessHooks:()=>M5,createHookConfigFileHooks:()=>m8,createHookConfigFileExtension:()=>$2,createHookAuditHooks:()=>ef,createAgentHooksExtension:()=>sf,HookEventPayloadSchema:()=>N5,HookEventNameSchema:()=>T5,HookConfigFileName:()=>of,HOOK_CONFIG_FILE_EVENT_MAP:()=>I8,HOOKS_CONFIG_DIRECTORY_NAME:()=>Q6});import{HookEventNameSchema as T5,HookEventPayloadSchema as N5,parseHookEventPayload as w2,resolveHookSessionContext as NN}from"@cline/shared";import{z as Pf}from"zod";import{spawn as DN}from"node:child_process";import{augmentNodeCommandForDebug as LN,withResolvedClineBuildEnv as zN}from"@cline/shared";function ON($){let f=$.trim();if(!f)return{};let W=f.split(`
560
+ `).map((Q)=>Q.trim()).filter(Boolean).filter((Q)=>Q.startsWith("HOOK_CONTROL\t")).map((Q)=>Q.slice(13)),Z=W.length>0?W[W.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(Q){return{parseError:Q instanceof Error?Q.message:"Failed to parse subprocess stdout JSON"}}}function _N($,f){let J=$ instanceof Error?$:Error(String($)),W=J,Z=f.join(" ");if(W.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (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 "${Z}": ${J.message}`)}async function TN($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((W,Z)=>{let Q=(j)=>{J.off("error",Q);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){W();return}Z(j)};J.once("error",Q),J.end(f,(j)=>{if(J.off("error",Q),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){W();return}Z(j);return}W()})})}async function q2($,f){let J=LN(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let W=!!f.detached,Z=DN(J[0],J.slice(1),{cwd:f.cwd,env:zN(f.env),stdio:W?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:W}),Q=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:W})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(_N(G,J))})});if(await TN(Z,JSON.stringify($)),W){await Promise.race([Q,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",H="",Y=!1,A;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{H+=B.toString()});let V=new Promise((B)=>{if((f.timeoutMs??0)>0)A=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(A)clearTimeout(A);let{parsedJson:G,parseError:R}=ON(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([V,j])}var MN=Pf.object({contextModification:Pf.string().optional(),cancel:Pf.boolean().optional(),review:Pf.boolean().optional(),errorMessage:Pf.string().optional(),context:Pf.string().optional(),overrideInput:Pf.unknown().optional()}).passthrough();var yN=["agent","hook"];async function S2($,f={}){let J=f.command??yN;return await q2($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function BV($){return $ instanceof Error?$:Error(String($))}function qN($){if(!$||typeof $!=="object")return;let f=MN.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function VV($){if(!$||typeof $!=="object")return{};let f={};for(let[J,W]of Object.entries($))if(typeof W==="string")f[J]=W;else f[J]=JSON.stringify(W);return f}function u$($,f,J){let W=J.env??process.env,Z=W.CLINE_USER_ID?.trim()||W.USER?.trim()||"unknown",Q=J.cwd||process.cwd();return{clineVersion:W.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:NN(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:Q?[Q]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function wN($){return{name:$.name,message:$.message,stack:$.stack}}function SN($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function hN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function CN($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function EN($){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 bN($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function Uf($,f){try{let J=await S2($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(BV(J),$)}}function M5($={}){return{hooks:{beforeRun:async(X)=>{let H=hN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let A={...u$("agent_resume",H,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await Uf(A,$)}else{let A={...u$("agent_start",H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await Uf(A,$)}return},beforeTool:async(X)=>{let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...u$("tool_call",H,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:VV(X.input)}};try{let A=await S2(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,result:A,detached:!1}),A?.timedOut)throw Error("tool_call hook command timed out");if(A?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${A.parseError}`);return bN(qN(A?.parsedJson))}catch(A){$.onDispatchError?.(BV(A),Y);return}},afterTool:async(X)=>{let H=EN(X),Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},A={...u$("tool_result",Y,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:H,postToolUse:{toolName:H.name,parameters:VV(H.input),result:typeof H.output==="string"?H.output:JSON.stringify(H.output),success:!H.error,executionTimeMs:H.durationMs}};await Uf(A,$);return},afterRun:async({snapshot:X,result:H})=>{let Y={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(H.status==="completed"){let B={...u$("agent_end",Y,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}};await Uf(B,$);return}let A=H.status==="aborted"||SN(H.error?.message)?"agent_abort":"agent_error",V=A==="agent_error"?{...u$(A,Y,$),hookName:A,iteration:H.iterations,error:wN(H.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...u$(A,Y,$),hookName:A,reason:H.error?.message,taskCancel:{taskMetadata:{}}};await Uf(V,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...u$("prompt_submit",H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:CN(X.message.content),attachments:[]}};await Uf(Y,$)}},shutdown:async({agentId:X,conversationId:H,parentAgentId:Y,reason:A})=>{let V={...u$("session_shutdown",{agentId:X,conversationId:H,parentAgentId:Y},$),hookName:"session_shutdown",reason:A};await Uf(V,$)}}}var PB={};w(PB,{writeHubDiscovery:()=>K5,withHubStartupLock:()=>G5,verifyHubConnection:()=>V$,truncateNotificationBody:()=>sJ,toHubHealthUrl:()=>k9,stopLocalHubServerGracefully:()=>i9,startHubWebSocketServer:()=>Df,startHubServer:()=>KB,spawnDetachedHubServerWithRetry:()=>D2,spawnDetachedHubServer:()=>u9,sendHubCommand:()=>RV,restartLocalHubIfIdleAfterStartupTimeout:()=>F5,resolveWorkspaceHubOwnerContext:()=>UA,resolveSharedHubOwnerContext:()=>Y0,resolveHubUrl:()=>FQ,resolveHubOwnerContext:()=>x$,resolveHubEndpointOptions:()=>d0,resolveHubBuildId:()=>U1,resolveDefaultHubPort:()=>R2,resolveDefaultHubPathname:()=>v9,resolveDefaultHubHost:()=>g9,resolveCompatibleLocalHubUrl:()=>gJ,resolveClineDir:()=>BA,resolveClineDataDir:()=>kJ,requestHubShutdown:()=>mJ,rememberRecoverableLocalHubUrl:()=>F1,readHubDiscovery:()=>K0,probeHubServer:()=>A$,probeHubConnection:()=>FV,prewarmDetachedHubServer:()=>P5,normalizeHubWebSocketUrl:()=>R1,isHubReconnectableTransportError:()=>p9,isHubCommandTimeoutError:()=>U5,isDiscoveryFilePresent:()=>GA,ensureHubWebSocketServer:()=>I5,ensureHubServer:()=>GB,ensureDetachedHubServer:()=>RA,ensureCompatibleLocalHubUrl:()=>Vf,createLocalHubScheduleRuntimeHandlers:()=>x5,createInMemoryHubOwnerContext:()=>KA,createHubServerUrl:()=>$$,createHubAuthToken:()=>B5,createConfiguredTelemetryService:()=>c$,createConfiguredTelemetryHandle:()=>k2,connectToHub:()=>S5,clearHubDiscovery:()=>c0,NodeHubClient:()=>f$,NativeHubTransportAdapter:()=>J4,HubUIClient:()=>LQ,HubTransportError:()=>T0,HubSessionClient:()=>DQ,HubServerTransport:()=>x2,HubScheduleService:()=>C2,HubScheduleCommandService:()=>h2,HubCommandError:()=>L2,DEFAULT_HUB_PORT:()=>x9,DEFAULT_HUB_PATHNAME:()=>m9,DEFAULT_HUB_HOST:()=>I9,BrowserWebSocketHubAdapter:()=>f4});import{createSessionId as kN}from"@cline/shared";function l0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function GV($,f,J){return{version:$.version,requestId:$.requestId??kN("hubreq_"),ok:!1,error:{code:f,message:J}}}class h2{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return l0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return l0($,{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 l0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return l0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return l0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return l0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return l0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return l0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return l0($,{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 l0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return l0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return l0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return GV($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return GV($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}function q5($){return $?new Date($).getTime():void 0}function IN($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function y5($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__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:q5($.nextRunAt),lastRunAt:q5($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:IN($)}}function xN($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function KQ($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:q5($.startedAt),endedAt:q5($.completedAt),status:xN($.status),errorMessage:$.error}}class C2{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new SJ({dbPath:$.dbPath}),this.materializer=new NJ({store:this.store}),this.runner=new MJ({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,eventPublisher:$.eventPublisher,workspaceRoot:"",logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency})}async start(){if(this.disposed)throw Error("HubScheduleService has been disposed");if(this.started)return;this.started=!0,await this.runner.start()}async stop(){await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,await this.runner.dispose(),this.store.close()}createSchedule($){if(R9($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return y5(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?y5(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>y5(f))}updateSchedule($,f){if(f.cronPattern!==void 0)R9(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let W=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!W)throw Error("workspaceRoot is required for enabled schedules");let Q=this.store.updateHubSchedule($,{...f,scheduleId:$});return Q?y5(Q):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return KQ(J,$)}triggerScheduleNowDetached($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;return this.runner.tick().catch(()=>{return}),KQ(f,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let Q=f??this.store.getSpec(Z.specId);if(!Q||Q.source!=="hub-schedule")return;return KQ(Z,Q.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,W=0,Z=0,Q;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!Q&&j.status!=="success"&&j.status!=="completed")Q=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,W+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:W>0?Z/W/1000:0,lastFailure:Q}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,W)=>String(J.nextRunAt).localeCompare(String(W.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:W})=>({scheduleId:J.externalId,name:J.title,nextRunAt:W}))}}w5();function jM($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var XM="cline-hub-auth.";function HM($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function YM($,f){let J=new URL($),W=new URL(f);return J.search="",J.hash="",W.search="",W.hash="",J.toString()===W.toString()}async function AM($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=Y0(),W=await K0(J.discoveryPath);if(W?.url&&YM($.toString(),W.url))return W.authToken;return}async function FQ($={}){let f=d0($);if(!HM($)){let J=Y0(),W=await K0(J.discoveryPath);if(W?.url)return W.url}return $$(f.host,f.port,f.pathname)}async function S5($){return await new Promise((f,J)=>{(async()=>{let W=new URL($),Z=await AM(W);W.hash="";let Q=new WebSocket(W.toString(),Z?[`${XM}${Z}`]:void 0),j=new Map,X=0;Q.addEventListener("open",()=>{f({send(H){let Y=H.requestId??`hub-client-${++X}`;return new Promise((A,V)=>{j.set(Y,{resolve:A,reject:V});let B={kind:"command",envelope:{...H,requestId:Y}};Q.send(JSON.stringify(B))})},close(){Q.close()}})}),Q.addEventListener("message",(H)=>{let Y=JSON.parse(String(H.data));if(Y.kind==="reply"&&Y.envelope.requestId){let A=j.get(Y.envelope.requestId);if(A)j.delete(Y.envelope.requestId),A.resolve(Y.envelope)}}),Q.addEventListener("close",()=>{for(let H of j.values())H.reject(Error("Hub connection closed"));j.clear()}),Q.addEventListener("error",(H)=>{J(jM(H,$))})})().catch(J)})}async function FV($){try{return(await S5($)).close(),!0}catch{return!1}}async function RV($,f){let J=await FQ($),W=await S5(J);try{return await W.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{W.close()}}function RQ($){return $?JSON.parse(JSON.stringify($)):{}}function h5($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?RQ(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function DV($,f){return $.error?.message??`hub command failed: ${f}`}function VM($){let f=RQ($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let W=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof W?.message==="string"&&W.message.trim())return{...f,error:W.message.trim()};return f}function LV($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function BM($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function KM($){let f=RQ($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||LV(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||LV(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:VM($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class DQ{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new f$({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 f=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}),J=h5(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).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 f;try{f=await this.client.command("session.get",void 0,$)}catch(J){if(I$(J))return;throw J}return h5(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(DV(J,"session.messages"));let W=J.payload?.messages;return Array.isArray(W)?W:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let W=$.config,Z=await this.client.command("session.restore",{sessionId:f,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}:{}},f);if(!Z.ok)throw Error(DV(Z,"session.restore"));let Q=h5(Z.payload);if(J&&!Q?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=BM(Z.payload);return{sessionId:Q?.sessionId,startResult:Q?.sessionId?{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((W)=>h5({session:W})).filter((W)=>Boolean(W?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).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($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),W=this.client.subscribe((Z)=>{let Q=KM(Z);if(!Q)return;if(J.size>0&&!J.has(Q.sessionId))return;f.onEvent?.(Q)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),W}streamTeamProgress($,f){let J=this.client.subscribe((W)=>{if(W.event!=="team.progress"||!W.payload)return;f.onProjection?.(W.payload)});return this.ensureMetadataApplied().catch((W)=>{f.onError?.(W instanceof Error?W:Error(String(W)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).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($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.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 f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class LQ{client;constructor($){this.client=new f$({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 f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}function GM($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
561
561
  `).trim()||void 0}var zV=120,zQ="...";function sJ($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=zV)return f;let J=zV-Buffer.byteLength(zQ,"utf8");if(J<=0)return zQ;let W="";for(let Z of f){if(Buffer.byteLength(W+Z,"utf8")>J)break;W+=Z}return`${W}${zQ}`}async function OV($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await P1(J)].reverse().find((H)=>H.role==="assistant"),Q=Z?GM(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:sJ(Q&&Q.length>0?Q:X.length>0?X:j),severity:"info"}}import{captureSdkError as k5,createSessionId as nM}from"@cline/shared";import{createSessionId as RM}from"@cline/shared";import{createSessionId as FM}from"@cline/shared";function PM($){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 UM($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function C5($,f,J,W){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:PM($.status),participants:f?[...f.participants.values()]:[],metadata:UM($),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,...J?{usage:{...J}}:{},...W?{aggregateUsage:{...W}}:{}}}function u($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function m($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function E5($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function w0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function Ff($,f,J){return{version:"v1",event:$,eventId:FM("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function p0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let W=await $.sessionHost.getAccumulatedUsage?.(f);return C5(J,$.sessionState.get(f),W?.usage,W?.aggregateUsage)}async function r0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[W,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return B$({session:J,messages:W,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function b5($,f,J,W,Z={}){let Q=$.sessionState.get(f);if(Q){if(Z.interactive!==void 0)Q.interactive=Z.interactive;if(!Q.participants.has(J))Q.participants.set(J,{clientId:J,attachedAt:Date.now(),role:W});return Q}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:W}]])};return $.sessionState.set(f,j),j}async function OQ($,f){let J=RM("approval_"),W=f.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((Q)=>{$.pendingApprovals.set(J,{sessionId:W,resolve:Q}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},W))})}function _Q($,f,J){let W=$.pendingApprovals.get(f);if(!W)return;return $.pendingApprovals.delete(f),W.resolve(J),{sessionId:W.sessionId}}function TQ($,f,J){let W=0;for(let[Z,Q]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:Q.sessionId}))continue;$.pendingApprovals.delete(Z),Q.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},Q.sessionId)),W+=1}return W}async function _V($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return m(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,Q=f.payload?.approved===!0,j=_Q($,J,{approved:Q,reason:Z});if(!j)return m(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:Q,reason:Z},j.sessionId)),u(f,{approvalId:J,approved:Q})}import{createSessionId as zM}from"@cline/shared";function DM($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var TV={debug:10,info:20,warn:30,error:40,silent:50};function LM(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function g($,f,J={}){if(TV[$]<TV[LM()])return;let W=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,Q])=>[Z,DM(Q)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${W}`);return}console.log(`[hub] ${W}`)}function NQ($,f){let J=f instanceof Error?f.stack||f.message:String(f);g("error",$,{error:J})}async function NV($,f,J,W,Z,Q){let j=zM("capreq_"),X=performance.now();return g("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((H,Y)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:Q,resolve:(A)=>{if(g(A.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:A.ok,error:A.error,durationMs:Math.round(performance.now()-X)}),!A.ok){Y(Error(A.error||`Capability ${J} was rejected by ${Z}.`));return}H(A.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:W},f)),g("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function MV($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return W.onProgress?.(Q),u(f,{requestId:J})}function z1($,f,J){let W=0;for(let[Z,Q]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...Q}))continue;$.pendingCapabilityRequests.delete(Z),g("warn","capability.request.cancelled",{requestId:Z,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,reason:J}),Q.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,ok:!1,cancelled:!0,error:J},Q.sessionId)),W+=1}return W}async function yV($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",W=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!W||!Z)return m(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,W,Q,Z);return u(f,j)}catch(Q){return m(f,"capability_request_failed",Q instanceof Error?Q.message:String(Q))}}function qV($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",W=$.pendingCapabilityRequests.get(J);if(!W)return m(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==W.targetClientId)return m(f,"capability_wrong_client",`Capability request ${J} is owned by ${W.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==W.sessionId)return m(f,"capability_wrong_session",`Capability request ${J} belongs to session ${W.sessionId}`);$.pendingCapabilityRequests.delete(J);let Q=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return g(X?"info":"warn","capability.respond",{requestId:J,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:X,error:j}),W.resolve({ok:X,payload:Q,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:W.capabilityName,targetClientId:W.targetClientId,respondedByClientId:Z,ok:X,payload:Q,error:j},W.sessionId)),u(f,{requestId:J,ok:X})}import{createSessionId as OM}from"@cline/shared";function wV($,f){let J=f.payload,W=J?.clientId?.trim()||f.clientId?.trim()||OM("client_");return $.clients.set(W,{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:W,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),u(f,{clientId:W})}function SV($,f){let J=f.clientId?.trim(),W=J?$.clients.get(J):void 0;if(!J||!W)return m(f,"client_not_found","Client is not registered with this hub.");let Z=E5(f.payload?.metadata);if(W.lastSeenAt=Date.now(),Z)W.metadata=JSON.parse(JSON.stringify(Z));return u(f)}function hV($,f,J){let W=f.clientId?.trim();if(W)$.clients.delete(W),J(W),$.publish($.buildEvent("hub.client.disconnected",{clientId:W}));return u(f)}function CV($,f){return u(f,{clients:[...$.clients.values()]})}var _M=30000;function TM($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function NM($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function MM($,f,J){let W=J instanceof Error&&J.message.trim()?J.message:`Unknown session: ${f}`;return m($,jf,W)}function yM($){return $?$:void 0}function qM($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function wM($,f,J,W){let Z=performance.now(),Q=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:W},X=setInterval(()=>{if(Q)return;let A=Math.round(performance.now()-Z);g("warn","run.heartbeat",{...j,elapsedMs:A}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:A,...W?{timeoutMs:W}:{}},J.sessionId))},_M),H=$.sessionHost.runTurn(J);H.then((A)=>{if(!Q)return;g("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:A?.finishReason})},(A)=>{if(!Q)return;g("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:A})});let Y;try{if(!W)return await H;return await Promise.race([H,new Promise((A,V)=>{Y=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${W}ms.`;Q=!0,clearInterval(X),V(Error(B)),g("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),TQ($,(K)=>K.sessionId===J.sessionId,B),z1($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{g("error","run.timeout_abort_failed",{...j,error:K})})},W)})])}finally{if(Q=!0,clearInterval(X),Y)clearTimeout(Y)}}async function EV($,f){let J=w0(f),W=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof W.prompt==="string"?W.prompt:typeof W.input==="string"?W.input:"";if(!Z.trim())return m(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let Q=W.attachments&&typeof W.attachments==="object"&&!Array.isArray(W.attachments)?W.attachments:void 0,j=Array.isArray(Q?.userFiles)?Q.userFiles.filter((A)=>typeof A==="string"):void 0,X=qM(W);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let H;try{H=await wM($,f,{sessionId:J,prompt:Z,mode:yM(W.mode),delivery:W.delivery==="queue"||W.delivery==="steer"?W.delivery:void 0,userImages:Array.isArray(Q?.userImages)?Q.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(A){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);if(I$(A))return MM(f,J,A);throw $.publish($.buildEvent("run.failed",{reason:"error",error:A instanceof Error?A.message:String(A)},J)),A}if(H){let A=await r0($,J),V=NM(H);if($.publish($.buildEvent(TM(H.finishReason),{reason:H.finishReason,...V?{error:V}:{},result:H,...A?{snapshot:A}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let Y=await r0($,J);return u(f,H||Y?{...H?{result:H}:{},...Y?{snapshot:Y}:{}}:void 0)}async function bV($,f){let J=w0(f),W=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";TQ($,(Z)=>Z.sessionId===J,W);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){g("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{z1($,(Z)=>Z.sessionId===J,W)}return u(f,{applied:!0})}async function kV($,f){let J=w2(f.payload?.payload);if(!J)return m(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),u(f,{applied:!0})}async function IV($,f){switch(f.type){case"chunk":return;case"agent_event":await SM($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,W]=await Promise.all([p0($,f.payload.sessionId),r0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...W?{snapshot:W}:{}},f.payload.sessionId));return}case"ended":await hM($,f);return;default:return}}async function SM($,f){let{sessionId:J,event:W}=f.payload;if(W.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:W.iteration},J));return}if(W.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:W.iteration,hadToolCalls:W.hadToolCalls,toolCallCount:W.toolCallCount},J));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},J));return}if(W.contentType==="reasoning"){if(W.redacted&&!W.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof W.reasoning==="string"&&W.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:W.reasoning,redacted:W.redacted===!0},J));return}if(W.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:W.toolCallId,toolName:W.toolName,input:W.input},J));return}}if(W.type==="content_end"){switch(W.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:W.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:W.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:W.toolCallId,toolName:W.toolName,output:W.output,error:W.error},J));break}return}if(W.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,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:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":W.parentAgentId?"subagent":"lead",agentId:W.agentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(W.type==="done")$.publish($.buildEvent("agent.done",{reason:W.reason,text:W.text,iterations:W.iterations,usage:W.usage},J))}async function hM($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),W=J===f.payload.reason||J==="run.start.reply";if(W)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,Q]=await Promise.all([p0($,f.payload.sessionId),r0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await OV(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(W)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...Q?{snapshot:Q}:{}},f.payload.sessionId))}import{createSessionId as cV,parseRuntimeConfigExtensions as dV}from"@cline/shared";var vV={};w(vV,{SessionVersioningService:()=>O1,SessionVersioningError:()=>S0});var gV={};w(gV,{trimMessagesToCheckpoint:()=>mV,trimMessagesBeforeCheckpoint:()=>yQ,readSessionCheckpointHistory:()=>oJ,createRestoredCheckpointMetadata:()=>MQ,createCheckpointRestorePlan:()=>qQ,applyCheckpointToWorktree:()=>wQ});import{execFile as CM}from"node:child_process";import{promisify as EM}from"node:util";var I2=EM(CM);function oJ($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((W)=>!!W&&typeof W==="object"&&!Array.isArray(W)).flatMap((W)=>{let Z=String(W.ref??"").trim(),Q=Number(W.createdAt??0),j=Number(W.runCount??0);if(Z.length===0||!Number.isFinite(Q)||!Number.isInteger(j)||j<1)return[];let X=W.kind==="stash"||W.kind==="commit"?W.kind:void 0;return[{ref:Z,createdAt:Q,runCount:j,...X?{kind:X}:{}}]})}function MQ($,f){let J=oJ($).filter((Z)=>Z.runCount<=f),W=J.at(-1);return W?{latest:W,history:J}:void 0}function bM($,f){return $.reduce((J,W)=>{if(W.runCount>f)return J;if(!J||W.runCount>J.runCount)return W;return J},void 0)}function xV($,f){let J=0;for(let W=0;W<$.length;W+=1){let Z=$[W];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return W}throw Error(`Could not find user message for checkpoint run ${f}`)}function mV($,f){let J=xV($,f);return $.slice(0,J+1)}function yQ($,f){let J=xV($,f);return $.slice(0,J)}function qQ($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=bM(oJ($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} 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:J,cwd:W,...$.restoreMessages!==!1?{messages:mV($.messages??[],f)}:{}}}async function wQ($,f){if((await I2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await I2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await I2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await I2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await I2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await I2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}class S0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function kM($){let f=$.sessionId.trim();if(!f)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 f}class O1{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,W=kM({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(W);if(!Z)throw new S0("session_not_found",`Session ${W} not found`);let Q=f?await $.readMessages(W):void 0;if(f&&Q?.length===0)throw new S0("session_messages_not_found",`No messages found for session ${W}`);let j=qQ({session:Z,messages:Q,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??wQ)(j.cwd,j.checkpoint);let X=B$({session:Z,messages:Q});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let H=MQ(Z,$.checkpointRunCount),Y=$.restore?.omitCheckpointMessageFromSession?yQ(Q??[],$.checkpointRunCount):j.messages??[],A={sourceSession:Z,sourceMessages:Q,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:H,initialMessages:Y,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new S0("invalid_restore","start is required when restore.messages is true");let V=$.buildStartInput?await $.buildStartInput(A,$.start):$.start,B=await $.startSession(V),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??qX)(j.cwd,K,H?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:B$({session:G,messages:Y})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as su,HUB_COMPACTION_CAPABILITY as ou,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as eu,HUB_HOOK_CAPABILITY_PREFIX as $c,HUB_MISTAKE_LIMIT_CAPABILITY as fc,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Jc,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Wc,isHubToolExecutorName as IM}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Hc,HUB_COMPACTION_CAPABILITY as Yc,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Ac,HUB_HOOK_CAPABILITY_PREFIX as Vc,HUB_MISTAKE_LIMIT_CAPABILITY as Bc,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Kc,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Gc}from"@cline/shared";var xM=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Rf($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function mM($,f){let J=typeof $.name==="string"?$.name.trim():"",W=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",Q=Rf($.inputSchema);if(!J||!W||!Q||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:W,inputSchema:Q,...Rf($.lifecycle)?{lifecycle:Rf($.lifecycle)}:{}}}function hQ($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let W of $){if(!W||typeof W!=="object"||Array.isArray(W))continue;let Z=W,Q=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(Q==="tool"){let X=mM(Z,J);if(X)f.push(X);continue}if(Q==="toolExecutor"){let X=Z.executor;if(!IM(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(Q==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(Q==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...Rf(Z.config)?{config:Rf(Z.config)}:{}});continue}if(Q==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...Rf(Z.config)?{config:Rf(Z.config)}:{}});continue}if(Q==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(Q==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function uV($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function gM($){return Object.hasOwn($,"update")?$.update:$}function eJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function vM($){let f=($??[]).map(eJ).filter(Boolean);return f.length>0?new Set(f):void 0}function uM($,f,J){if(!J)return!0;let W=eJ($),Z=eJ(f),Q=W.includes(":")?W.split(":").at(-1)??W:W,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(W)||J.has(Z)||J.has(Q)||J.has(j)}function SQ($,f){let J=vM(f);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)=>uM(W.id,W.name,J))}function cM($,f){let J=async(W,Z)=>{let Q=eJ(W),X=SQ($,f).filter((B)=>B.id===Q||eJ(B.name)===Q||B.id.endsWith(`:${Q}`)).filter((B)=>!B.disabled);if(X.length!==1)return X.length>1?`Skill "${W}" is ambiguous. Use one of: ${X.map((B)=>B.id).join(", ")}`:`Skill "${W}" not found.`;let H=X[0].skill,Y=Z?.trim(),A=Y?`
562
562
  <command-args>${Y}</command-args>`:"",V=H.description?.trim()?`Description: ${H.description.trim()}
563
563
 
@@ -709,14 +709,14 @@ Caused by: ${$.stack}`;return Q}async function Ay($){return await new Promise((f
709
709
  reviewed_by = excluded.reviewed_by,
710
710
  reviewed_at = excluded.reviewed_at,
711
711
  version = team_outcome_fragments.version + 1`,[W,Q.outcomeId,Q.id,Q.section,Q.sourceAgentId,Q.sourceRunId??null,Q.content,Q.status,Q.reviewedBy??null,Q.reviewedAt?Q.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=g2($),W=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(W.length===0)return[];let Z=cQ();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
712
- WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),W.map((Q)=>Q.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function dQ($={}){try{let f=new Lf($);return f.init(),f}catch{let f=new W4({teamDir:$.teamDir});return f.init(),f}}function u5($,f){return by($,f)}function Iy($,f){let J=f?.["*"]??{},W=f?.[$]??{};return{...J,...W}.enabled!==!1}function xy($,f){return $.filter((J)=>Iy(J.name,f))}function TB($,f){return c1(xy($,f))}function c5(){return`team-${ky(5)}`}function lQ($,f,J,W,Z,Q,j,X){let H=I0[q$({mode:J})],Y=hf(f,W,J,Z??Sf);return TB(x1({cwd:$,...H,enableSkills:!!j,...Y,executors:{...j?{skills:j}:{},...X??{}}}),Q)}function my($){return lQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,gy,$.toolExecutors).some((f)=>f.name==="skills")}var gy=async()=>"";async function vy($){let f=_0();if(!b$({filePath:f}))return{tools:[]};let J=new Zf({clientFactory:P2({settingsPath:f})}),W;try{W=await Wf(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let H=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${H}`),{tools:[]}}let Z=W.filter((X)=>X.disabled!==!0),Q=await Promise.allSettled(Z.map((X)=>U2({serverName:X.name,provider:J}))),j=[];for(let[X,H]of Q.entries())if(H.status==="fulfilled")j.push(...H.value);else{let Y=H.reason instanceof Error?H.reason.message:String(H.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${Y}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function uy($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function cy($){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 dy($){let f=I0[q$({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.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 v2{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:W,logger:Z,telemetry:Q,createSpawnTool:j,onTeamRestored:X,userInstructionService:H,configExtensions:Y,toolExecutors:A}=$,V=$.onTeamEvent??(()=>{}),B=dy(f),K=j$(),G=[],R=f.teamName?.trim()||c5(),P=f.sessionId?.trim()||R,U=u5(Y,"rules"),F=u5(Y,"skills"),O=u5(Y,"workflows"),_=u5(Y,"plugins"),D=U||F||O,z=!1,N=Boolean(H),q=H,$0;if(!q&&D)q=V1({skills:F?{workspacePath:f.cwd,includePluginSkills:_,pluginSkillDirectories:_?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(q)await q.start().catch(()=>{});let A0=B.enableTools&&F&&Boolean(q)&&q?.hasConfiguredSkills(f.skills)===!0&&my({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:A}),o=q&&D?q.createExtension({includeRules:U,includeSkills:F,includeWorkflows:O,registerSkillsTool:A0,allowedSkillNames:f.skills}):void 0,V0=o?[...W??f.extensions??[],o]:W??f.extensions;if(B.enableTools){if(G.push(...lQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A)),!B.disableMcpSettingsTools){let r=await vy(f.logger);G.push(...r.tools),$0=r.shutdown}}let i,W$=B.enableAgentTeams?dQ():void 0,p=W$?.loadRuntime(P),a0=p?.state,k=p?.teammates??[],D0=new Map(k.map((r)=>[r.agentId,r])),n=f.sessionId||R,t0,T1=[],N1=!1,_f=Ef({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:V0,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(n))this.teamRuntimeEntries.set(n,{delegatedAgentConfigProvider:_f});let l2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:_f};if(this.teamRuntimeEntries.set(n,r),i=r.runtime,!i){if(i=new Gf({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(f0)=>{if(V(f0),i&&W$){if(f0.type==="teammate_spawned"&&f0.teammate?.rolePrompt){let D$={agentId:f0.agentId,rolePrompt:f0.teammate.rolePrompt,modelId:f0.teammate.modelId,maxIterations:f0.teammate.maxIterations};D0.set(D$.agentId,D$)}if(f0.type==="teammate_shutdown"&&!cy(f0.reason))D0.delete(f0.agentId);W$.handleTeamEvent(P,f0),W$.persistRuntime(P,i.exportState(),Array.from(D0.values()))}}}),a0)i.hydrateState(a0),N1=!0;r.runtime=i}if(!z){if(!i)return;z=!0;let f0=If({runtime:i,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(a0),restoredTeammates:k,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(D$)=>{T1=D$,t0?.addTools(D$)},createBaseTools:B.enableTools?()=>lQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A):void 0,teammateConfigProvider:_f});if(N1)i.recoverActiveRuns("runtime_recovered");if(f0.restoredFromPersistence)X?.();G.push(...f0.tools)}return i};if(B.enableSpawnAgent&&j){let r=j();G.push({...r,execute:async(f0,D$)=>{return l2(),r.execute(f0,D$)}})}if(B.enableAgentTeams)l2();let H4=TB(G,f.toolPolicies),V9=H4.some((r)=>r.name===J0.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),Tf=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get(n)?.runtime;if(!r)return;let f0=r.listTasks(),D$=f0.some((l$)=>l$.status==="in_progress"||l$.status==="pending"),g7=r.listRuns({}),NK=g7.some((l$)=>l$.status==="running"||l$.status==="queued");if(D$||NK){let l$=f0.filter((C0)=>C0.status==="in_progress"||C0.status==="pending").map((C0)=>`${C0.id} (${C0.status}): ${C0.title}`).join(", "),v7=g7.filter((C0)=>C0.status==="running"||C0.status==="queued").map((C0)=>`${C0.id} (${C0.status})`).join(", "),B9=[];if(l$)B9.push(`Unfinished tasks: ${l$}`);if(v7)B9.push(`Active runs: ${v7}`);return`[SYSTEM] You still have team obligations. ${B9.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,p2=V9?{requireCompletionTool:!0,...Tf?{completionGuard:Tf}:{}}:Tf?{completionGuard:Tf}:void 0;return{tools:H4,logger:Z??f.logger,telemetry:Q??f.telemetry,teamRuntime:i,teamRestoredFromPersistence:Boolean(a0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??_f,extensions:V0,completionPolicy:p2,registerLeadAgent:(r)=>{if(t0=r,T1.length>0)r.addTools(c1(T1,[...K]))},shutdown:async(r)=>{if(uy(i,r),this.teamRuntimeEntries.delete(n),await $0?.(),!N)q?.stop()}}}}var yB={};w(yB,{requestDesktopToolApproval:()=>rQ});import{mkdir as ly,readFile as py,unlink as ry,writeFile as iy}from"node:fs/promises";import{join as MB}from"node:path";function ny($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function ay($){return new Promise((f)=>setTimeout(f,$))}async function pQ($){try{await ry($)}catch{}}async function rQ($,f={}){let J=f.approvalDir?.trim(),W=f.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await ly(J,{recursive:!0});let Z=ny(`${$.toolCallId}`),Q=MB(J,`${W}.request.${Z}.json`),j=MB(J,`${W}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await iy(Q,`${JSON.stringify({requestId:Z,sessionId:W,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
712
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),W.map((Q)=>Q.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function dQ($={}){try{let f=new Lf($);return f.init(),f}catch{let f=new W4({teamDir:$.teamDir});return f.init(),f}}function u5($,f){return by($,f)}function Iy($,f){let J=f?.["*"]??{},W=f?.[$]??{};return{...J,...W}.enabled!==!1}function xy($,f){return $.filter((J)=>Iy(J.name,f))}function TB($,f){return c1(xy($,f))}function c5(){return`team-${ky(5)}`}function lQ($,f,J,W,Z,Q,j,X){let H=I0[q$({mode:J})],Y=hf(f,W,J,Z??Sf);return TB(x1({cwd:$,...H,enableSkills:!!j,...Y,executors:{...j?{skills:j}:{},...X??{}}}),Q)}function my($){return lQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,gy,$.toolExecutors).some((f)=>f.name==="skills")}var gy=async()=>"";async function vy($){let f=_0();if(!b$({filePath:f}))return{tools:[]};let J=new Zf({clientFactory:P2({settingsPath:f})}),W;try{W=await Wf(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let H=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${H}`),{tools:[]}}let Z=W.filter((X)=>X.disabled!==!0),Q=await Promise.allSettled(Z.map((X)=>U2({serverName:X.name,provider:J}))),j=[];for(let[X,H]of Q.entries())if(H.status==="fulfilled")j.push(...H.value);else{let Y=H.reason instanceof Error?H.reason.message:String(H.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${Y}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function uy($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function cy($){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 dy($){let f=I0[q$({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.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 v2{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:W,logger:Z,telemetry:Q,createSpawnTool:j,onTeamRestored:X,userInstructionService:H,configExtensions:Y,toolExecutors:A}=$,V=$.onTeamEvent??(()=>{}),B=dy(f),K=j$(),G=[],R=f.teamName?.trim()||c5(),P=f.sessionId?.trim()||R,U=u5(Y,"rules"),F=u5(Y,"skills"),O=u5(Y,"workflows"),_=u5(Y,"plugins"),D=U||F||O,z=!1,N=Boolean(H),q=H,$0;if(!q&&D)q=V1({skills:F?{workspacePath:f.cwd,includePluginSkills:_,pluginSkillDirectories:_?$.pluginSkillDirectories:void 0,pluginPaths:f.pluginPaths,cwd:f.cwd}:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(q)await q.start().catch(()=>{});let A0=B.enableTools&&F&&Boolean(q)&&q?.hasConfiguredSkills(f.skills)===!0&&my({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:A}),o=q&&D?q.createExtension({includeRules:U,includeSkills:F,includeWorkflows:O,registerSkillsTool:A0,allowedSkillNames:f.skills}):void 0,V0=o?[...W??f.extensions??[],o]:W??f.extensions;if(B.enableTools){if(G.push(...lQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A)),!B.disableMcpSettingsTools){let r=await vy(f.logger);G.push(...r.tools),$0=r.shutdown}}let i,W$=B.enableAgentTeams?dQ():void 0,p=W$?.loadRuntime(P),a0=p?.state,k=p?.teammates??[],D0=new Map(k.map((r)=>[r.agentId,r])),n=f.sessionId||R,t0,T1=[],N1=!1,_f=Ef({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:V0,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(n))this.teamRuntimeEntries.set(n,{delegatedAgentConfigProvider:_f});let l2=()=>{if(!B.enableAgentTeams)return;let r=this.teamRuntimeEntries.get(n)??{delegatedAgentConfigProvider:_f};if(this.teamRuntimeEntries.set(n,r),i=r.runtime,!i){if(i=new Gf({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(f0)=>{if(V(f0),i&&W$){if(f0.type==="teammate_spawned"&&f0.teammate?.rolePrompt){let D$={agentId:f0.agentId,rolePrompt:f0.teammate.rolePrompt,modelId:f0.teammate.modelId,maxIterations:f0.teammate.maxIterations};D0.set(D$.agentId,D$)}if(f0.type==="teammate_shutdown"&&!cy(f0.reason))D0.delete(f0.agentId);W$.handleTeamEvent(P,f0),W$.persistRuntime(P,i.exportState(),Array.from(D0.values()))}}}),a0)i.hydrateState(a0),N1=!0;r.runtime=i}if(!z){if(!i)return;z=!0;let f0=If({runtime:i,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(a0),restoredTeammates:k,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(D$)=>{T1=D$,t0?.addTools(D$)},createBaseTools:B.enableTools?()=>lQ(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,A):void 0,teammateConfigProvider:_f});if(N1)i.recoverActiveRuns("runtime_recovered");if(f0.restoredFromPersistence)X?.();G.push(...f0.tools)}return i};if(B.enableSpawnAgent&&j){let r=j();G.push({...r,execute:async(f0,D$)=>{return l2(),r.execute(f0,D$)}})}if(B.enableAgentTeams)l2();let H4=TB(G,f.toolPolicies),VW=H4.some((r)=>r.name===J0.SUBMIT_AND_EXIT&&r.lifecycle?.completesRun===!0),Tf=B.enableAgentTeams?()=>{let r=this.teamRuntimeEntries.get(n)?.runtime;if(!r)return;let f0=r.listTasks(),D$=f0.some((l$)=>l$.status==="in_progress"||l$.status==="pending"),g7=r.listRuns({}),NK=g7.some((l$)=>l$.status==="running"||l$.status==="queued");if(D$||NK){let l$=f0.filter((C0)=>C0.status==="in_progress"||C0.status==="pending").map((C0)=>`${C0.id} (${C0.status}): ${C0.title}`).join(", "),v7=g7.filter((C0)=>C0.status==="running"||C0.status==="queued").map((C0)=>`${C0.id} (${C0.status})`).join(", "),BW=[];if(l$)BW.push(`Unfinished tasks: ${l$}`);if(v7)BW.push(`Active runs: ${v7}`);return`[SYSTEM] You still have team obligations. ${BW.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,p2=VW?{requireCompletionTool:!0,...Tf?{completionGuard:Tf}:{}}:Tf?{completionGuard:Tf}:void 0;return{tools:H4,logger:Z??f.logger,telemetry:Q??f.telemetry,teamRuntime:i,teamRestoredFromPersistence:Boolean(a0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(n)?.delegatedAgentConfigProvider??_f,extensions:V0,completionPolicy:p2,registerLeadAgent:(r)=>{if(t0=r,T1.length>0)r.addTools(c1(T1,[...K]))},shutdown:async(r)=>{if(uy(i,r),this.teamRuntimeEntries.delete(n),await $0?.(),!N)q?.stop()}}}}var yB={};w(yB,{requestDesktopToolApproval:()=>rQ});import{mkdir as ly,readFile as py,unlink as ry,writeFile as iy}from"node:fs/promises";import{join as MB}from"node:path";function ny($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function ay($){return new Promise((f)=>setTimeout(f,$))}async function pQ($){try{await ry($)}catch{}}async function rQ($,f={}){let J=f.approvalDir?.trim(),W=f.sessionId?.trim();if(!J||!W)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await ly(J,{recursive:!0});let Z=ny(`${$.toolCallId}`),Q=MB(J,`${W}.request.${Z}.json`),j=MB(J,`${W}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await iy(Q,`${JSON.stringify({requestId:Z,sessionId:W,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
713
713
  `,"utf8");let H=f.timeoutMs??300000,Y=f.pollIntervalMs??200,A=Date.now();while(Date.now()-A<H){try{let V=await py(j,"utf8"),B=JSON.parse(V),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([pQ(j),pQ(Q)]),K}catch{}await ay(Y)}return await pQ(Q),{approved:!1,reason:"Tool approval request timed out"}}X$();X$();var hB={};w(hB,{uninstallPlugin:()=>$7});import{existsSync as c2,readdirSync as ty,readFileSync as sy,rmdirSync as oy,rmSync as ey,statSync as $q}from"node:fs";import{basename as i0,dirname as _1,extname as fq,isAbsolute as Jq,join as d$,relative as Wq,resolve as u2,sep as iQ}from"node:path";import{discoverPluginModulePaths as Zq,resolvePluginConfigSearchPaths as Qq}from"@cline/shared/storage";var oQ="_installed",jq="package",Xq=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function nQ($){return $.trim().toLowerCase()}function J$($,f){let J=f?.trim();if(!J)return;$.add(J)}function Hq($){return $.replace(/-[0-9a-f]{12}$/i,"")}function aQ($){let f=fq($);return f?$.slice(0,-f.length):$}function tQ($){if(!c2($))return;try{let f=JSON.parse(sy($,"utf8"));return typeof f.name==="string"?f.name.trim():void 0}catch{return}}function eQ($,f){let J=Wq(f,$);return J===""||!J.startsWith("..")&&!Jq(J)}function qB($){let J=u2($).split(iQ),W=J.lastIndexOf(oQ);if(W<0)return;let Z=J[W+1];if(!Z)return;let Q=Xq.get(Z)??1,j=W+2+Q;if(J.length<j)return;let X=J.slice(0,j).join(iQ)||iQ;return c2(X)?X:void 0}function d5($){try{return ty($,{withFileTypes:!0})}catch{return[]}}function Yq($){let f=d$($,oQ);if(!c2(f))return[];let J=[];for(let W of d5(f)){if(!W.isDirectory())continue;let Z=d$(f,W.name);if(W.name==="git"){for(let Q of d5(Z)){if(!Q.isDirectory())continue;let j=d$(Z,Q.name);for(let X of d5(j))if(X.isDirectory())J.push(d$(j,X.name))}continue}for(let Q of d5(Z))if(Q.isDirectory())J.push(d$(Z,Q.name))}return J.sort((W,Z)=>W.localeCompare(Z))}function wB($){try{return Zq($)}catch{return[]}}function sQ($){let f=wB($),J=new Set;J$(J,i0($)),J$(J,Hq(i0($))),J$(J,tQ(d$($,"package.json"))),J$(J,tQ(d$($,jq,"package.json")));for(let W of f)J$(J,i0(W)),J$(J,aQ(i0(W)));return{installPath:$,entryPaths:f,names:[...J].sort((W,Z)=>W.localeCompare(Z)),installed:!0}}function Aq($,f){let J=u2($),W=f.find((j)=>eQ(J,j));if(!W)return;let Z=_1(J);while(Z!==W&&Z!==_1(Z)){if(c2(d$(Z,"package.json")))return Z;Z=_1(Z)}let Q=i0(J);if((Q==="index.ts"||Q==="index.js")&&_1(J)!==W)return _1(J);return J}function SB($,f){let J=Aq($,f);if(!J)return;let W=new Set;return J$(W,i0($)),J$(W,aQ(i0($))),J$(W,i0(J)),J$(W,aQ(i0(J))),J$(W,tQ(d$(J,"package.json"))),{installPath:J,entryPaths:[$],names:[...W].sort((Z,Q)=>Z.localeCompare(Q)),installed:!1}}function Vq($){let f=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Qq(f).filter((J)=>c2(J))}function Bq($){let f=new Map;for(let J of $){for(let W of Yq(J))f.set(W,sQ(W));for(let W of wB(J)){let Z=qB(W);if(Z){if(!f.has(Z))f.set(Z,sQ(Z));continue}let Q=SB(W,$);if(Q)f.set(Q.installPath,Q)}}return[...f.values()].sort((J,W)=>J.installPath.localeCompare(W.installPath))}function Kq($,f){let J=nQ(f);if(!J)return!1;if(nQ($.installPath)===J)return!0;return $.names.some((W)=>nQ(W)===J)}function Gq($,f,J){let W=u2($);for(let Q of f){if(eQ(W,Q.installPath))return Q;if(Q.entryPaths.some((j)=>u2(j)===W))return Q}let Z=qB(W);if(Z)return sQ(Z);if(c2(W))return SB(W,J);return}function Pq($){let f=O0(),J=f.disabledPlugins;if(!J?.length)return;let W=J.filter((Z)=>{let Q=u2(Z);if(eQ(Q,$.installPath))return!1;return!$.entryPaths.some((j)=>u2(j)===Q)});if(W.length===J.length)return;h$({...f,disabledPlugins:W})}function Uq($){let f=_1($);while(f!==_1(f)&&i0(f)!==oQ){try{oy(f)}catch{return}f=_1(f)}}function Fq($){return`${$.names[0]??i0($.installPath)} at ${$.installPath}`}async function $7($){let f=Vq($),J=Bq(f),W=$.path?.trim(),Z=$.name?.trim(),Q;if(W){if(Q=Gq(W,J,f),!Q)throw Error(`No plugin found at ${W}`)}else{if(!Z)throw Error("plugin uninstall requires a plugin name");let X=J.filter((H)=>Kq(H,Z));if(X.length===0)throw Error(`No plugin found matching "${Z}"`);if(X.length>1)throw Error(`Multiple plugins match "${Z}": ${X.map(Fq).join(", ")}`);Q=X[0]}let j=$q(Q.installPath,{throwIfNoEntry:!1});if(!j)throw Error(`Plugin install path does not exist: ${Q.installPath}`);if(ey(Q.installPath,{recursive:j.isDirectory(),force:!0}),Pq(Q),Q.installed)Uq(Q.installPath);return{name:Z||Q.names[0]||i0(Q.installPath),installPath:Q.installPath,removedPaths:[Q.installPath],entryPaths:Q.entryPaths}}var sB={};w(sB,{updateLocalProvider:()=>s5,saveLocalProviderSettings:()=>H7,saveLocalProviderOAuthCredentials:()=>B7,resolveLocalClineAuthToken:()=>K7,refreshProviderModelsFromSource:()=>Y7,normalizeOAuthProvider:()=>A7,loginLocalProvider:()=>V7,listLocalProviders:()=>j7,getLocalProviderModels:()=>X7,ensureCustomProvidersLoaded:()=>n5,deleteLocalProvider:()=>o5,addLocalProvider:()=>Q7});import*as N0 from"@cline/llms";import{getClineEnvironmentConfig as mq}from"@cline/shared";import{existsSync as Rq,mkdirSync as Dq,readFileSync as Lq,writeFileSync as zq}from"node:fs";import{mkdir as Oq,readFile as _q,writeFile as Tq}from"node:fs/promises";import{dirname as f7,join as Nq}from"node:path";import*as h0 from"@cline/llms";import{ModelCapabilitySchema as Mq,ProviderCapabilitySchema as yq,ProviderClientSchema as qq,ProviderProtocolSchema as wq}from"@cline/shared";import{z as l}from"zod";var Sq=l.object({id:l.string().optional(),name:l.string().optional(),maxTokens:l.number().optional(),contextWindow:l.number().optional(),maxInputTokens:l.number().optional(),capabilities:l.array(Mq).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),hq=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:wq.optional(),client:qq.optional(),capabilities:l.array(yq).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),CB=l.object({provider:hq.optional(),models:l.record(l.string(),Sq).optional()}).passthrough(),EB=l.object({version:l.literal(1),providers:l.record(l.string(),CB)}),Cq=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),l5=new Set;function bB($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function zf($){return Nq(f7($.getFilePath()),"models.json")}function p5(){return{version:1,providers:{}}}function kB($){let f=Cq.safeParse($);if(!f.success)return p5();let J={};for(let[W,Z]of Object.entries(f.data.providers)){let Q=CB.safeParse(Z);if(Q.success)J[W]=Q.data}return{version:1,providers:J}}function J7($){if(!Rq($))return p5();try{let f=Lq($,"utf8");return kB(JSON.parse(f))}catch{}return p5()}async function d2($){try{let f=await _q($,"utf8");return kB(JSON.parse(f))}catch{}return p5()}function IB($,f){Dq(f7($),{recursive:!0});let J=EB.parse(f);zq($,`${JSON.stringify(J,null,2)}
714
714
  `,"utf8")}async function r5($,f){await Oq(f7($),{recursive:!0});let J=EB.parse(f);await Tq($,`${JSON.stringify(J,null,2)}
715
- `,"utf8")}function xB($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function mB($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function gB($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function Eq($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function vB($,f){return $??f??"openai-chat"}function uB($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function cB($,f,J){let W=new Set(f?.capabilities??J??[]);if(f?.supportsVision)W.add("images");if(f?.supportsAttachments)W.add("files");if(f?.supportsReasoning)W.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function bq($,f){for(let[J,W]of Object.entries(f??{})){let Z=W.id?.trim()||J.trim();if(!Z)continue;h0.registerModel($,Z,cB(Z,W))}}function kq($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function Iq($){return Object.assign({},...h0.resolveProviderModelCatalogKeys($).map((J)=>h0.getGeneratedModelsForProvider(J)))}function xq($){let f=$.provider.trim();if(!f||h0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let W=h0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=Iq(f),Q=gB($.capabilities),j=Q.length>0?Q:void 0,X=$.model?.trim(),H={...Z,...W?.models??{}};if(X)H[X]=kq(X,H[X],j);let Y=Object.keys(H).filter(Boolean),A=X||Y[0];if(!A)return;let V=vB($.protocol,W?.provider.protocol),B=uB($.client,V,W?.provider.client);h0.registerProvider({provider:{id:f,name:W?.provider.name??bB(f),description:W?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:A,capabilities:mB($.capabilities)??W?.provider.capabilities,source:"file"},models:H})}function i5($){for(let f of Object.values($.providers))xq(f.settings)}function Z4($,f){let J=f.models??{};if(!Eq(f.provider)){bq($,J);return}let W=gB(f.provider.capabilities),Z=Object.entries(J).map(([Y,A])=>({id:A.id?.trim()||Y.trim(),model:A})).filter(({id:Y})=>Y.length>0),Q=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=vB(f.provider.protocol,void 0),X=uB(f.provider.client,j,void 0),H=Object.fromEntries(Z.map(({id:Y,model:A})=>[Y,{...cB(Y,A,W.length>0?W:void 0),status:"active"}]));h0.registerProvider({provider:{id:$,name:f.provider.name.trim()||bB($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:Q,capabilities:mB(f.provider.capabilities),source:"file"},models:H})}function dB($){let f=zf($);if(l5.has(f))return;let J=J7(f);for(let[W,Z]of Object.entries(J.providers))Z4(W,Z);l5.add(f)}async function n5($){let f=zf($);if(l5.has(f))return;let J=await d2(f);for(let[W,Z]of Object.entries(J.providers))Z4(W,Z);l5.add(f)}function gq($){return $.apiKey??$.auth?.apiKey}function vq($){return($.auth?.accessToken?.trim()??"").length>0}function pB($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function uq($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function cq($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of $)J=J*31+W.charCodeAt(0)>>>0;return f[J%f.length]}function rB($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>xB(f,J))}async function dq($,f){let J=await N0.getModelsForProvider($);if(!f)return J;let W=await l8($,{loadPrivateOnAuth:!0,failOnError:!1},f);return W?.knownModels?{...J,...W.knownModels}:J}function W7($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function lq($){if(!$?.length)return;return[...new Set($)]}function pq($,f){return lq([...$??[],...f??[]])}function rq($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function iq($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function nq($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(iq)}var a5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},lB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function aq($){if(!$)return[a5];if($.source!=="system")return $.baseUrl?[a5,lB]:[a5];let f=[];if($.env?.length)f.push(a5);if($.baseUrl)f.push(lB);return f}function tq($,f){return f.split(".").reduce((J,W)=>{if(!J||typeof J!=="object")return;return J[W]},$)}function sq($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function oq($,f,J){if(!$?.length)return;let W={};for(let Z of $){let j=sq(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:tq(f,Z.path))??Z.defaultValue;if(j!==void 0)W[Z.path]=j}return W}function iB($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function Z7($,f){let J=f?.includes("vision")??!1,W=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function nB($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await B6($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function aB($,f){let J=$.read(),W=!1;if(J.providers[f])delete J.providers[f],W=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,W=!0;if(W)$.write(J);N0.unregisterProvider(f)}async function Q7($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!W&&!Z){let G=zf($);if((await d2(G)).providers[J]){let P=await o5($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return aB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=f.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let j=W7(f.models),X=f.modelsSourceUrl?.trim(),H=await nB({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(H.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&H.includes(f.defaultModelId.trim())?f.defaultModelId.trim():H[0],A=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,V=iB(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:W,headers:V,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=zf($),K=await d2(B);return K.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:A,modelsSourceUrl:X},models:Z7(H,A)},await r5(B,K),Z4(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:H.length}}async function s5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=zf($),Z=await d2(W),Q=Z.providers[J];if(!Q){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let D=f.modelsSourceUrl?.trim(),z=W7(f.models)[0]??_.model?.trim();if(!z&&!D)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:f.name?.trim()||pB(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:z,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:z?Z7([z],_.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??Q.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let H=f.capabilities===void 0?Q.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?Q.provider.protocol:f.protocol??void 0,A=f.client===void 0?Q.provider.client:f.client??void 0,V=W7(f.models),B=f.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(Q.models??{}).map((_)=>_.trim()).filter(Boolean),R=await nB({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?Q.provider.defaultModelId?.trim():f.defaultModelId?.trim(),U=P&&R.includes(P)?P:R[0],O={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:U};if(Y)O.protocol=Y;else delete O.protocol;if(A)O.client=A;else delete O.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)O.apiKey=_;else delete O.apiKey}if(f.headers!==void 0){let _=iB(f.headers);if(_)O.headers=_;else delete O.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")O.timeout=f.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:U,protocol:Y,client:A,capabilities:H,modelsSourceUrl:B},models:Z7(R,H)},await r5(W,Z),Z4(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:R.length}}async function o5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=zf($),Z=await d2(W);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await r5(W,Z),N0.unregisterProvider(J),aB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W}}async function j7($){let f=$.read(),J=N0.getProviderIds(),W=await Promise.all(J.map(async(Q)=>{let[j,X]=await Promise.all([N0.getProvider(Q),N0.getModelsForProvider(Q)]),H=rB(X),Y=f.providers[Q]?.settings,A=j?.name??pB(Q),V=pq(j?.capabilities,Y?.capabilities),B=nq(j?.metadata)??aq(j);return{provider:{id:Q,name:A,models:H.length,color:cq(Q),letter:uq(A),enabled:Boolean(Y),apiKey:Y?gq(Y):void 0,oauthAccessTokenPresent:Y?vq(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:oq(B,Y,j),modelList:H},rank:rq(j?.metadata)}}));return W.sort((Q,j)=>{if(Q.rank!==j.rank)return Q.rank-j.rank;return Q.provider.name.localeCompare(j.provider.name)||Q.provider.id.localeCompare(j.provider.id)}),{providers:W.map((Q)=>Q.provider),settingsPath:$.getFilePath()}}async function X7($,f){let J=$.trim(),W=await dq(J,f),Z=rB(W);return{providerId:J,models:Z}}function t5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function tB($,f){if(!t5(f))return t5($)?{...$}:void 0;let J=t5($)?{...$}:{};for(let[W,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[W];continue}if(t5(Z)){let Q=tB(J[W],Z);if(Q&&Object.keys(Q).length>0)J[W]=Q;else delete J[W];continue}J[W]=Z}return Object.keys(J).length>0?J:void 0}function H7($,f){let J=f.providerId.trim();if(f.enabled===!1){let Q=$.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return $.write(Q),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,Q)&&typeof f[Q]==="string")if(f[Q].trim().length===0)delete Z[Q];else Z[Q]=f[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,Q))Z[Q]=f[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,Q)&&f[Q]!=null){let j=tB(Z[Q],f[Q]);if(j)Z[Q]=j;else delete Z[Q]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function Y7($,f){let J=f.trim(),W=$.getProviderSettings(J),Q=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),X=K6(j,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!j||!X)return{providerId:J,refreshed:!1};let H=await s5($,{providerId:J,name:Q.name,baseUrl:j,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:X,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:H.modelsCount}}function A7($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function eq($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function V7($,f,J,W){let Z=e8({onPrompt:async(Q)=>Q.defaultValue??"",openUrl:J,onOpenUrlError:({error:Q})=>{throw Q instanceof Error?Q:Error(String(Q))}});if($==="cline")return H2({apiBaseUrl:f?.baseUrl?.trim()||mq().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:W});if($==="oca")return f2({mode:f?.oca?.mode,callbacks:Z,telemetry:W});return Y2({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:W})}function B7($,f,J,W){let Z={...J?.auth??{},accessToken:eq(f,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function K7($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var oB={};w(oB,{getProviderConfigFields:()=>G7});import*as e5 from"@cline/llms";import{isOAuthProviderId as $w}from"@cline/shared";var fw=["apiKey","baseUrl","awsRegion","awsProfile","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Jw={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 Ww($,f){let J={};for(let W of fw){let Z=$[W],Q=f[W];if(Z||Q)J[W]={...Z,...Q}}return J}function Zw($){let f=Jw[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:Ww($.fields,f.fields)}}var Qw=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function jw($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return Qw.has($)}function G7($){let f=e5.normalizeProviderId($);if($w(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=e5.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let W=J?.provider.baseUrl,Z={apiKey:{}};if(jw(f,J))Z.baseUrl={defaultValue:W};return Zw({providerId:f,authMethod:"api-key",fields:Z})}var JK={};w(JK,{resolveLegacyClineAuth:()=>F7,migrateLegacyProviderSettings:()=>Q4});import{existsSync as Xw,readFileSync as Hw}from"node:fs";import{dirname as Yw,join as P7}from"node:path";import*as f9 from"@cline/llms";import{resolveClineDataDir as Aw}from"@cline/shared/storage";var $9="openai",fK=f9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,eB=128000;function F7($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let W=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:W,accountId:J.userInfo?.id}}catch{return}}function h($){let f=$?.trim();return f?f:void 0}function $K($){if(!Xw($))return;try{let f=Hw($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function Vw($){let f=$.dataDir??Aw(),J=$.globalStatePath??P7(f,"globalState.json"),W=$.secretsPath??P7(f,"secrets.json"),Z=$K(J),Q=$K(W);if(!Z&&!Q)return;return{globalState:Z??{},secrets:Q??{}}}function U7($){if($===$9)return fK;return $}function Bw($,f,J,W){let Z=J==="plan"?"planMode":"actMode",Q=f===W?h(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?h(typeof $[X]==="string"?$[X]:void 0):void 0)??Q}function Kw($,f,J){let W=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Q=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??W,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,H=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!X&&H===void 0)return;return{...X?{effort:X}:{},...H!==void 0?{budgetTokens:H}:{}}}function Gw($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),W=h(J.access_token),Z=h(J.refresh_token),Q=h(J.accountId);if(!W&&!Z&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...Z?{refreshToken:Z}:{},...Q?{accountId:Q}:{}}}}catch{return}}function Pw($){let f=f9.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function Uw($,f,J,W){let Z=U7($),Q=h(W==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=Bw(f,$,W,Q)??Pw(Z),X=Kw(f,Z,W),H=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey},A={};if($==="openai-codex")Object.assign(A,Gw(J));if($==="cline")try{let U=h(J["cline:clineAccountId"]);if(U)A.auth={...A.auth??{},...F7(U)}}catch{}if($===$9&&f.openAiHeaders)A.headers=f.openAiHeaders;if($==="bedrock"){let U=f.awsAuthentication==="profile"||f.awsUseProfile===!0;A.aws={accessKey:h(J.awsAccessKey),secretKey:h(J.awsSecretKey),sessionToken:h(J.awsSessionToken),region:h(f.awsRegion),authentication:f.awsAuthentication,profile:U?h(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:h(f.awsBedrockEndpoint),customModelBaseId:h(W==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")A.gcp={projectId:h(f.vertexProjectId),region:h(f.vertexRegion)};if($===$9&&(f.azureApiVersion||f.azureIdentity!==void 0))A.azure={apiVersion:h(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")A.sap={clientId:h(J.sapAiCoreClientId),clientSecret:h(J.sapAiCoreClientSecret),tokenUrl:h(f.sapAiCoreTokenUrl),resourceGroup:h(f.sapAiResourceGroup),deploymentId:h(W==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){A.oca={mode:f.ocaMode};let U=h(J.ocaRefreshToken);if(U)A.auth={...A.auth??{},refreshToken:U}}if($==="qwen")A.apiLine=f.qwenApiLine;if($==="moonshot")A.apiLine=f.moonshotApiLine;if($==="zai")A.apiLine=f.zaiApiLine;if($==="minimax")A.apiLine=f.minimaxApiLine;let V={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=h(Y[$]),K=h(V[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...H?{timeout:H}:{},...A},R=i8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function Fw($,f){if($!==fK)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:eB,maxInputTokens:eB,capabilities:["streaming","tools","images"]}}}}function Rw($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let Q=h(Z);if(Q)J.add(Q)}if(h(f.apiKey))J.add("anthropic");if(h(f.openRouterApiKey))J.add("openrouter");if(h(f.openAiApiKey))J.add($9);if(h(f.openAiNativeApiKey))J.add("openai-native");if(h(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(h(f.geminiApiKey))J.add("gemini");if(h(f.ollamaApiKey))J.add("ollama");if(h(f.awsAccessKey)||h(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||h($.awsProfile))J.add("bedrock");if(h($.vertexProjectId)||h($.vertexRegion))J.add("vertex");if(h(f.clineApiKey))J.add("cline");let W=F7(h(f["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)J.add("cline");if(h(f.ocaApiKey))J.add("oca");if(h(f.sapAiCoreClientId)||h(f.sapAiCoreClientSecret)||h($.sapAiCoreTokenUrl)||h($.sapAiCoreBaseUrl)||h($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function Q4($){let f=$.providerSettingsManager.read(),J=Vw($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:W,secrets:Z}=J,Q=W.mode==="plan"?"plan":"act",j=Rw(W,Z),X=Y1();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let H=new Date().toISOString(),Y=0,A=P7(Yw($.providerSettingsManager.getFilePath()),"models.json"),V=J7(A),B=0;for(let R of j){let P=U7(R);if(X.providers[P])continue;let U=Uw(R,W,Z,Q);if(!U)continue;X.providers[P]={settings:U,updatedAt:H,tokenSource:"migration"},Y+=1;let F=Fw(P,U);if(F&&!V.providers[P])V.providers[P]=F,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=h(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),G=K?U7(K):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)IB(A,V);return{migrated:Y>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}L0();w5();var WK={};w(WK,{FileTeamPersistenceStore:()=>J9});import{appendFileSync as Dw,existsSync as R7,mkdirSync as Lw,readFileSync as zw,renameSync as Ow,unlinkSync as _w,writeFileSync as Tw}from"node:fs";import{join as D7}from"node:path";import{resolveTeamDataDir as Nw}from"@cline/shared/storage";function Mw($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class J9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=Mw($.teamName),J=$.baseDir?.trim()||Nw();this.dirPath=D7(J,f),this.statePath=D7(this.dirPath,"state.json"),this.taskHistoryPath=D7(this.dirPath,"task-history.jsonl")}loadState(){if(!R7(this.statePath))return;try{let $=zw(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return JV(f.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 f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Tw(J,`${JSON.stringify(f,null,2)}
715
+ `,"utf8")}function xB($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function mB($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function gB($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function Eq($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function vB($,f){return $??f??"openai-chat"}function uB($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function cB($,f,J){let W=new Set(f?.capabilities??J??[]);if(f?.supportsVision)W.add("images");if(f?.supportsAttachments)W.add("files");if(f?.supportsReasoning)W.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:W.size>0?[...W]:void 0}}function bq($,f){for(let[J,W]of Object.entries(f??{})){let Z=W.id?.trim()||J.trim();if(!Z)continue;h0.registerModel($,Z,cB(Z,W))}}function kq($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function Iq($){return Object.assign({},...h0.resolveProviderModelCatalogKeys($).map((J)=>h0.getGeneratedModelsForProvider(J)))}function xq($){let f=$.provider.trim();if(!f||h0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let W=h0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=Iq(f),Q=gB($.capabilities),j=Q.length>0?Q:void 0,X=$.model?.trim(),H={...Z,...W?.models??{}};if(X)H[X]=kq(X,H[X],j);let Y=Object.keys(H).filter(Boolean),A=X||Y[0];if(!A)return;let V=vB($.protocol,W?.provider.protocol),B=uB($.client,V,W?.provider.client);h0.registerProvider({provider:{id:f,name:W?.provider.name??bB(f),description:W?.provider.description,protocol:V,client:B,baseUrl:J,modelsSourceUrl:W?.provider.modelsSourceUrl,defaultModelId:A,capabilities:mB($.capabilities)??W?.provider.capabilities,source:"file"},models:H})}function i5($){for(let f of Object.values($.providers))xq(f.settings)}function Z4($,f){let J=f.models??{};if(!Eq(f.provider)){bq($,J);return}let W=gB(f.provider.capabilities),Z=Object.entries(J).map(([Y,A])=>({id:A.id?.trim()||Y.trim(),model:A})).filter(({id:Y})=>Y.length>0),Q=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=vB(f.provider.protocol,void 0),X=uB(f.provider.client,j,void 0),H=Object.fromEntries(Z.map(({id:Y,model:A})=>[Y,{...cB(Y,A,W.length>0?W:void 0),status:"active"}]));h0.registerProvider({provider:{id:$,name:f.provider.name.trim()||bB($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:Q,capabilities:mB(f.provider.capabilities),source:"file"},models:H})}function dB($){let f=zf($);if(l5.has(f))return;let J=J7(f);for(let[W,Z]of Object.entries(J.providers))Z4(W,Z);l5.add(f)}async function n5($){let f=zf($);if(l5.has(f))return;let J=await d2(f);for(let[W,Z]of Object.entries(J.providers))Z4(W,Z);l5.add(f)}function gq($){return $.apiKey??$.auth?.apiKey}function vq($){return($.auth?.accessToken?.trim()??"").length>0}function pB($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function uq($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function cq($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let W of $)J=J*31+W.charCodeAt(0)>>>0;return f[J%f.length]}function rB($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>xB(f,J))}async function dq($,f){let J=await N0.getModelsForProvider($);if(!f)return J;let W=await l8($,{loadPrivateOnAuth:!0,failOnError:!1},f);return W?.knownModels?{...J,...W.knownModels}:J}function W7($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function lq($){if(!$?.length)return;return[...new Set($)]}function pq($,f){return lq([...$??[],...f??[]])}function rq($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function iq($){if(!$||typeof $!=="object")return!1;let f=$;return typeof f.path==="string"&&f.path.trim().length>0&&typeof f.label==="string"&&f.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(f.type))}function nq($){let f=$?.configFields;if(!Array.isArray(f))return;return f.filter(iq)}var a5={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},lB={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function aq($){if(!$)return[a5];if($.source!=="system")return $.baseUrl?[a5,lB]:[a5];let f=[];if($.env?.length)f.push(a5);if($.baseUrl)f.push(lB);return f}function tq($,f){return f.split(".").reduce((J,W)=>{if(!J||typeof J!=="object")return;return J[W]},$)}function sq($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function oq($,f,J){if(!$?.length)return;let W={};for(let Z of $){let j=sq(Z.path==="baseUrl"&&f?.baseUrl===void 0?J?.baseUrl:tq(f,Z.path))??Z.defaultValue;if(j!==void 0)W[Z.path]=j}return W}function iB($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function Z7($,f){let J=f?.includes("vision")??!1,W=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:W}]))}async function nB($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await B6($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function aB($,f){let J=$.read(),W=!1;if(J.providers[f])delete J.providers[f],W=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,W=!0;if(W)$.write(J);N0.unregisterProvider(f)}async function Q7($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!W&&!Z){let G=zf($);if((await d2(G)).providers[J]){let P=await o5($,{providerId:J});return{providerId:J,settingsPath:P.settingsPath,modelsPath:P.modelsPath,modelsCount:0}}return aB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(J))throw Error(`provider "${J}" already exists`);let Q=f.name.trim();if(!Q)throw Error("name is required");if(!W)throw Error("baseUrl is required");let j=W7(f.models),X=f.modelsSourceUrl?.trim(),H=await nB({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(H.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&H.includes(f.defaultModelId.trim())?f.defaultModelId.trim():H[0],A=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,V=iB(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:W,headers:V,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=zf($),K=await d2(B);return K.providers[J]={provider:{name:Q,baseUrl:W,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:A,modelsSourceUrl:X},models:Z7(H,A)},await r5(B,K),Z4(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:H.length}}async function s5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=zf($),Z=await d2(W),Q=Z.providers[J];if(!Q){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let D=f.modelsSourceUrl?.trim(),z=W7(f.models)[0]??_.model?.trim();if(!z&&!D)throw Error(`provider "${J}" cannot be updated because no model is configured`);Q={provider:{name:f.name?.trim()||pB(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:z,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:z?Z7([z],_.capabilities):{}}}if(!Q.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??Q.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??Q.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let H=f.capabilities===void 0?Q.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?Q.provider.protocol:f.protocol??void 0,A=f.client===void 0?Q.provider.client:f.client??void 0,V=W7(f.models),B=f.modelsSourceUrl===void 0?Q.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(Q.models??{}).map((_)=>_.trim()).filter(Boolean),R=await nB({providerId:J,explicitModels:V,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let P=f.defaultModelId===void 0?Q.provider.defaultModelId?.trim():f.defaultModelId?.trim(),U=P&&R.includes(P)?P:R[0],O={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:U};if(Y)O.protocol=Y;else delete O.protocol;if(A)O.client=A;else delete O.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)O.apiKey=_;else delete O.apiKey}if(f.headers!==void 0){let _=iB(f.headers);if(_)O.headers=_;else delete O.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")O.timeout=f.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:U,protocol:Y,client:A,capabilities:H,modelsSourceUrl:B},models:Z7(R,H)},await r5(W,Z),Z4(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W,modelsCount:R.length}}async function o5($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let W=zf($),Z=await d2(W);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await r5(W,Z),N0.unregisterProvider(J),aB($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:W}}async function j7($){let f=$.read(),J=N0.getProviderIds(),W=await Promise.all(J.map(async(Q)=>{let[j,X]=await Promise.all([N0.getProvider(Q),N0.getModelsForProvider(Q)]),H=rB(X),Y=f.providers[Q]?.settings,A=j?.name??pB(Q),V=pq(j?.capabilities,Y?.capabilities),B=nq(j?.metadata)??aq(j);return{provider:{id:Q,name:A,models:H.length,color:cq(Q),letter:uq(A),enabled:Boolean(Y),apiKey:Y?gq(Y):void 0,oauthAccessTokenPresent:Y?vq(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:V,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:B,configValues:oq(B,Y,j),modelList:H},rank:rq(j?.metadata)}}));return W.sort((Q,j)=>{if(Q.rank!==j.rank)return Q.rank-j.rank;return Q.provider.name.localeCompare(j.provider.name)||Q.provider.id.localeCompare(j.provider.id)}),{providers:W.map((Q)=>Q.provider),settingsPath:$.getFilePath()}}async function X7($,f){let J=$.trim(),W=await dq(J,f),Z=rB(W);return{providerId:J,models:Z}}function t5($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function tB($,f){if(!t5(f))return t5($)?{...$}:void 0;let J=t5($)?{...$}:{};for(let[W,Z]of Object.entries(f)){if(Z==null||Z===""){delete J[W];continue}if(t5(Z)){let Q=tB(J[W],Z);if(Q&&Object.keys(Q).length>0)J[W]=Q;else delete J[W];continue}J[W]=Z}return Object.keys(J).length>0?J:void 0}function H7($,f){let J=f.providerId.trim();if(f.enabled===!1){let Q=$.read();if(delete Q.providers[J],Q.lastUsedProvider===J)delete Q.lastUsedProvider;return $.write(Q),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let Q of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,Q)&&typeof f[Q]==="string")if(f[Q].trim().length===0)delete Z[Q];else Z[Q]=f[Q];for(let Q of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,Q))Z[Q]=f[Q];for(let Q of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,Q)&&f[Q]!=null){let j=tB(Z[Q],f[Q]);if(j)Z[Q]=j;else delete Z[Q]}return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function Y7($,f){let J=f.trim(),W=$.getProviderSettings(J),Q=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=W?.baseUrl?.trim()||Q?.baseUrl?.trim(),X=K6(j,Q?.baseUrl,Q?.modelsSourceUrl);if(!W||!Q||!j||!X)return{providerId:J,refreshed:!1};let H=await s5($,{providerId:J,name:Q.name,baseUrl:j,apiKey:W.apiKey,headers:W.headers??null,timeoutMs:W.timeout??null,modelsSourceUrl:X,protocol:W.protocol??Q.protocol??null,client:W.client??Q.client??null,capabilities:W.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:H.modelsCount}}function A7($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function eq($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function V7($,f,J,W){let Z=e8({onPrompt:async(Q)=>Q.defaultValue??"",openUrl:J,onOpenUrlError:({error:Q})=>{throw Q instanceof Error?Q:Error(String(Q))}});if($==="cline")return H2({apiBaseUrl:f?.baseUrl?.trim()||mq().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:W});if($==="oca")return f2({mode:f?.oca?.mode,callbacks:Z,telemetry:W});return Y2({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:W})}function B7($,f,J,W){let Z={...J?.auth??{},accessToken:eq(f,W),refreshToken:W.refresh,accountId:W.accountId,expiresAt:W.expires},Q={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(Q,{tokenSource:"oauth"}),Q}function K7($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var oB={};w(oB,{getProviderConfigFields:()=>G7});import*as e5 from"@cline/llms";import{isOAuthProviderId as $w}from"@cline/shared";var fw=["apiKey","baseUrl","awsRegion","awsProfile","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],Jw={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 Ww($,f){let J={};for(let W of fw){let Z=$[W],Q=f[W];if(Z||Q)J[W]={...Z,...Q}}return J}function Zw($){let f=Jw[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:Ww($.fields,f.fields)}}var Qw=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function jw($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return Qw.has($)}function G7($){let f=e5.normalizeProviderId($);if($w(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=e5.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let W=J?.provider.baseUrl,Z={apiKey:{}};if(jw(f,J))Z.baseUrl={defaultValue:W};return Zw({providerId:f,authMethod:"api-key",fields:Z})}var JK={};w(JK,{resolveLegacyClineAuth:()=>F7,migrateLegacyProviderSettings:()=>Q4});import{existsSync as Xw,readFileSync as Hw}from"node:fs";import{dirname as Yw,join as P7}from"node:path";import*as fW from"@cline/llms";import{resolveClineDataDir as Aw}from"@cline/shared/storage";var $W="openai",fK=fW.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,eB=128000;function F7($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;let W=typeof J.expiresAt==="number"&&Number.isFinite(J.expiresAt)?J.expiresAt<10000000000?J.expiresAt*1000:J.expiresAt:void 0;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:W,accountId:J.userInfo?.id}}catch{return}}function h($){let f=$?.trim();return f?f:void 0}function $K($){if(!Xw($))return;try{let f=Hw($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function Vw($){let f=$.dataDir??Aw(),J=$.globalStatePath??P7(f,"globalState.json"),W=$.secretsPath??P7(f,"secrets.json"),Z=$K(J),Q=$K(W);if(!Z&&!Q)return;return{globalState:Z??{},secrets:Q??{}}}function U7($){if($===$W)return fK;return $}function Bw($,f,J,W){let Z=J==="plan"?"planMode":"actMode",Q=f===W?h(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?h(typeof $[X]==="string"?$[X]:void 0):void 0)??Q}function Kw($,f,J){let W=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,Q=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??W,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,H=typeof Q==="number"&&Number.isInteger(Q)&&Q>0?Q:void 0;if(!X&&H===void 0)return;return{...X?{effort:X}:{},...H!==void 0?{budgetTokens:H}:{}}}function Gw($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),W=h(J.access_token),Z=h(J.refresh_token),Q=h(J.accountId);if(!W&&!Z&&!Q)return;return{...W?{apiKey:W}:{},auth:{...W?{accessToken:W}:{},...Z?{refreshToken:Z}:{},...Q?{accountId:Q}:{}}}}catch{return}}function Pw($){let f=fW.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function Uw($,f,J,W){let Z=U7($),Q=h(W==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=Bw(f,$,W,Q)??Pw(Z),X=Kw(f,Z,W),H=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey},A={};if($==="openai-codex")Object.assign(A,Gw(J));if($==="cline")try{let U=h(J["cline:clineAccountId"]);if(U)A.auth={...A.auth??{},...F7(U)}}catch{}if($===$W&&f.openAiHeaders)A.headers=f.openAiHeaders;if($==="bedrock"){let U=f.awsAuthentication==="profile"||f.awsUseProfile===!0;A.aws={accessKey:h(J.awsAccessKey),secretKey:h(J.awsSecretKey),sessionToken:h(J.awsSessionToken),region:h(f.awsRegion),authentication:f.awsAuthentication,profile:U?h(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:h(f.awsBedrockEndpoint),customModelBaseId:h(W==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")A.gcp={projectId:h(f.vertexProjectId),region:h(f.vertexRegion)};if($===$W&&(f.azureApiVersion||f.azureIdentity!==void 0))A.azure={apiVersion:h(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")A.sap={clientId:h(J.sapAiCoreClientId),clientSecret:h(J.sapAiCoreClientSecret),tokenUrl:h(f.sapAiCoreTokenUrl),resourceGroup:h(f.sapAiResourceGroup),deploymentId:h(W==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){A.oca={mode:f.ocaMode};let U=h(J.ocaRefreshToken);if(U)A.auth={...A.auth??{},refreshToken:U}}if($==="qwen")A.apiLine=f.qwenApiLine;if($==="moonshot")A.apiLine=f.moonshotApiLine;if($==="zai")A.apiLine=f.zaiApiLine;if($==="minimax")A.apiLine=f.minimaxApiLine;let V={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=h(Y[$]),K=h(V[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...H?{timeout:H}:{},...A},R=i8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function Fw($,f){if($!==fK)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:eB,maxInputTokens:eB,capabilities:["streaming","tools","images"]}}}}function Rw($,f){let J=new Set;for(let Z of[$.actModeApiProvider,$.planModeApiProvider]){let Q=h(Z);if(Q)J.add(Q)}if(h(f.apiKey))J.add("anthropic");if(h(f.openRouterApiKey))J.add("openrouter");if(h(f.openAiApiKey))J.add($W);if(h(f.openAiNativeApiKey))J.add("openai-native");if(h(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(h(f.geminiApiKey))J.add("gemini");if(h(f.ollamaApiKey))J.add("ollama");if(h(f.awsAccessKey)||h(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||h($.awsProfile))J.add("bedrock");if(h($.vertexProjectId)||h($.vertexRegion))J.add("vertex");if(h(f.clineApiKey))J.add("cline");let W=F7(h(f["cline:clineAccountId"]));if(W?.accessToken||W?.refreshToken||W?.accountId)J.add("cline");if(h(f.ocaApiKey))J.add("oca");if(h(f.sapAiCoreClientId)||h(f.sapAiCoreClientSecret)||h($.sapAiCoreTokenUrl)||h($.sapAiCoreBaseUrl)||h($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)J.add("sapaicore");return J}function Q4($){let f=$.providerSettingsManager.read(),J=Vw($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:W,secrets:Z}=J,Q=W.mode==="plan"?"plan":"act",j=Rw(W,Z),X=Y1();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let H=new Date().toISOString(),Y=0,A=P7(Yw($.providerSettingsManager.getFilePath()),"models.json"),V=J7(A),B=0;for(let R of j){let P=U7(R);if(X.providers[P])continue;let U=Uw(R,W,Z,Q);if(!U)continue;X.providers[P]={settings:U,updatedAt:H,tokenSource:"migration"},Y+=1;let F=Fw(P,U);if(F&&!V.providers[P])V.providers[P]=F,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=h(Q==="plan"?W.planModeApiProvider:W.actModeApiProvider),G=K?U7(K):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)IB(A,V);return{migrated:Y>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}L0();w5();var WK={};w(WK,{FileTeamPersistenceStore:()=>JW});import{appendFileSync as Dw,existsSync as R7,mkdirSync as Lw,readFileSync as zw,renameSync as Ow,unlinkSync as _w,writeFileSync as Tw}from"node:fs";import{join as D7}from"node:path";import{resolveTeamDataDir as Nw}from"@cline/shared/storage";function Mw($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class JW{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=Mw($.teamName),J=$.baseDir?.trim()||Nw();this.dirPath=D7(J,f),this.statePath=D7(this.dirPath,"state.json"),this.taskHistoryPath=D7(this.dirPath,"task-history.jsonl")}loadState(){if(!R7(this.statePath))return;try{let $=zw(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return JV(f.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 f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;Tw(J,`${JSON.stringify(f,null,2)}
716
716
  `,"utf8"),Ow(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),Dw(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
717
- `,"utf8")}ensureDir(){if(!R7(this.dirPath))Lw(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(R7(this.statePath))_w(this.statePath)}}var ZK={};w(ZK,{ChatViewStateSchema:()=>L7,ChatSummarySchema:()=>X9,ChatSessionStatusSchema:()=>Z9,ChatSessionConfigSchema:()=>W9,ChatMessageSchema:()=>j9,ChatMessageRoleSchema:()=>Q9});import{z as C}from"zod";var W9=C.object({workspaceRoot:C.string().min(1),cwd:C.string().optional(),provider:C.string().min(1),model:C.string().min(1),mode:C.enum(["act","plan"]).default("act"),apiKey:C.string(),systemPrompt:C.string().optional(),rules:C.string().optional(),maxIterations:C.number().int().positive().optional(),enableTools:C.boolean(),enableSpawn:C.boolean().optional(),enableTeams:C.boolean().optional(),autoApproveTools:C.boolean().optional(),missionStepInterval:C.number().int().positive().optional(),missionTimeIntervalMs:C.number().int().positive().optional()}),Z9=C.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),Q9=C.enum(["user","assistant","tool","system","status","error"]),j9=C.object({id:C.string().min(1),sessionId:C.string().nullable(),role:Q9,content:C.string(),createdAt:C.number().int().nonnegative(),meta:C.object({stream:C.enum(["stdout","stderr"]).optional(),toolName:C.string().optional(),iteration:C.number().int().nonnegative().optional(),agentId:C.string().optional(),conversationId:C.string().optional(),hookEventName:C.string().optional(),inputTokens:C.number().int().nonnegative().optional(),outputTokens:C.number().int().nonnegative().optional(),checkpoint:C.object({ref:C.string(),createdAt:C.number().int().nonnegative(),runCount:C.number().int().positive(),kind:C.enum(["stash","commit"]).optional()}).optional()}).optional()}),X9=C.object({toolCalls:C.number().int().nonnegative(),tokensIn:C.number().int().nonnegative(),tokensOut:C.number().int().nonnegative()}),L7=C.object({sessionId:C.string().nullable(),status:Z9,config:W9,messages:C.array(j9),rawTranscript:C.string(),error:C.string().nullable(),summary:X9});var QK={};w(QK,{CORE_BUILD_VERSION:()=>z7});var z7=jA;import{Agent as HS,createAgentRuntime as YS}from"@cline/agents";var XK={};w(XK,{fetchClineRecommendedModels:()=>O7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>H9});import{getClineEnvironmentConfig as yw}from"@cline/shared";var qw=5000,H9={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"]}]};function ww($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function jK($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function Sw($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],W=Array.isArray(f.free)?f.free:[],Z=J.map(jK).filter((j)=>j!==null),Q=W.map(jK).filter((j)=>j!==null);if(Z.length===0&&Q.length===0)return null;return{recommended:Z,free:Q}}function hw($){let f=$.baseUrl?.trim();if(f)return f;let J=yw().apiBaseUrl;try{return($.providerSettingsManager??new R$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function Cw($,f,J){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await $(f,{signal:W.signal})}finally{clearTimeout(Z)}}async function O7($={}){try{let f=hw($),J=$.fetchImpl??fetch,W=await Cw(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??qw);if(!W.ok)throw Error(`HTTP ${W.status}`);let Z=await W.json(),Q=Sw(Z);if(Q)return Q}catch{}return ww(H9)}var HK={};w(HK,{loadLlmsConfigFromFile:()=>T7,defineLlmsConfig:()=>_7});import{readFile as Ew}from"node:fs/promises";import bw from"node:path";function _7($){return $}async function T7($){let f=bw.resolve($),J=await Ew(f,"utf8"),W;try{W=JSON.parse(J)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${Q}`)}return kw(W,f)}function kw($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var GK={};w(GK,{createLlmsSdk:()=>M7,DefaultLlmsSdk:()=>j4});import{BUILT_IN_PROVIDER_IDS as VK,createHandler as mw,createHandlerAsync as gw,getProviderCollection as vw,hasProvider as BK,registerAsyncHandler as uw,registerHandler as cw,registerModel as dw,registerProvider as KK}from"@cline/llms";function YK($){return $?{...$}:{}}function Iw($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function xw($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function AK($){let f=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:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class N7{providers=new Map;register($){xw($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...YK($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Iw($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...YK($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.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($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class j4{configuredProviders=new N7;constructor($){this.applyConfig($)}createHandler($){return mw(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return gw(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(KK($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)cw($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)uw($.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 f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);KK({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){dw($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...VK]}async getBuiltInProviders(){return(await Promise.all(VK.map((f)=>vw(f)))).filter((f)=>f!==void 0).map((f)=>AK({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=BK(f.id),W=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof W==="string"&&BK(W);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function M7($){return new j4($)}GQ();async function lw(){return Promise.resolve().then(() => (IQ(),UB))}function GS(){return new Date().toISOString()}function PS($){if(RK($)!=="providers.json")return;let f=q7($);if(RK(f)!=="settings")return;return q7(f)}class R${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??KS(),this.dataDir=$.dataDir??PS(this.filePath),this.dataDir||!$.filePath)Q4({providerSettingsManager:this,dataDir:this.dataDir});if(dB(this),i5(this.read()),y7(this.filePath))try{FK(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!y7(this.filePath))return Y1();try{let $=VS(this.filePath,"utf8"),f=JSON.parse($),J=Z2.safeParse(f);if(J.success)return i5(J.data),J.data}catch{}return Y1()}write($){let f=Z2.parse($),J=q7(this.filePath);if(!y7(J))AS(J,{recursive:!0,mode:448});BS(this.filePath,`${JSON.stringify(f,null,2)}
718
- `,"utf8");try{FK(this.filePath,384)}catch{}i5(f)}saveProviderSettings($,f={}){let J=i8.parse($),W=this.read(),Z=J.provider,Q=f.setLastUsed!==!1,j=W.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",H={...W,providers:{...W.providers,[Z]:{settings:J,updatedAt:GS(),tokenSource:X}},lastUsedProvider:Q?Z:W.lastUsedProvider};return this.write(H),H}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return m0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return m0(f,$)}async refreshCatalog(){try{await J2({})}catch{}}}L0();z5();import{getClineEnvironmentConfig as US,isOAuthProviderId as FS}from"@cline/shared";var w7="workos:";function RS($,f){if($==="cline")return`${w7}${f}`;return f}function DS($,f){if($==="cline"&&f.toLowerCase().startsWith(w7))return f.slice(w7.length);return f}function LS($){let J=z0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function zS($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=LS(f);if(W)return W;return Date.now()-1}function OS($,f){let J=f.auth?.accessToken?.trim(),W=f.auth?.refreshToken?.trim();if(!J||!W)return null;let Z=DS($,J);if(!Z)return null;return{access:Z,refresh:W,expires:zS(f,Z),accountId:f.auth?.accountId}}function _S($,f){let J=$?.expiresAt,W=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===W}class Y9 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 S7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new R$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!FS($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let W=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,W),W}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let W=OS($,J);if(!W)return null;let Z=await this.resolveCredentials($,J,W,f);if(!Z)throw new Y9($);let Q=RS($,Z.access),j={...J.auth??{},accessToken:Q,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let X={...J,auth:j},H=!_S(J.auth,X.auth);if(H)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Q,accountId:Z.accountId,refreshed:H}}async resolveCredentials($,f,J,W){if($==="cline")return fJ(J,{apiBaseUrl:f.baseUrl?.trim()||US().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if($==="oca")return u8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return WJ(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as TS}from"@cline/shared";import{nanoid as NS}from"nanoid";class DK{list($){return $?n0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((H)=>H.id===J);if(W<0)return{sessionId:f.sessionId,prompts:n0($),updated:!1};let Z=$.pendingPrompts[W];if(!Z)return{sessionId:f.sessionId,prompts:n0($),updated:!1};let Q=f.prompt===void 0?Z.prompt:TS(f.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:Q,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(W,1),MS($,X,W,Z.delivery),{sessionId:f.sessionId,prompts:n0($),prompt:A9(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:f.sessionId,prompts:n0($),removed:!1};let[Z]=$.pendingPrompts.splice(W,1);return{sessionId:f.sessionId,prompts:n0($),prompt:Z?A9(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j}=f,X=$.pendingPrompts.findIndex((H)=>H.prompt===J);if(X>=0){let[H]=$.pendingPrompts.splice(X,1),Y={...H,prompt:J,mode:W??H.mode,userImages:Q??H.userImages,userFiles:j??H.userFiles};if(Z==="steer"||H.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let H={id:`pending_${Date.now()}_${NS(5)}`,prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(H);else $.pendingPrompts.push(H)}return n0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(f<0)return{prompts:n0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:n0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:n0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),n0($)}clear($){return $.pendingPrompts.length=0,[]}}class h7{deps;service=new DK;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:n0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{W=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,W&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=A9(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function A9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function n0($){return $.pendingPrompts.map(A9)}function MS($,f,J,W){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(W==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class E7{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let W=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=fW(J),j=!!W&&(!Q.agentId||Q.agentId===C7(W.agent));JW(Z,J,j?{isPrimaryAgentEvent:!0,agentId:C7(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(eZ(J,f),f.type==="agent_event"){let W={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};JW(W,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let W=S$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:C7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(W)r$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await $Q($,f,this.deps.invokeBackendOptional),J)fQ(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let H=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!H)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await H.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let W=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:Q,delivery:j})}handlePluginLog($,f,J){let W=this.deps.getSession($),Z=J??W?.config.extensionContext?.logger??W?.config.logger;if(!Z||!f||typeof f!=="object")return;let Q=f,j=typeof Q.message==="string"?Q.message:"";if(!j)return;let X=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(X.sessionId??=$,typeof Q.pluginName==="string"&&Q.pluginName)X.pluginName=Q.pluginName;if(Q.level==="debug"){Z.debug(j,X);return}if(Q.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function C7($){return $.getAgentId()}function b7($){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:J1($.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 k7($,f){let J=$[f];return typeof J==="function"?J:null}async function LK($,f,...J){let W=k7($,f);if(!W)throw Error(`session service method not available: ${f}`);return Promise.resolve(W.apply($,J))}async function zK($,f,...J){let W=k7($,f);if(!W)return;await Promise.resolve(W.apply($,J))}async function OK($,f,...J){let W=k7($,f);if(!W)return;return await Promise.resolve(W.apply($,J))}X$();L0();function I7($,f,J,W){return $1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=f.enableTools?x1({cwd:f.cwd,...I0[q$({mode:f.mode})],executors:W}):[];if(f.enableSpawnAgent)Q.push(I7($,f,J,W));return c1(Q)},onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let X=S$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId});if(X)r$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...X});n2(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime,X=$.subAgentStarts.get(Q.subAgentId),H=X?Date.now()-X.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
719
- `).length:0;n2(f.telemetry,{event:"ended",ulid:J,durationMs:H,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...S$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as yS,stat as qS}from"node:fs/promises";var wS=20480000;async function _K($){let f=await qS($);if(!f.isFile())throw Error("Path is not a file");if(f.size>wS)throw Error("File is too large to read into context.");let J=await yS($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var TK=5000;function X4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xS($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=X4(f.inputTokens),W=X4(f.outputTokens),Z=X4(f.cacheReadTokens),Q=X4(f.cacheWriteTokens),j=X4(f.totalCost);if(J===void 0||W===void 0||Z===void 0||Q===void 0||j===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Z,cacheWriteTokens:Q,totalCost:j}}function mS($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class F${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new CJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new O1;constructor($){let f=hS();if(f)IS(f);let J=Kf($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new v2,this.createAgentInstance=$.createAgent??((W)=>new e$(W)),this.defaultCapabilities=F0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new R$,this.oauthTokenManager=$.oauthTokenManager??new S7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new h7({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 E7({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,Z,Q)=>{this.invoke("persistSessionMessages",W,Z,Q)},enqueuePendingPrompt:(W,Z)=>this.pendingPromptsController.enqueue(W,Z),invokeBackendOptional:(W,...Z)=>this.invokeOptional(W,...Z)})}async startSession($){let f=$.source??G0.CLI,J=s(),W=$.config.sessionId?.trim()??"",Z=W||ES(),Q=$,j=Q.initialMessages??[],X=j.length>0?vf(j):B0(),H=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!H)throw Error("session service method not available: ensureSessionsDir");let Y=x7(H,Z),A=x7(Y,`${Z}.messages.json`),V=x7(Y,`${Z}.json`),B=J1($.config),K=y0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:B,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:A}),G;if(W.length>0&&j.length>0&&!Q.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",Z);if(k)K=k,G={manifestPath:V,messagesPath:k.messages_path||A,manifest:k}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:Y,rootMessagesPath:G?.messagesPath??A,manifest:K});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,P);let U=F0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,_=O?.extensionContext?.logger??O?.logger,D=O?.extensionContext?.automation,z;z=await RH({input:Q,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,k.payload,_);return}this.eventBridge.handlePluginEvent(Z,k,D)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(Z,k),z.config.onTeamEvent?.(k)},createSpawnTool:()=>I7({getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,D0,n)=>this.eventBridge.dispatchAgentEvent(k,D0,n),invokeBackendOptional:(k,...D0)=>this.invokeOptional(k,...D0)},z.config,Z,F),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(Z,()=>k)}});let N=await this.runtimeBuilder.build(z.runtimeBuilderInput),q=z.config,$0=z.providerConfig;if(N.teamRuntime&&!q.teamName?.trim())q.teamName=N.teamRuntime.getTeamName();let A0=[...N.tools,...q.extraTools??[]],o=N.extensions??z.extensions,V0={sessionId:Z,providerId:$0.providerId,modelId:$0.modelId,apiKey:$0.apiKey,baseUrl:$0.baseUrl,headers:$0.headers,knownModels:$0.knownModels,providerConfig:$0,thinking:q.thinking,reasoningEffort:q.reasoningEffort??$0.reasoningEffort,systemPrompt:q.systemPrompt,maxIterations:q.maxIterations,execution:q.execution,prepareTurn:$8(q),tools:A0,hooks:z.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:_K,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(k)=>{let D0=z.requestToolApproval,n=this.sessions.get(Z);if(n)await this.markTurnPending(n);try{if(!D0)return{approved:!1,reason:"Tool approval callback is not configured."};return await D0(k)}finally{let t0=this.sessions.get(Z);if(t0?.status==="pending")await this.markTurnRunning(t0)}}:void 0,telemetry:q.telemetry,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(Z);return k?lJ(k.prompt,k.mode??q.mode):void 0},logger:N.logger??q.logger,extensionContext:q.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(Z,q,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await z.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let D0=this.sessions.get(Z);if(!D0)return;let n=D0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,n,q.systemPrompt)}catch(t0){q.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:t0}),Of(q.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:t0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:q.providerId,modelId:q.modelId}})}}};let i=this.createAgentInstance(V0);if(V0.onEvent)i.subscribeEvents(V0.onEvent);N.registerLeadAgent?.(i);let W$=S$({agentId:i.getAgentId(),conversationId:i.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(LH(q,Z,W.length>0,B,W$),W$)r$(q.telemetry,{ulid:Z,modelId:q.modelId,provider:q.providerId,...W$});if(N.teamRuntime)O4(q.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:i.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let p={sessionId:Z,config:q,sessionMetadata:Q.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:N,agent:i,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,p),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,j,p.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(p,"completed",0)}let a0;try{if(Q.prompt?.trim())if(a0=await this.executeTurn(p,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!p.interactive)await this.finalizeSingleRun(p,a0.finishReason);else await this.completeInteractiveTurn(p,a0.finishReason)}catch(k){if(p.interactive&&p.aborting)a0=await this.completeAbortedInteractiveTurn(p);else throw Of(p.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),k}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:A,result:a0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let W=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),W=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.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 Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw Of(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=qZ(this.usageBySession.get($)),J=qZ(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!W0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!W0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return b7(f);let J=$.trim();if(!J)return;let W=await this.getRow(J);if(W)return T8(W);let Z=await this.readManifest(J);return Z?A5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(T8),W=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(W.has(Z.sessionId))continue;J.unshift(b7(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return P1(J.messagesPath);let W=await this.readManifest(f);return P1(W?.messages_path)}async dispatchHookEvent($){await oY($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),W=J.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 Z=await this.executeAgentTurn($,W,J.userImages,J.userFiles);while(JQ($,Z.finishReason)){let Q=await WQ($);if(Q.length===0)break;let j=ZQ($,Q);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(dJ($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),W=B0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,W){let Z=$.started||$.agent.getMessages().length>0,Q=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??B0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=B0(),$.turnUsageByAgent=new Map,P4($.config.telemetry,$.sessionId,$.config.mode),Nf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let H=Z?()=>$.agent.continue(f,J,W):()=>$.agent.run(f,J,W),Y=await this.runWithAuthRetry($,H,Q);$.started=!0;let A=c4(Y.messages,Y,Q);$.persistedMessages=A;let V=M8($.turnUsageByAgent?.values()??[]),B=X0(j,Y.usage),K=X0(X0(B0(),Y.usage),V),G=X0(X,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,A,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(H){throw Of($.config.telemetry,{component:"core",operation:"session.turn",error:H,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),H}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((W)=>W.name===J0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,r2($.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($,f){let J=J1($.config),W=kS(f.prompt).trim();if(!W)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await qf(W,J);zH($.config.telemetry,Z);let Q=lJ(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),H=Array.from(new Set([...j,...X]));return{prompt:Q,userImages:f.userImages,userFiles:H.length>0?H:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=J1($.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:f,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($,f){let J=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(dJ($))return;let J=f==="aborted"||$.aborting,W=f==="error";await this.shutdownSession($,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)r2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});_5($);let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Of($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){W("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){W("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Of($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){W("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!W.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,W0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=W.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=W.endedAt??s(),$.endedAt=W0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(W){if(!bS(W,$.config.providerId))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(W){if(W instanceof Y9)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new k$($);throw Of(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>CS(W)?W:m7($,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return S$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=X0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let W=m7(f),Z=`${J}.messages.json`,Q;try{Q=SS($)}catch{return B0()}let j=B0();for(let X of Q){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let H=m7($,X);if(H===W)continue;let Y=await P1(H);if(Y.length===0)continue;j=X0(j,vf(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=xS(f.metadata?.aggregateUsage);if(J)return mS($,J);let W=f.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:B$({session:f,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($)),TK))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(TK)).find((W)=>W.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return LK(this.sessionService,$,...f)}invokeOptional($,...f){return zK(this.sessionService,$,...f)}invokeOptionalValue($,...f){return OK(this.sessionService,$,...f)}}function vS($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function uS($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function x5($={}){let f=new F$({sessionService:new U$(new G$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:gS(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:uS(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:vS(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}dS(process.env.CLINE_VCR);function lS($){let f=process.cwd(),J,W,Z;for(let Q=0;Q<$.length;Q+=1){let j=$[Q],X=$[Q+1];if(j==="--cwd"&&X){f=X,Q+=1;continue}if(j==="--host"&&X){J=X,Q+=1;continue}if(j==="--port"&&X){let H=Number(X);if(Number.isFinite(H))W=H;Q+=1;continue}if(j==="--pathname"&&X)Z=X,Q+=1}return{cwd:f,host:J,port:W,pathname:Z}}async function pS(){let $=lS(process.argv.slice(2));process.chdir($.cwd);let f=d0({host:$.host,port:$.port,pathname:$.pathname}),J=await Df({host:f.host,port:f.port,pathname:f.pathname,owner:Y0(),runtimeHandlers:x5(),cronOptions:{workspaceRoot:$.cwd}}),W=async()=>{await J.close(),process.exit(0)},Z=!1,Q=(j,X)=>{if(Z)return;Z=!0;let H=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] ${j}: ${H}
717
+ `,"utf8")}ensureDir(){if(!R7(this.dirPath))Lw(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(R7(this.statePath))_w(this.statePath)}}var ZK={};w(ZK,{ChatViewStateSchema:()=>L7,ChatSummarySchema:()=>XW,ChatSessionStatusSchema:()=>ZW,ChatSessionConfigSchema:()=>WW,ChatMessageSchema:()=>jW,ChatMessageRoleSchema:()=>QW});import{z as C}from"zod";var WW=C.object({workspaceRoot:C.string().min(1),cwd:C.string().optional(),provider:C.string().min(1),model:C.string().min(1),mode:C.enum(["act","plan"]).default("act"),apiKey:C.string(),systemPrompt:C.string().optional(),rules:C.string().optional(),maxIterations:C.number().int().positive().optional(),enableTools:C.boolean(),enableSpawn:C.boolean().optional(),enableTeams:C.boolean().optional(),autoApproveTools:C.boolean().optional(),missionStepInterval:C.number().int().positive().optional(),missionTimeIntervalMs:C.number().int().positive().optional()}),ZW=C.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),QW=C.enum(["user","assistant","tool","system","status","error"]),jW=C.object({id:C.string().min(1),sessionId:C.string().nullable(),role:QW,content:C.string(),createdAt:C.number().int().nonnegative(),meta:C.object({stream:C.enum(["stdout","stderr"]).optional(),toolName:C.string().optional(),iteration:C.number().int().nonnegative().optional(),agentId:C.string().optional(),conversationId:C.string().optional(),hookEventName:C.string().optional(),inputTokens:C.number().int().nonnegative().optional(),outputTokens:C.number().int().nonnegative().optional(),checkpoint:C.object({ref:C.string(),createdAt:C.number().int().nonnegative(),runCount:C.number().int().positive(),kind:C.enum(["stash","commit"]).optional()}).optional()}).optional()}),XW=C.object({toolCalls:C.number().int().nonnegative(),tokensIn:C.number().int().nonnegative(),tokensOut:C.number().int().nonnegative()}),L7=C.object({sessionId:C.string().nullable(),status:ZW,config:WW,messages:C.array(jW),rawTranscript:C.string(),error:C.string().nullable(),summary:XW});var QK={};w(QK,{CORE_BUILD_VERSION:()=>z7});var z7=jA;import{Agent as HS,createAgentRuntime as YS}from"@cline/agents";var XK={};w(XK,{fetchClineRecommendedModels:()=>O7,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>HW});import{getClineEnvironmentConfig as yw}from"@cline/shared";var qw=5000,HW={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"]}]};function ww($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function jK($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function Sw($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],W=Array.isArray(f.free)?f.free:[],Z=J.map(jK).filter((j)=>j!==null),Q=W.map(jK).filter((j)=>j!==null);if(Z.length===0&&Q.length===0)return null;return{recommended:Z,free:Q}}function hw($){let f=$.baseUrl?.trim();if(f)return f;let J=yw().apiBaseUrl;try{return($.providerSettingsManager??new R$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function Cw($,f,J){let W=new AbortController,Z=setTimeout(()=>W.abort(),J);try{return await $(f,{signal:W.signal})}finally{clearTimeout(Z)}}async function O7($={}){try{let f=hw($),J=$.fetchImpl??fetch,W=await Cw(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??qw);if(!W.ok)throw Error(`HTTP ${W.status}`);let Z=await W.json(),Q=Sw(Z);if(Q)return Q}catch{}return ww(HW)}var HK={};w(HK,{loadLlmsConfigFromFile:()=>T7,defineLlmsConfig:()=>_7});import{readFile as Ew}from"node:fs/promises";import bw from"node:path";function _7($){return $}async function T7($){let f=bw.resolve($),J=await Ew(f,"utf8"),W;try{W=JSON.parse(J)}catch(Z){let Q=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${Q}`)}return kw(W,f)}function kw($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let W=$.providers;if(!Array.isArray(W))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!W.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}var GK={};w(GK,{createLlmsSdk:()=>M7,DefaultLlmsSdk:()=>j4});import{BUILT_IN_PROVIDER_IDS as VK,createHandler as mw,createHandlerAsync as gw,getProviderCollection as vw,hasProvider as BK,registerAsyncHandler as uw,registerHandler as cw,registerModel as dw,registerProvider as KK}from"@cline/llms";function YK($){return $?{...$}:{}}function Iw($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function xw($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function AK($){let f=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:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class N7{providers=new Map;register($){xw($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...YK($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:Iw($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...YK($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.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($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class j4{configuredProviders=new N7;constructor($){this.applyConfig($)}createHandler($){return mw(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return gw(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(KK($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)cw($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)uw($.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 f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);KK({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){dw($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...VK]}async getBuiltInProviders(){return(await Promise.all(VK.map((f)=>vw(f)))).filter((f)=>f!==void 0).map((f)=>AK({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=BK(f.id),W=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof W==="string"&&BK(W);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function M7($){return new j4($)}GQ();async function lw(){return Promise.resolve().then(() => (IQ(),UB))}function GS(){return new Date().toISOString()}function PS($){if(RK($)!=="providers.json")return;let f=q7($);if(RK(f)!=="settings")return;return q7(f)}class R${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??KS(),this.dataDir=$.dataDir??PS(this.filePath),this.dataDir||!$.filePath)Q4({providerSettingsManager:this,dataDir:this.dataDir});if(dB(this),i5(this.read()),y7(this.filePath))try{FK(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!y7(this.filePath))return Y1();try{let $=VS(this.filePath,"utf8"),f=JSON.parse($),J=Z2.safeParse(f);if(J.success)return i5(J.data),J.data}catch{}return Y1()}write($){let f=Z2.parse($),J=q7(this.filePath);if(!y7(J))AS(J,{recursive:!0,mode:448});BS(this.filePath,`${JSON.stringify(f,null,2)}
718
+ `,"utf8");try{FK(this.filePath,384)}catch{}i5(f)}saveProviderSettings($,f={}){let J=i8.parse($),W=this.read(),Z=J.provider,Q=f.setLastUsed!==!1,j=W.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",H={...W,providers:{...W.providers,[Z]:{settings:J,updatedAt:GS(),tokenSource:X}},lastUsedProvider:Q?Z:W.lastUsedProvider};return this.write(H),H}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return m0(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return m0(f,$)}async refreshCatalog(){try{await J2({})}catch{}}}L0();z5();import{getClineEnvironmentConfig as US,isOAuthProviderId as FS}from"@cline/shared";var w7="workos:";function RS($,f){if($==="cline")return`${w7}${f}`;return f}function DS($,f){if($==="cline"&&f.toLowerCase().startsWith(w7))return f.slice(w7.length);return f}function LS($){let J=z0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function zS($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let W=LS(f);if(W)return W;return Date.now()-1}function OS($,f){let J=f.auth?.accessToken?.trim(),W=f.auth?.refreshToken?.trim();if(!J||!W)return null;let Z=DS($,J);if(!Z)return null;return{access:Z,refresh:W,expires:zS(f,Z),accountId:f.auth?.accountId}}function _S($,f){let J=$?.expiresAt,W=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===W}class YW 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 S7{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new R$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!FS($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let W=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,W),W}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let W=OS($,J);if(!W)return null;let Z=await this.resolveCredentials($,J,W,f);if(!Z)throw new YW($);let Q=RS($,Z.access),j={...J.auth??{},accessToken:Q,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let X={...J,auth:j},H=!_S(J.auth,X.auth);if(H)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:Q,accountId:Z.accountId,refreshed:H}}async resolveCredentials($,f,J,W){if($==="cline")return fJ(J,{apiBaseUrl:f.baseUrl?.trim()||US().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:W});if($==="oca")return u8(J,{forceRefresh:W,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return WJ(J,{forceRefresh:W,telemetry:this.telemetry})}}import{normalizeUserInput as TS}from"@cline/shared";import{nanoid as NS}from"nanoid";class DK{list($){return $?n0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((H)=>H.id===J);if(W<0)return{sessionId:f.sessionId,prompts:n0($),updated:!1};let Z=$.pendingPrompts[W];if(!Z)return{sessionId:f.sessionId,prompts:n0($),updated:!1};let Q=f.prompt===void 0?Z.prompt:TS(f.prompt).trim();if(!Q)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:Q,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(W,1),MS($,X,W,Z.delivery),{sessionId:f.sessionId,prompts:n0($),prompt:AW(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),W=$.pendingPrompts.findIndex((Q)=>Q.id===J);if(W<0)return{sessionId:f.sessionId,prompts:n0($),removed:!1};let[Z]=$.pendingPrompts.splice(W,1);return{sessionId:f.sessionId,prompts:n0($),prompt:Z?AW(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j}=f,X=$.pendingPrompts.findIndex((H)=>H.prompt===J);if(X>=0){let[H]=$.pendingPrompts.splice(X,1),Y={...H,prompt:J,mode:W??H.mode,userImages:Q??H.userImages,userFiles:j??H.userFiles};if(Z==="steer"||H.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let H={id:`pending_${Date.now()}_${NS(5)}`,prompt:J,mode:W,delivery:Z,userImages:Q,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(H);else $.pendingPrompts.push(H)}return n0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((W)=>W.delivery==="steer");if(f<0)return{prompts:n0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:n0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:n0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),n0($)}clear($){return $.pendingPrompts.length=0,[]}}class h7{deps;service=new DK;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:n0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let W=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{W=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,W&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=AW(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function AW($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function n0($){return $.pendingPrompts.map(AW)}function MS($,f,J,W){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(W==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}L0();class E7{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let W=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:W,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},Q=fZ(J),j=!!W&&(!Q.agentId||Q.agentId===C7(W.agent));JZ(Z,J,j?{isPrimaryAgentEvent:!0,agentId:C7(W.agent),conversationId:W.agent.getConversationId(),...W?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(e9(J,f),f.type==="agent_event"){let W={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};JZ(W,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let W=S$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:C7(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(W)r$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...W})}}if(await $Q($,f,this.deps.invokeBackendOptional),J)fQ(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let H=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!H)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await H.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let W=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof W?.sessionId==="string"&&W.sessionId.trim().length>0?W.sessionId.trim():$,Q=typeof W?.prompt==="string"?W.prompt.trim():"";if(!Q)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":W?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:Q,delivery:j})}handlePluginLog($,f,J){let W=this.deps.getSession($),Z=J??W?.config.extensionContext?.logger??W?.config.logger;if(!Z||!f||typeof f!=="object")return;let Q=f,j=typeof Q.message==="string"?Q.message:"";if(!j)return;let X=Q.metadata&&typeof Q.metadata==="object"?{...Q.metadata}:{};if(X.sessionId??=$,typeof Q.pluginName==="string"&&Q.pluginName)X.pluginName=Q.pluginName;if(Q.level==="debug"){Z.debug(j,X);return}if(Q.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function C7($){return $.getAgentId()}function b7($){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:J1($.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 k7($,f){let J=$[f];return typeof J==="function"?J:null}async function LK($,f,...J){let W=k7($,f);if(!W)throw Error(`session service method not available: ${f}`);return Promise.resolve(W.apply($,J))}async function zK($,f,...J){let W=k7($,f);if(!W)return;await Promise.resolve(W.apply($,J))}async function OK($,f,...J){let W=k7($,f);if(!W)return;return await Promise.resolve(W.apply($,J))}X$();L0();function I7($,f,J,W){return $1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let Q=f.enableTools?x1({cwd:f.cwd,...I0[q$({mode:f.mode})],executors:W}):[];if(f.enableSpawnAgent)Q.push(I7($,f,J,W));return c1(Q)},onSubAgentEvent:(Q)=>$.onAgentEvent(J,f,Q),onSubAgentStart:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(Q.subAgentId,{startedAt:Date.now(),rootSessionId:J});let X=S$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId});if(X)r$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...X});n2(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:Q.parentAgentId,agentId:Q.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",J,Q)},onSubAgentEnd:(Q)=>{let j=$.getSession(J)?.runtime.teamRuntime,X=$.subAgentStarts.get(Q.subAgentId),H=X?Date.now()-X.startedAt:0,Y=Q.result?.text?Q.result.text.split(`
719
+ `).length:0;n2(f.telemetry,{event:"ended",ulid:J,durationMs:H,outputLines:Y,errorMessage:Q.error?String(Q.error):void 0,agentId:Q.subAgentId,parentId:Q.parentAgentId,...S$({agentId:Q.subAgentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:Q.parentAgentId})}),$.subAgentStarts.delete(Q.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,Q)}})}import{readFile as yS,stat as qS}from"node:fs/promises";var wS=20480000;async function _K($){let f=await qS($);if(!f.isFile())throw Error("Path is not a file");if(f.size>wS)throw Error("File is too large to read into context.");let J=await yS($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var TK=5000;function X4($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function xS($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=X4(f.inputTokens),W=X4(f.outputTokens),Z=X4(f.cacheReadTokens),Q=X4(f.cacheWriteTokens),j=X4(f.totalCost);if(J===void 0||W===void 0||Z===void 0||Q===void 0||j===void 0)return;return{inputTokens:J,outputTokens:W,cacheReadTokens:Z,cacheWriteTokens:Q,totalCost:j}}function mS($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class F${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new CJ;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new O1;constructor($){let f=hS();if(f)IS(f);let J=Kf($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new v2,this.createAgentInstance=$.createAgent??((W)=>new e$(W)),this.defaultCapabilities=F0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new R$,this.oauthTokenManager=$.oauthTokenManager??new S7({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new h7({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 E7({getSession:(W)=>this.sessions.get(W),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(W)=>this.emit(W),persistMessages:(W,Z,Q)=>{this.invoke("persistSessionMessages",W,Z,Q)},enqueuePendingPrompt:(W,Z)=>this.pendingPromptsController.enqueue(W,Z),invokeBackendOptional:(W,...Z)=>this.invokeOptional(W,...Z)})}async startSession($){let f=$.source??G0.CLI,J=s(),W=$.config.sessionId?.trim()??"",Z=W||ES(),Q=$,j=Q.initialMessages??[],X=j.length>0?vf(j):B0(),H=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!H)throw Error("session service method not available: ensureSessionsDir");let Y=x7(H,Z),A=x7(Y,`${Z}.messages.json`),V=x7(Y,`${Z}.json`),B=J1($.config),K=y0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:Q.config.providerId,model:Q.config.modelId,cwd:Q.config.cwd,workspace_root:B,team_name:Q.config.teamName,enable_tools:Q.config.enableTools,enable_spawn:Q.config.enableSpawnAgent,enable_teams:Q.config.enableAgentTeams,prompt:Q.prompt?.trim()||void 0,messages_path:A}),G;if(W.length>0&&j.length>0&&!Q.prompt?.trim()){let k=await this.invokeOptionalValue("readSessionManifest",Z);if(k)K=k,G={manifestPath:V,messagesPath:k.messages_path||A,manifest:k}}let P=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:Y,rootMessagesPath:G?.messagesPath??A,manifest:K});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,P);let U=F0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,_=O?.extensionContext?.logger??O?.logger,D=O?.extensionContext?.automation,z;z=await RH({input:Q,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(k)=>{if(k.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,k.payload,_);return}this.eventBridge.handlePluginEvent(Z,k,D)},onTeamEvent:(k)=>{this.eventBridge.handleTeamEvent(Z,k),z.config.onTeamEvent?.(k)},createSpawnTool:()=>I7({getSession:(k)=>this.sessions.get(k),subAgentStarts:this.subAgentStarts,onAgentEvent:(k,D0,n)=>this.eventBridge.dispatchAgentEvent(k,D0,n),invokeBackendOptional:(k,...D0)=>this.invokeOptional(k,...D0)},z.config,Z,F),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(k)=>{await this.persistSessionMetadata(Z,()=>k)}});let N=await this.runtimeBuilder.build(z.runtimeBuilderInput),q=z.config,$0=z.providerConfig;if(N.teamRuntime&&!q.teamName?.trim())q.teamName=N.teamRuntime.getTeamName();let A0=[...N.tools,...q.extraTools??[]],o=N.extensions??z.extensions,V0={sessionId:Z,providerId:$0.providerId,modelId:$0.modelId,apiKey:$0.apiKey,baseUrl:$0.baseUrl,headers:$0.headers,knownModels:$0.knownModels,providerConfig:$0,thinking:q.thinking,reasoningEffort:q.reasoningEffort??$0.reasoningEffort,systemPrompt:q.systemPrompt,maxIterations:q.maxIterations,execution:q.execution,prepareTurn:$8(q),tools:A0,hooks:z.hooks,extensions:o,hookErrorMode:q.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:_K,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(k)=>{let D0=z.requestToolApproval,n=this.sessions.get(Z);if(n)await this.markTurnPending(n);try{if(!D0)return{approved:!1,reason:"Tool approval callback is not configured."};return await D0(k)}finally{let t0=this.sessions.get(Z);if(t0?.status==="pending")await this.markTurnRunning(t0)}}:void 0,telemetry:q.telemetry,onConsecutiveMistakeLimitReached:q.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let k=this.pendingPromptsController.consumeSteer(Z);return k?lJ(k.prompt,k.mode??q.mode):void 0},logger:N.logger??q.logger,extensionContext:q.extensionContext,onEvent:(k)=>this.eventBridge.dispatchAgentEvent(Z,q,k)};V0.hooks={...V0.hooks,onEvent:async(k)=>{if(await z.hooks?.onEvent?.(k),k.type!=="assistant-message")return;let D0=this.sessions.get(Z);if(!D0)return;let n=D0.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,n,q.systemPrompt)}catch(t0){q.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:t0}),Of(q.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:t0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:q.providerId,modelId:q.modelId}})}}};let i=this.createAgentInstance(V0);if(V0.onEvent)i.subscribeEvents(V0.onEvent);N.registerLeadAgent?.(i);let W$=S$({agentId:i.getAgentId(),conversationId:i.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(LH(q,Z,W.length>0,B,W$),W$)r$(q.telemetry,{ulid:Z,modelId:q.modelId,provider:q.providerId,...W$});if(N.teamRuntime)O4(q.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:i.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let p={sessionId:Z,config:q,sessionMetadata:Q.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:N,agent:i,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,p),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(p),await this.invoke("persistSessionMessages",p.sessionId,j,p.config.systemPrompt),!Q.prompt?.trim())await this.updateStatus(p,"completed",0)}let a0;try{if(Q.prompt?.trim())if(a0=await this.executeTurn(p,{prompt:Q.prompt,userImages:Q.userImages,userFiles:Q.userFiles}),!p.interactive)await this.finalizeSingleRun(p,a0.finishReason);else await this.completeInteractiveTurn(p,a0.finishReason)}catch(k){if(p.interactive&&p.aborting)a0=await this.completeAbortedInteractiveTurn(p);else throw Of(p.config.telemetry,{component:"core",operation:"session.start",error:k,severity:"error",handled:!1,context:{sessionId:p.sessionId,providerId:p.config.providerId,modelId:p.config.modelId}}),await this.failSession(p),k}return{sessionId:Z,manifest:K,manifestPath:V,messagesPath:A,result:a0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let W=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...W?{sessionMetadata:W}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),W=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.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 Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw Of(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=q9(this.usageBySession.get($)),J=q9(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!W0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!W0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return b7(f);let J=$.trim();if(!J)return;let W=await this.getRow(J);if(W)return T8(W);let Z=await this.readManifest(J);return Z?A5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(T8),W=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(W.has(Z.sessionId))continue;J.unshift(b7(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return P1(J.messagesPath);let W=await this.readManifest(f);return P1(W?.messages_path)}async dispatchHookEvent($){await oY($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),W=J.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 Z=await this.executeAgentTurn($,W,J.userImages,J.userFiles);while(JQ($,Z.finishReason)){let Q=await WQ($);if(Q.length===0)break;let j=ZQ($,Q);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(dJ($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),W=B0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:W}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:W,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,W){let Z=$.started||$.agent.getMessages().length>0,Q=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??B0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=B0(),$.turnUsageByAgent=new Map,P4($.config.telemetry,$.sessionId,$.config.mode),Nf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let H=Z?()=>$.agent.continue(f,J,W):()=>$.agent.run(f,J,W),Y=await this.runWithAuthRetry($,H,Q);$.started=!0;let A=c4(Y.messages,Y,Q);$.persistedMessages=A;let V=M8($.turnUsageByAgent?.values()??[]),B=X0(j,Y.usage),K=X0(X0(B0(),Y.usage),V),G=X0(X,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,A,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(H){throw Of($.config.telemetry,{component:"core",operation:"session.turn",error:H,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),H}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((W)=>W.name===J0.SUBMIT_AND_EXIT&&W.error===void 0))return;$.submitAndExitObserved=!0,r2($.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($,f){let J=J1($.config),W=kS(f.prompt).trim();if(!W)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await qf(W,J);zH($.config.telemetry,Z);let Q=lJ(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),H=Array.from(new Set([...j,...X]));return{prompt:Q,userImages:f.userImages,userFiles:H.length>0?H:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=J1($.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:f,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($,f){let J=this.sessions.get($),W=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(W?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(dJ($))return;let J=f==="aborted"||$.aborting,W=f==="error";await this.shutdownSession($,{status:J?"cancelled":W?"failed":"completed",exitCode:W?1:0,shutdownReason:W?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)r2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});_5($);let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Of($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){W("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){W("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],W=(Z,Q)=>{J.push(Q),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:Q,severity:"warn"}),Of($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:Q,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){W("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){W("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){W("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let W=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!W.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,W0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=W.endedAt??s(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=W.endedAt??s(),$.endedAt=W0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(W){if(!bS(W,$.config.providerId))throw W;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(W){if(W instanceof YW)throw Error(`${W.providerId} requires re-authentication.`);throw W}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=new k$($);throw Of(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((W)=>W.trim()).filter((W)=>W.length>0).map((W)=>CS(W)?W:m7($,W));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return S$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=X0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let W=m7(f),Z=`${J}.messages.json`,Q;try{Q=SS($)}catch{return B0()}let j=B0();for(let X of Q){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let H=m7($,X);if(H===W)continue;let Y=await P1(H);if(Y.length===0)continue;j=X0(j,vf(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=xS(f.metadata?.aggregateUsage);if(J)return mS($,J);let W=f.metadata?.aggregatedAgentsCost;if(typeof W!=="number"||!Number.isFinite(W)||W<=$.totalCost)return $;return{...$,totalCost:W}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:B$({session:f,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($)),TK))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(TK)).find((W)=>W.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return LK(this.sessionService,$,...f)}invokeOptional($,...f){return zK(this.sessionService,$,...f)}invokeOptionalValue($,...f){return OK(this.sessionService,$,...f)}}function vS($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function uS($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function x5($={}){let f=new F$({sessionService:new U$(new G$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let W=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:gS(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:W,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:uS(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,W){let Z=await f.runTurn({sessionId:J,prompt:W.prompt,userImages:W.attachments?.userImages,userFiles:W.attachments?.userFiles?.map((Q)=>Q.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:vS(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}dS(process.env.CLINE_VCR);function lS($){let f=process.cwd(),J,W,Z;for(let Q=0;Q<$.length;Q+=1){let j=$[Q],X=$[Q+1];if(j==="--cwd"&&X){f=X,Q+=1;continue}if(j==="--host"&&X){J=X,Q+=1;continue}if(j==="--port"&&X){let H=Number(X);if(Number.isFinite(H))W=H;Q+=1;continue}if(j==="--pathname"&&X)Z=X,Q+=1}return{cwd:f,host:J,port:W,pathname:Z}}async function pS(){let $=lS(process.argv.slice(2));process.chdir($.cwd);let f=d0({host:$.host,port:$.port,pathname:$.pathname}),J=await Df({host:f.host,port:f.port,pathname:f.pathname,owner:Y0(),runtimeHandlers:x5(),cronOptions:{workspaceRoot:$.cwd}}),W=async()=>{await J.close(),process.exit(0)},Z=!1,Q=(j,X)=>{if(Z)return;Z=!0;let H=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] ${j}: ${H}
720
720
  `),J.close().catch((Y)=>{let A=Y instanceof Error?Y.stack||Y.message:String(Y);process.stderr.write(`[hub-daemon] shutdown after ${j} failed: ${A}
721
721
  `)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{W()}),process.on("SIGTERM",()=>{W()}),process.on("uncaughtException",(j)=>{Q("uncaughtException",j)}),process.on("unhandledRejection",(j)=>{if(j instanceof cS){process.stderr.write(`[hub-daemon] ignored agent runtime abort rejection: ${j.message}
722
722
  `);return}Q("unhandledRejection",j)}),await new Promise(()=>{})}pS().catch(($)=>{let f=$ instanceof Error?$.stack||$.message:String($);process.stderr.write(`[hub-daemon] fatal: ${f}