@cline/core 0.0.48-nightly.1781666345 → 0.0.49

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,8 +1,8 @@
1
- import{createRequire as YF}from"node:module";var{defineProperty:t9,getOwnPropertyNames:jF}=Object;var cj=Object.prototype.hasOwnProperty;function uj($){return this[$]}var q=($,J,Q)=>{var Z=jF(J);for(let W of Z)if(!cj.call($,W)&&W!=="default")t9($,W,{get:uj.bind(J,W),enumerable:!0});if(Q){for(let W of Z)if(!cj.call(Q,W)&&W!=="default")t9(Q,W,{get:uj.bind(J,W),enumerable:!0});return Q}};var fF=($)=>$;function XF($,J){this[$]=fF.bind(null,J)}var w=($,J)=>{for(var Q in J)t9($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:XF.bind(J,Q)})};var h$=($,J)=>()=>($&&(J=$($=0)),J);var dj=YF(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as VF}from"@cline/shared";function r($,J,Q){$?.capture({event:J,properties:Q})}function EJ($){if(!$)return;return $.substring(0,HF)}function BF($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function AF($){return typeof $==="string"?$:$.message}function lj($,J){return $.some((Q)=>J.has(Q.trim().toLowerCase()))}function pj($){r($,x.CLIENT.EXTENSION_ACTIVATED)}function bJ($,J){let Q=[...J.vcs_types],Z={root_count:J.root_count,vcs_types:Q,is_multi_root:J.root_count>1,has_git:lj(Q,new Set(["git"])),has_mercurial:lj(Q,new Set(["mercurial","hg"]))};if(J.init_duration_ms!==void 0)Z.init_duration_ms=J.init_duration_ms;if(J.feature_flag_enabled!==void 0)Z.feature_flag_enabled=J.feature_flag_enabled;if(J.is_remote_workspace!==void 0)Z.is_remote_workspace=J.is_remote_workspace;r($,x.WORKSPACE.INITIALIZED,Z)}function hJ($,J,Q){r($,x.WORKSPACE.INIT_ERROR,{error_type:BF(J),error_message:EJ(AF(J)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function rj($,J){r($,x.WORKSPACE.PATH_RESOLVED,{...J})}function P1($,J){r($,x.USER.AUTH_STARTED,{provider:J})}function N1($,J){r($,x.USER.AUTH_SUCCEEDED,{provider:J})}function w1($,J,Q){r($,x.USER.AUTH_FAILED,{provider:J,errorMessage:EJ(Q)})}function e1($,J,Q){r($,x.USER.AUTH_LOGGED_OUT,{provider:J,reason:Q})}function ij($,J){r($,x.USER.PROVIDER_CONFIGURED,{provider:J})}function nj($,J){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,J)}function S1($,J){let Q=J.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:J.id,account_email:J.email,provider:J.provider,organization_id:J.organizationId,organization_name:J.organizationName,member_id:J.memberId})}function kJ($,J){r($,x.TASK.CREATED,J)}function IJ($,J){r($,x.TASK.RESTARTED,J)}function V4($,J){r($,x.TASK.COMPLETED,J)}function g2($,J){r($,x.TASK.CONVERSATION_TURN,{...J,timestamp:new Date().toISOString()})}function xJ($,J){r($,x.TASK.TOKEN_USAGE,J)}function gJ($,J,Q){r($,x.TASK.MODE_SWITCH,{ulid:J,mode:Q})}function mJ($,J){r($,x.TASK.TOOL_USED,J)}function vJ($,J){r($,x.TASK.SKILL_USED,J)}function cJ($,J){r($,x.TASK.DIFF_EDIT_FAILED,J)}function H4($,J){r($,x.TASK.PROVIDER_API_ERROR,{...J,errorMessage:EJ(J.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function aj($,J){r($,x.SDK.TOOL_TIMEOUT,KF(J))}function KF($){let J={};for(let[Q,Z]of Object.entries($))if(Z!==void 0)J[Q]=Z;return J}function uJ($,J,Q){r($,x.TASK.MENTION_USED,{mentionType:J,contentLength:Q,timestamp:new Date().toISOString()})}function dJ($,J,Q,Z){r($,x.TASK.MENTION_FAILED,{mentionType:J,errorType:Q,errorMessage:EJ(Z),timestamp:new Date().toISOString()})}function lJ($,J,Q,Z,W){r($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:J.length,resultCount:Q,searchType:Z,isEmpty:W,timestamp:new Date().toISOString()})}function $$($,J){r($,x.TASK.AGENT_CREATED,{...J,timestamp:new Date().toISOString()})}function pJ($,J){r($,x.TASK.AGENT_TEAM_CREATED,{...J,timestamp:new Date().toISOString()})}function B4($,J){r($,J.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...J,timestamp:new Date().toISOString()})}function rJ($,J,Q,Z){r($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:J,globalCount:Q,workspaceCount:Z,totalCount:Q+Z,timestamp:new Date().toISOString()})}function iJ($,J){r($,x.TASK.COMPACTION_EXECUTED,{...J,timestamp:new Date().toISOString()})}function nJ($,J){r($,x.TASK.COMPACTION_SKIPPED,{...J,timestamp:new Date().toISOString()})}var HF=500,x;var O0=h$(()=>{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:VF,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as NU,readFileSync as wU,statSync as SU,writeFileSync as CU}from"node:fs";import{dirname as yU}from"node:path";import{resolveGlobalSettingsPath as yX}from"@cline/shared/storage";import{z as e2}from"zod";function D5(){return l4.parse({})}function EU(){U5=void 0}function bU($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function hU($){let J;try{J=wU($,"utf8")}catch{return D5()}try{let Q=l4.safeParse(JSON.parse(J));return Q.success?Q.data:D5()}catch{return D5()}}function kU(){let $=yX(),J=SU($,{throwIfNoEntry:!1}),Q=J?.mtimeMs??0,Z=J?.size??0,W=U5;if(W&&W.path===$&&W.mtimeMs===Q&&W.size===Z)return W;let j=bU(J?hU($):D5());return U5={path:$,mtimeMs:Q,size:Z,value:j},U5}function M0(){return kU().value}function k1($,J={}){let Q=yX(),Z=M0();NU(yU(Q),{recursive:!0});let W=l4.parse($);if(!Z.telemetryOptOut&&W.telemetryOptOut)nj(J.telemetry);CU(Q,`${JSON.stringify(W,null,2)}
2
- `,"utf8"),EU()}function R5(){return M0().telemetryOptOut}function EX($,J={}){k1({...M0(),telemetryOptOut:$},J)}function bX(){return M0().autoUpdateEnabled}function hX($,J={}){k1({...M0(),autoUpdateEnabled:$},J)}function B1($){return new Set($??M0().disabledTools??[])}function p4($){return new Set($??M0().disabledPlugins??[])}function kX($){return B1().has($)}function z5($){let J=M0(),Q=new Set(J.disabledTools??[]),Z=Q.has($);if(Z)Q.delete($);else Q.add($);return k1({...J,disabledTools:[...Q]}),!Z}function IZ($,J){let Q=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Q.length===0)return;let Z=M0(),W=B1(Z.disabledTools);for(let j of Q)if(J)W.add(j);else W.delete(j);k1({...Z,disabledTools:[...W]})}function IX($,J){return IZ([$],J),J}function xX($){return p4().has($)}function gX($,J){let Q=$.trim();if(!Q)return;let Z=M0(),W=p4(Z.disabledPlugins);if(J)W.add(Q);else W.delete(Q);k1({...Z,disabledPlugins:[...W]})}function L5($,J){let Q=p4(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z))}function I1($,J){let Q=B1(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z.name))}function _5($,J){if(!$||$.length===0)return $;let Q=B1(J);if(Q.size===0)return $;return $.map((Z)=>{if(!Z.setup)return Z;return{...Z,setup:(W,j)=>Z.setup?.({...W,registerTool:(f)=>{if(!Q.has(f.name))W.registerTool(f)}},j)}})}var CX,l4,U5;var W1=h$(()=>{O0();CX=e2.preprocess(($)=>Array.isArray($)?$.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):void 0,e2.array(e2.string()).optional()).transform(($)=>{if(!$)return;let J=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z));return J.length>0?J:void 0}),l4=e2.object({telemetryOptOut:e2.boolean().default(!1).catch(!1),autoUpdateEnabled:e2.boolean().default(!0).catch(!0),disabledTools:CX.optional(),disabledPlugins:CX.optional()}).strip().transform(($)=>{let J={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)J.disabledTools=$.disabledTools;if($.disabledPlugins?.length)J.disabledPlugins=$.disabledPlugins;return J})});var oX={};w(oX,{normalizeUserMessage:()=>NR,buildInitialUserContent:()=>PR});async function PR($,J,Q,Z){let W=wR(J),j=await CR(Q,Z);if(W.length===0&&!j)return $;let f=[{type:"text",text:$},...W];if(j)f.push(...j);return f}function NR($){if($==null)return"";if(typeof $==="string")return $;let J=$.content;if(typeof J==="string")return J;if(!Array.isArray(J))return"";let Q=[];for(let Z of J)if(Z&&typeof Z==="object"&&Z.type==="text"){let W=Z.text;if(typeof W==="string")Q.push(W)}return Q.join(`
3
- `)}function wR($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let Z=SR(Q);if(Z)J.push(Z)}return J}function SR($){let J=$.trim();if(!J)return;let Q=J.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let Z=Q[1],W=Q[2];if(!Z||!W)return;return{type:"image",mediaType:Z,data:W}}return{type:"image",mediaType:"image/png",data:J}}async function CR($,J){if(!$||$.length===0)return;let Q=J??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Z=await Promise.all($.map(async(W)=>{let j=W.replace(/\\/g,"/");try{let f=await Q(W);return{type:"file",path:j,content:f}}catch(f){let X=f instanceof Error?f.message:String(f);return{type:"file",path:j,content:`Error fetching content: ${X}`}}}));if(Z.length===0)return;return Z}var RH={};w(RH,{updateMcpServerOAuthState:()=>H2,setMcpServerDisabled:()=>Y2,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>B0,registerMcpServersFromSettingsFile:()=>B2,normalizeMcpServerOAuthState:()=>w8,loadMcpSettingsFile:()=>X2,listMcpServerOAuthStatuses:()=>g6,hasMcpSettingsFile:()=>c1,getMcpServerOAuthState:()=>V2});import{existsSync as wO,mkdirSync as AH,readFileSync as a7,writeFileSync as KH}from"node:fs";import{dirname as GH}from"node:path";import{resolveMcpSettingsPath as SO}from"@cline/shared/storage";import{z as y}from"zod";function n7($){if(!$)return;if($==="http")return"streamableHttp";return $}function B0(){return SO()}function vO($){let J=a7($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${$}": ${W}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function UH($,J){if(!Object.hasOwn($,J))return;let Q=$[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function cO($,J,Q){Object.defineProperty($,J,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function X2($={}){let J=$.filePath??B0(),Q=a7(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${J}": ${f}`)}let W=mO.safeParse(Z);if(!W.success){let j=W.error.issues.map((f)=>{let X=f.path.join(".");return X?`${X}: ${f.message}`:f.message}).join("; ");throw Error(`Invalid MCP settings at "${J}": ${j}`)}return W.data}function uO($){let J=a7($,"utf8"),Q;try{Q=JSON.parse(J)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${$}": ${f}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object`);let Z=Q,W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Z}function w8($){if(!$)return;let J={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(J).length>0?J:void 0}function dO($){if($===void 0)return;let J=s7.safeParse($);if(!J.success)return;return w8(J.data)}function c1($={}){let J=$.filePath??B0();return wO(J)}function A1($={}){let J=X2($);return Object.entries(J.mcpServers).map(([Q,Z])=>({name:Q,transport:Z.transport,disabled:Z.disabled,metadata:Z.metadata,oauth:Z.oauth}))}function Y2($){let J=$.filePath??B0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");let Z=vO(J),W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${J}": mcpServers must be an object.`);let j={...W},f=UH(j,Q);if(!f)throw Error(`Unknown MCP server: ${Q}`);let X={...f};if($.disabled)X.disabled=!0;else delete X.disabled;cO(j,Q,X),AH(GH(J),{recursive:!0}),KH(J,`${JSON.stringify({...Z,mcpServers:j},null,2)}
4
- `)}function V2($,J={}){let Q=X2(J);if(!Object.hasOwn(Q.mcpServers,$))return;return w8(Q.mcpServers[$]?.oauth)}function H2($,J,Q={}){let Z=Q.filePath??B0(),W=uO(Z),j=W.mcpServers,f=UH(j,$);if(!f)throw Error(`Unknown MCP server: ${$}`);let X=dO(f.oauth)??{},Y=w8(J(X));if(Y)f.oauth=Y;else delete f.oauth;return AH(GH(Z),{recursive:!0}),KH(Z,`${JSON.stringify(W,null,2)}
5
- `,"utf8"),Y??{}}function g6($={}){return A1($).map((Q)=>{let Z=Q.transport.type!=="stdio",W=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:Z,oauthConfigured:Z&&typeof W==="string"&&W.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,Z)=>Q.serverName.localeCompare(Z.serverName))}async function B2($,J={}){let Q=A1(J);for(let Z of Q)await $.registerServer(Z);return Q}var x6,FH,s7,CO,yO,EO,bO,hO,kO,DH,IO,xO,gO,mO;var qQ=h$(()=>{x6=y.record(y.string(),y.string()),FH=y.record(y.string(),y.unknown()),s7=y.object({clientInformation:y.record(y.string(),y.unknown()).optional(),tokens:y.record(y.string(),y.unknown()).optional(),codeVerifier:y.string().optional(),discoveryState:y.record(y.string(),y.unknown()).optional(),redirectUrl:y.string().url().optional(),lastError:y.string().optional(),lastAuthenticatedAt:y.number().int().positive().optional()}).strip(),CO=y.object({type:y.literal("stdio"),command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:x6.optional()}),yO=y.object({type:y.literal("sse"),url:y.string().url(),headers:x6.optional()}),EO=y.object({type:y.literal("streamableHttp"),url:y.string().url(),headers:x6.optional()}),bO=y.discriminatedUnion("type",[CO,yO,EO]),hO=y.object({transport:bO,disabled:y.boolean().optional(),metadata:FH.optional(),oauth:s7.optional()}),kO=y.enum(["stdio","sse","http","streamableHttp"]).optional(),DH=y.object({type:y.enum(["stdio","sse","streamableHttp"]).optional(),transportType:kO,disabled:y.boolean().optional(),metadata:FH.optional(),oauth:s7.optional()});IO=DH.extend({command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:x6.optional()}).superRefine(($,J)=>{let Q=$.type??n7($.transportType);if(Q&&Q!=="stdio")J.addIssue({code:y.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})),xO=DH.extend({url:y.string().url(),headers:x6.optional()}).superRefine(($,J)=>{let Q=$.type??n7($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")J.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??n7($.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}}),gO=y.union([hO,IO,xO]),mO=y.object({mcpServers:y.record(y.string(),gO)}).passthrough()});import{existsSync as aP,mkdirSync as sP,readFileSync as oP,writeFileSync as tP}from"node:fs";import{resolve as eP}from"node:path";import{resolveSessionDataDir as $N}from"@cline/shared/storage";import{nanoid as JN}from"nanoid";import*as QN from"node-machine-id";function b0($){let J=$?.trim();if(J)return J;let Q=jN();if(Q)return Q;return fN()}function WN(){let $=QN;return $.machineIdSync??$.default?.machineIdSync}function jN(){try{let $=WN();if(!$)return;return $().trim()||void 0}catch{return}}function fN(){let $=$N(),J=eP($,ZN);try{if(aP(J)){let Z=oP(J,"utf8").trim();if(Z.length>0)return Z}}catch{}let Q=`cl-${JN()}`;try{sP($,{recursive:!0}),tP(J,Q,"utf8")}catch{}return Q}var ZN="machine-id";var g8=()=>{};class GJ{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($,J){if(!this.isEnabled())return;this.emitLog($,J,!1)}emitRequired($,J){this.emitLog($,J,!0)}recordCounter($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Z?{description:Z}:void 0),this.counters.set($,j);j.add(J,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Z?{description:Z}:void 0),this.histograms.set($,j);j.record(J,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.buildAttributes(Q),f=JSON.stringify(j),X=this.gaugeValues.get($);if(J===null){if(X){if(X.delete(f),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Z?{description:Z}:void 0);V.addCallback((H)=>{for(let B of this.snapshotGaugeSeries($))H.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set($,V)}Y.set(f,{value:J,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,J,Q){if(!this.logger)return;let Z=this.flattenProperties(this.buildAttributes(J,Q));this.logger.emit({severityText:"INFO",body:$,attributes:Z})}buildAttributes($,J=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...J?{_required:!0}:{}}}snapshotGaugeSeries($){let J=this.gaugeValues.get($);if(!J)return[];return Array.from(J.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,J="",Q=new WeakSet,Z=0){if(!$)return{};let W={},j=100,f=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=J?`${J}.${X}`:X;if(Y===null||Y===void 0){W[V]=String(Y);continue}if(Array.isArray(Y)){let H=Y.length>j?Y.slice(0,j):Y;try{W[V]=JSON.stringify(H)}catch{W[V]="[UnserializableArray]"}if(Y.length>j)W[`${V}_truncated`]=!0,W[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){W[V]=Y.toISOString();continue}if(Y instanceof Error){W[V]=Y.message;continue}if(Q.has(Y)){W[V]="[Circular]";continue}if(Z>=f){W[V]="[MaxDepthExceeded]";continue}Q.add(Y),Object.assign(W,this.flattenProperties(Y,V,Q,Z+1));continue}if(Ow(Y)){W[V]=Y;continue}try{W[V]=JSON.stringify(Y)}catch{W[V]=String(Y)}}return W}}function Ow($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class FJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,J){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:J})}emitRequired($,J){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:J})}recordCounter($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordHistogram($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordGauge($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:J,attributes:Q,description:Z,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class o8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new FJ({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 J=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,J)}captureRequired($,J){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.emitRequired($,Q)}recordCounter($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordCounter($,J,j,Z,W)}recordHistogram($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordHistogram($,J,j,Z,W)}recordGauge($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordGauge($,J,j,Z,W)}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 X3=()=>{};import{metrics as Tw,trace as Mw}from"@opentelemetry/api";import{logs as qw}from"@opentelemetry/api-logs";import{OTLPLogExporter as Pw}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as Nw}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as ww}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as Sw}from"@opentelemetry/resources";import{BatchLogRecordProcessor as Cw,ConsoleLogRecordExporter as yw,LoggerProvider as Ew}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as bw,MeterProvider as hw,PeriodicExportingMetricReader as gA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as kw,ConsoleSpanExporter as Iw,SimpleSpanProcessor as xw}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as gw}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as mw,ATTR_SERVICE_VERSION as vw}from"@opentelemetry/semantic-conventions";class mA{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($,J){this.resolveProperties(J)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class t8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let J=Sw({[mw]:$.serviceName??"cline",...$.serviceVersion?{[vw]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(J),this.loggerProvider=this.createLoggerProvider(J),this.tracerProvider=this.createTracerProvider(J),this.meterProvider)Tw.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)qw.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",J){return Mw.getTracer($,J??this.options.serviceVersion)}createAdapter($){return new GJ({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let J=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new o8({...$,adapters:[J],distinctId:b0($.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 J=Y3(this.options.metricsExporter);if(J.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Z=Math.min(30000,Math.floor(Q*0.8)),W=J.map((j)=>dw(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:Z})).filter((j)=>j!==null);if(W.length===0)return null;return new hw({resource:$,readers:W})}createTracerProvider($){let J=Y3(this.options.tracesExporter);if(J.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Z=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let j of J){let f=uw(j,{endpoint:Q,headers:Z,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(f)W.push(f)}if(W.length===0)return null;return new gw({resource:$,spanProcessors:W})}createLoggerProvider($){let J=Y3(this.options.logsExporter);if(J.length===0)return null;let Q=J.map((Z)=>{let W=cw(Z,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new Cw(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Z)=>Z!==null);if(Q.length===0)return null;return new Ew({resource:$,processors:Q})}}function DJ($){let J=new t8($),Q=J.createTelemetryService($);return Q.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:J,telemetry:Q}}function s1($){if(R5())return{telemetry:new mA($)};if($.enabled!==!0)return{telemetry:new o8({...$,distinctId:b0($.distinctId)})};return DJ($)}function e8($){let{telemetry:J,provider:Q}=s1($);return{telemetry:J,provider:Q,flush:async()=>{let j=Q;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([J.dispose(),Q?.dispose()])}}}function Y3($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function cw($,J){if($==="console")return new yw;if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/logs");return new Pw({url:Q,headers:J.headers})}function uw($,J){if($==="console")return new xw(new Iw);if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/traces");return new kw(new ww({url:Q,headers:J.headers}))}function dw($,J){if($==="console")return new gA({exporter:new bw,exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout});if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/metrics");return new gA({exporter:new Nw({url:Q,headers:J.headers}),exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout})}function V3($,J){let Q=new URL($),Z=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=Z.endsWith(J)?Z:`${Z}${J}`,Q.toString()}var Y9=h$(()=>{W1();g8();X3()});var rK={};w(rK,{resolveCoreDistinctId:()=>b0,createOpenTelemetryTelemetryService:()=>DJ,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,OpenTelemetryProvider:()=>t8,OpenTelemetryAdapter:()=>GJ});var R9=h$(()=>{g8();Y9()});import{AgentRuntimeAbortError as hb}from"@cline/agents";import{initVcr as kb,resolveClineBuildEnv as Ib}from"@cline/shared";import{normalizeProviderId as yb}from"@cline/llms";var nG={};w(nG,{LocalRuntimeHost:()=>L1});import{readdirSync as Ob}from"node:fs";import{homedir as Tb}from"node:os";import{isAbsolute as Mb,join as xj,resolve as gj}from"node:path";import{captureSdkError as h2,createSessionId as qb,isLikelyAuthError as Pb,normalizeUserInput as Nb}from"@cline/shared";import{setHomeDirIfUnset as wb}from"@cline/shared/storage";var Mf={};w(Mf,{saveProviderOAuthCredentials:()=>x$,resolveProviderApiKeyFromSettings:()=>HZ,loginAndSaveProviderOAuthCredentials:()=>z4,isOAuthProvider:()=>I$,getProviderOAuthCredentialsFromSettings:()=>L4,getProviderAuthStorageId:()=>VZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>l2,formatProviderOAuthApiKey:()=>BZ});import{getClineEnvironmentConfig as Of}from"@cline/shared";O0();var jf={};w(jf,{startClineDeviceAuth:()=>WZ,refreshClineToken:()=>tJ,loginClineOAuth:()=>A4,getValidClineCredentials:()=>K4,completeClineDeviceAuth:()=>jZ});import{getClineEnvironmentConfig as e9}from"@cline/shared";var sj={};w(sj,{startLocalOAuthServer:()=>J1});function GF(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function J1($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??FF,j=GF(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},B=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{B(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((D,U)=>{try{let F=new URL(D.url||"",`http://${Q}:${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}`),B(),H(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(W),B(),H(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((D)=>{let U=(F)=>{G.off("error",U),D({bound:!1,error:F})};G.once("error",U),G.listen(K,Q,()=>{G.off("error",U),Y=G,D({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw B(),R.error}if(R.bound){V=K;let D=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:D})).catch(()=>{});return{callbackUrl:D,waitForCallback:A,cancelWait:()=>{B(),H(null)},close:()=>{B(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var FF=`<!DOCTYPE html>
1
+ import{createRequire as YF}from"node:module";var{defineProperty:tQ,getOwnPropertyNames:jF}=Object;var vj=Object.prototype.hasOwnProperty;function cj($){return this[$]}var q=($,J,Q)=>{var Z=jF(J);for(let W of Z)if(!vj.call($,W)&&W!=="default")tQ($,W,{get:cj.bind(J,W),enumerable:!0});if(Q){for(let W of Z)if(!vj.call(Q,W)&&W!=="default")tQ(Q,W,{get:cj.bind(J,W),enumerable:!0});return Q}};var fF=($)=>$;function XF($,J){this[$]=fF.bind(null,J)}var w=($,J)=>{for(var Q in J)tQ($,Q,{get:J[Q],enumerable:!0,configurable:!0,set:XF.bind(J,Q)})};var h$=($,J)=>()=>($&&(J=$($=0)),J);var uj=YF(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as VF}from"@cline/shared";function r($,J,Q){$?.capture({event:J,properties:Q})}function EJ($){if(!$)return;return $.substring(0,HF)}function BF($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function AF($){return typeof $==="string"?$:$.message}function dj($,J){return $.some((Q)=>J.has(Q.trim().toLowerCase()))}function lj($){r($,x.CLIENT.EXTENSION_ACTIVATED)}function bJ($,J){let Q=[...J.vcs_types],Z={root_count:J.root_count,vcs_types:Q,is_multi_root:J.root_count>1,has_git:dj(Q,new Set(["git"])),has_mercurial:dj(Q,new Set(["mercurial","hg"]))};if(J.init_duration_ms!==void 0)Z.init_duration_ms=J.init_duration_ms;if(J.feature_flag_enabled!==void 0)Z.feature_flag_enabled=J.feature_flag_enabled;if(J.is_remote_workspace!==void 0)Z.is_remote_workspace=J.is_remote_workspace;r($,x.WORKSPACE.INITIALIZED,Z)}function hJ($,J,Q){r($,x.WORKSPACE.INIT_ERROR,{error_type:BF(J),error_message:EJ(AF(J)),fallback_to_single_root:Q.fallback_to_single_root,workspace_count:Q.workspace_count??0})}function pj($,J){r($,x.WORKSPACE.PATH_RESOLVED,{...J})}function P1($,J){r($,x.USER.AUTH_STARTED,{provider:J})}function N1($,J){r($,x.USER.AUTH_SUCCEEDED,{provider:J})}function w1($,J,Q){r($,x.USER.AUTH_FAILED,{provider:J,errorMessage:EJ(Q)})}function e1($,J,Q){r($,x.USER.AUTH_LOGGED_OUT,{provider:J,reason:Q})}function rj($,J){r($,x.USER.PROVIDER_CONFIGURED,{provider:J})}function ij($,J){$?.captureRequired(x.USER.TELEMETRY_OPT_OUT,J)}function S1($,J){let Q=J.id?.trim();if(Q)$?.setDistinctId(Q);$?.updateCommonProperties({account_id:J.id,account_email:J.email,provider:J.provider,organization_id:J.organizationId,organization_name:J.organizationName,member_id:J.memberId})}function kJ($,J){r($,x.TASK.CREATED,J)}function IJ($,J){r($,x.TASK.RESTARTED,J)}function V4($,J){r($,x.TASK.COMPLETED,J)}function g2($,J){r($,x.TASK.CONVERSATION_TURN,{...J,timestamp:new Date().toISOString()})}function xJ($,J){r($,x.TASK.TOKEN_USAGE,J)}function gJ($,J,Q){r($,x.TASK.MODE_SWITCH,{ulid:J,mode:Q})}function mJ($,J){r($,x.TASK.TOOL_USED,J)}function vJ($,J){r($,x.TASK.SKILL_USED,J)}function cJ($,J){r($,x.TASK.DIFF_EDIT_FAILED,J)}function H4($,J){r($,x.TASK.PROVIDER_API_ERROR,{...J,errorMessage:EJ(J.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function nj($,J){r($,x.SDK.TOOL_TIMEOUT,KF(J))}function KF($){let J={};for(let[Q,Z]of Object.entries($))if(Z!==void 0)J[Q]=Z;return J}function uJ($,J,Q){r($,x.TASK.MENTION_USED,{mentionType:J,contentLength:Q,timestamp:new Date().toISOString()})}function dJ($,J,Q,Z){r($,x.TASK.MENTION_FAILED,{mentionType:J,errorType:Q,errorMessage:EJ(Z),timestamp:new Date().toISOString()})}function lJ($,J,Q,Z,W){r($,x.TASK.MENTION_SEARCH_RESULTS,{queryLength:J.length,resultCount:Q,searchType:Z,isEmpty:W,timestamp:new Date().toISOString()})}function $$($,J){r($,x.TASK.AGENT_CREATED,{...J,timestamp:new Date().toISOString()})}function pJ($,J){r($,x.TASK.AGENT_TEAM_CREATED,{...J,timestamp:new Date().toISOString()})}function B4($,J){r($,J.event==="ended"?x.TASK.SUBAGENT_COMPLETED:x.TASK.SUBAGENT_STARTED,{...J,timestamp:new Date().toISOString()})}function rJ($,J,Q,Z){r($,x.HOOKS.DISCOVERY_COMPLETED,{hookName:J,globalCount:Q,workspaceCount:Z,totalCount:Q+Z,timestamp:new Date().toISOString()})}function iJ($,J){r($,x.TASK.COMPACTION_EXECUTED,{...J,timestamp:new Date().toISOString()})}function nJ($,J){r($,x.TASK.COMPACTION_SKIPPED,{...J,timestamp:new Date().toISOString()})}var HF=500,x;var O0=h$(()=>{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:VF,TOOL_TIMEOUT:"sdk.tool_timeout"},FEATURE_FLAGS:{FLAG_CALLED:"$feature_flag_called"}}});import{mkdirSync as NU,readFileSync as wU,statSync as SU,writeFileSync as CU}from"node:fs";import{dirname as yU}from"node:path";import{resolveGlobalSettingsPath as CX}from"@cline/shared/storage";import{z as e2}from"zod";function D5(){return l4.parse({})}function EU(){U5=void 0}function bU($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function hU($){let J;try{J=wU($,"utf8")}catch{return D5()}try{let Q=l4.safeParse(JSON.parse(J));return Q.success?Q.data:D5()}catch{return D5()}}function kU(){let $=CX(),J=SU($,{throwIfNoEntry:!1}),Q=J?.mtimeMs??0,Z=J?.size??0,W=U5;if(W&&W.path===$&&W.mtimeMs===Q&&W.size===Z)return W;let j=bU(J?hU($):D5());return U5={path:$,mtimeMs:Q,size:Z,value:j},U5}function M0(){return kU().value}function k1($,J={}){let Q=CX(),Z=M0();NU(yU(Q),{recursive:!0});let W=l4.parse($);if(!Z.telemetryOptOut&&W.telemetryOptOut)ij(J.telemetry);CU(Q,`${JSON.stringify(W,null,2)}
2
+ `,"utf8"),EU()}function R5(){return M0().telemetryOptOut}function yX($,J={}){k1({...M0(),telemetryOptOut:$},J)}function EX(){return M0().autoUpdateEnabled}function bX($,J={}){k1({...M0(),autoUpdateEnabled:$},J)}function B1($){return new Set($??M0().disabledTools??[])}function p4($){return new Set($??M0().disabledPlugins??[])}function hX($){return B1().has($)}function z5($){let J=M0(),Q=new Set(J.disabledTools??[]),Z=Q.has($);if(Z)Q.delete($);else Q.add($);return k1({...J,disabledTools:[...Q]}),!Z}function IZ($,J){let Q=[...new Set($.map((j)=>j.trim()).filter(Boolean))];if(Q.length===0)return;let Z=M0(),W=B1(Z.disabledTools);for(let j of Q)if(J)W.add(j);else W.delete(j);k1({...Z,disabledTools:[...W]})}function kX($,J){return IZ([$],J),J}function IX($){return p4().has($)}function xX($,J){let Q=$.trim();if(!Q)return;let Z=M0(),W=p4(Z.disabledPlugins);if(J)W.add(Q);else W.delete(Q);k1({...Z,disabledPlugins:[...W]})}function L5($,J){let Q=p4(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z))}function I1($,J){let Q=B1(J);if(Q.size===0)return[...$];return $.filter((Z)=>!Q.has(Z.name))}function _5($,J){if(!$||$.length===0)return $;let Q=B1(J);if(Q.size===0)return $;return $.map((Z)=>{if(!Z.setup)return Z;return{...Z,setup:(W,j)=>Z.setup?.({...W,registerTool:(f)=>{if(!Q.has(f.name))W.registerTool(f)}},j)}})}var SX,l4,U5;var W1=h$(()=>{O0();SX=e2.preprocess(($)=>Array.isArray($)?$.filter((J)=>typeof J==="string").map((J)=>J.trim()).filter(Boolean):void 0,e2.array(e2.string()).optional()).transform(($)=>{if(!$)return;let J=[...new Set($)].sort((Q,Z)=>Q.localeCompare(Z));return J.length>0?J:void 0}),l4=e2.object({telemetryOptOut:e2.boolean().default(!1).catch(!1),autoUpdateEnabled:e2.boolean().default(!0).catch(!0),disabledTools:SX.optional(),disabledPlugins:SX.optional()}).strip().transform(($)=>{let J={autoUpdateEnabled:$.autoUpdateEnabled,telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)J.disabledTools=$.disabledTools;if($.disabledPlugins?.length)J.disabledPlugins=$.disabledPlugins;return J})});var sX={};w(sX,{normalizeUserMessage:()=>NR,buildInitialUserContent:()=>PR});async function PR($,J,Q,Z){let W=wR(J),j=await CR(Q,Z);if(W.length===0&&!j)return $;let f=[{type:"text",text:$},...W];if(j)f.push(...j);return f}function NR($){if($==null)return"";if(typeof $==="string")return $;let J=$.content;if(typeof J==="string")return J;if(!Array.isArray(J))return"";let Q=[];for(let Z of J)if(Z&&typeof Z==="object"&&Z.type==="text"){let W=Z.text;if(typeof W==="string")Q.push(W)}return Q.join(`
3
+ `)}function wR($){if(!$||$.length===0)return[];let J=[];for(let Q of $){let Z=SR(Q);if(Z)J.push(Z)}return J}function SR($){let J=$.trim();if(!J)return;let Q=J.match(/^data:([^;,]+);base64,(.+)$/);if(Q){let Z=Q[1],W=Q[2];if(!Z||!W)return;return{type:"image",mediaType:Z,data:W}}return{type:"image",mediaType:"image/png",data:J}}async function CR($,J){if(!$||$.length===0)return;let Q=J??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Z=await Promise.all($.map(async(W)=>{let j=W.replace(/\\/g,"/");try{let f=await Q(W);return{type:"file",path:j,content:f}}catch(f){let X=f instanceof Error?f.message:String(f);return{type:"file",path:j,content:`Error fetching content: ${X}`}}}));if(Z.length===0)return;return Z}var UH={};w(UH,{updateMcpServerOAuthState:()=>H2,setMcpServerDisabled:()=>Y2,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>B0,registerMcpServersFromSettingsFile:()=>B2,normalizeMcpServerOAuthState:()=>w8,loadMcpSettingsFile:()=>X2,listMcpServerOAuthStatuses:()=>g6,hasMcpSettingsFile:()=>c1,getMcpServerOAuthState:()=>V2});import{existsSync as wO,mkdirSync as BH,readFileSync as a7,writeFileSync as AH}from"node:fs";import{dirname as KH}from"node:path";import{resolveMcpSettingsPath as SO}from"@cline/shared/storage";import{z as y}from"zod";function n7($){if(!$)return;if($==="http")return"streamableHttp";return $}function B0(){return SO()}function vO($){let J=a7($,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse MCP settings JSON at "${$}": ${W}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object.`);return Q}function DH($,J){if(!Object.hasOwn($,J))return;let Q=$[J];if(!Q||typeof Q!=="object"||Array.isArray(Q))return;return Q}function cO($,J,Q){Object.defineProperty($,J,{value:Q,enumerable:!0,configurable:!0,writable:!0})}function X2($={}){let J=$.filePath??B0(),Q=a7(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${J}": ${f}`)}let W=mO.safeParse(Z);if(!W.success){let j=W.error.issues.map((f)=>{let X=f.path.join(".");return X?`${X}: ${f.message}`:f.message}).join("; ");throw Error(`Invalid MCP settings at "${J}": ${j}`)}return W.data}function uO($){let J=a7($,"utf8"),Q;try{Q=JSON.parse(J)}catch(j){let f=j instanceof Error?j.message:String(j);throw Error(`Failed to parse MCP settings JSON at "${$}": ${f}`)}if(!Q||typeof Q!=="object"||Array.isArray(Q))throw Error(`Invalid MCP settings at "${$}": expected object`);let Z=Q,W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Z}function w8($){if(!$)return;let J={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(J).length>0?J:void 0}function dO($){if($===void 0)return;let J=s7.safeParse($);if(!J.success)return;return w8(J.data)}function c1($={}){let J=$.filePath??B0();return wO(J)}function A1($={}){let J=X2($);return Object.entries(J.mcpServers).map(([Q,Z])=>({name:Q,transport:Z.transport,disabled:Z.disabled,metadata:Z.metadata,oauth:Z.oauth}))}function Y2($){let J=$.filePath??B0(),Q=$.name.trim();if(!Q)throw Error("MCP server settings toggle requires a server name.");let Z=vO(J),W=Z.mcpServers;if(!W||typeof W!=="object"||Array.isArray(W))throw Error(`Invalid MCP settings at "${J}": mcpServers must be an object.`);let j={...W},f=DH(j,Q);if(!f)throw Error(`Unknown MCP server: ${Q}`);let X={...f};if($.disabled)X.disabled=!0;else delete X.disabled;cO(j,Q,X),BH(KH(J),{recursive:!0}),AH(J,`${JSON.stringify({...Z,mcpServers:j},null,2)}
4
+ `)}function V2($,J={}){let Q=X2(J);if(!Object.hasOwn(Q.mcpServers,$))return;return w8(Q.mcpServers[$]?.oauth)}function H2($,J,Q={}){let Z=Q.filePath??B0(),W=uO(Z),j=W.mcpServers,f=DH(j,$);if(!f)throw Error(`Unknown MCP server: ${$}`);let X=dO(f.oauth)??{},Y=w8(J(X));if(Y)f.oauth=Y;else delete f.oauth;return BH(KH(Z),{recursive:!0}),AH(Z,`${JSON.stringify(W,null,2)}
5
+ `,"utf8"),Y??{}}function g6($={}){return A1($).map((Q)=>{let Z=Q.transport.type!=="stdio",W=Q.oauth?.tokens?.access_token;return{serverName:Q.name,oauthSupported:Z,oauthConfigured:Z&&typeof W==="string"&&W.trim().length>0,lastError:Q.oauth?.lastError,lastAuthenticatedAt:Q.oauth?.lastAuthenticatedAt}}).sort((Q,Z)=>Q.serverName.localeCompare(Z.serverName))}async function B2($,J={}){let Q=A1(J);for(let Z of Q)await $.registerServer(Z);return Q}var x6,GH,s7,CO,yO,EO,bO,hO,kO,FH,IO,xO,gO,mO;var q9=h$(()=>{x6=y.record(y.string(),y.string()),GH=y.record(y.string(),y.unknown()),s7=y.object({clientInformation:y.record(y.string(),y.unknown()).optional(),tokens:y.record(y.string(),y.unknown()).optional(),codeVerifier:y.string().optional(),discoveryState:y.record(y.string(),y.unknown()).optional(),redirectUrl:y.string().url().optional(),lastError:y.string().optional(),lastAuthenticatedAt:y.number().int().positive().optional()}).strip(),CO=y.object({type:y.literal("stdio"),command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:x6.optional()}),yO=y.object({type:y.literal("sse"),url:y.string().url(),headers:x6.optional()}),EO=y.object({type:y.literal("streamableHttp"),url:y.string().url(),headers:x6.optional()}),bO=y.discriminatedUnion("type",[CO,yO,EO]),hO=y.object({transport:bO,disabled:y.boolean().optional(),metadata:GH.optional(),oauth:s7.optional()}),kO=y.enum(["stdio","sse","http","streamableHttp"]).optional(),FH=y.object({type:y.enum(["stdio","sse","streamableHttp"]).optional(),transportType:kO,disabled:y.boolean().optional(),metadata:GH.optional(),oauth:s7.optional()});IO=FH.extend({command:y.string().min(1),args:y.array(y.string()).optional(),cwd:y.string().min(1).optional(),env:x6.optional()}).superRefine(($,J)=>{let Q=$.type??n7($.transportType);if(Q&&Q!=="stdio")J.addIssue({code:y.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})),xO=FH.extend({url:y.string().url(),headers:x6.optional()}).superRefine(($,J)=>{let Q=$.type??n7($.transportType)??"sse";if(Q!=="sse"&&Q!=="streamableHttp")J.addIssue({code:y.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??n7($.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}}),gO=y.union([hO,IO,xO]),mO=y.object({mcpServers:y.record(y.string(),gO)}).passthrough()});import{existsSync as aP,mkdirSync as sP,readFileSync as oP,writeFileSync as tP}from"node:fs";import{resolve as eP}from"node:path";import{resolveSessionDataDir as $N}from"@cline/shared/storage";import{nanoid as JN}from"nanoid";import*as QN from"node-machine-id";function b0($){let J=$?.trim();if(J)return J;let Q=jN();if(Q)return Q;return fN()}function WN(){let $=QN;return $.machineIdSync??$.default?.machineIdSync}function jN(){try{let $=WN();if(!$)return;return $().trim()||void 0}catch{return}}function fN(){let $=$N(),J=eP($,ZN);try{if(aP(J)){let Z=oP(J,"utf8").trim();if(Z.length>0)return Z}}catch{}let Q=`cl-${JN()}`;try{sP($,{recursive:!0}),tP(J,Q,"utf8")}catch{}return Q}var ZN="machine-id";var g8=()=>{};class GJ{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($,J){if(!this.isEnabled())return;this.emitLog($,J,!1)}emitRequired($,J){this.emitLog($,J,!0)}recordCounter($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.counters.get($);if(!j)j=this.meter.createCounter($,Z?{description:Z}:void 0),this.counters.set($,j);j.add(J,this.flattenProperties(this.buildAttributes(Q)))}recordHistogram($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.histograms.get($);if(!j)j=this.meter.createHistogram($,Z?{description:Z}:void 0),this.histograms.set($,j);j.record(J,this.flattenProperties(this.buildAttributes(Q)))}recordGauge($,J,Q,Z,W=!1){if(!this.meter||!W&&!this.isEnabled())return;let j=this.buildAttributes(Q),f=JSON.stringify(j),X=this.gaugeValues.get($);if(J===null){if(X){if(X.delete(f),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let Y=X;if(!Y)Y=new Map,this.gaugeValues.set($,Y);if(!this.gauges.has($)){let V=this.meter.createObservableGauge($,Z?{description:Z}:void 0);V.addCallback((H)=>{for(let B of this.snapshotGaugeSeries($))H.observe(B.value,this.flattenProperties(B.attributes))}),this.gauges.set($,V)}Y.set(f,{value:J,attributes:j})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,J,Q){if(!this.logger)return;let Z=this.flattenProperties(this.buildAttributes(J,Q));this.logger.emit({severityText:"INFO",body:$,attributes:Z})}buildAttributes($,J=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...J?{_required:!0}:{}}}snapshotGaugeSeries($){let J=this.gaugeValues.get($);if(!J)return[];return Array.from(J.values(),(Q)=>({value:Q.value,attributes:Q.attributes?{...Q.attributes}:void 0}))}flattenProperties($,J="",Q=new WeakSet,Z=0){if(!$)return{};let W={},j=100,f=10;for(let[X,Y]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let V=J?`${J}.${X}`:X;if(Y===null||Y===void 0){W[V]=String(Y);continue}if(Array.isArray(Y)){let H=Y.length>j?Y.slice(0,j):Y;try{W[V]=JSON.stringify(H)}catch{W[V]="[UnserializableArray]"}if(Y.length>j)W[`${V}_truncated`]=!0,W[`${V}_original_length`]=Y.length;continue}if(typeof Y==="object"){if(Y instanceof Date){W[V]=Y.toISOString();continue}if(Y instanceof Error){W[V]=Y.message;continue}if(Q.has(Y)){W[V]="[Circular]";continue}if(Z>=f){W[V]="[MaxDepthExceeded]";continue}Q.add(Y),Object.assign(W,this.flattenProperties(Y,V,Q,Z+1));continue}if(Ow(Y)){W[V]=Y;continue}try{W[V]=JSON.stringify(Y)}catch{W[V]=String(Y)}}return W}}function Ow($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class FJ{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,J){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:J})}emitRequired($,J){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:J})}recordCounter($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordHistogram($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:J,attributes:Q,description:Z,required:W===!0})}recordGauge($,J,Q,Z,W){if(!W&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:J,attributes:Q,description:Z,required:W===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class o8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new FJ({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 J=this.buildAttributes($.properties);for(let Q of this.adapters)Q.emit($.event,J)}captureRequired($,J){let Q=this.buildAttributes(J);for(let Z of this.adapters)Z.emitRequired($,Q)}recordCounter($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordCounter($,J,j,Z,W)}recordHistogram($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordHistogram($,J,j,Z,W)}recordGauge($,J,Q,Z,W=!1){let j=this.buildAttributes(Q);for(let f of this.adapters)f.recordGauge($,J,j,Z,W)}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 X3=()=>{};import{metrics as Tw,trace as Mw}from"@opentelemetry/api";import{logs as qw}from"@opentelemetry/api-logs";import{OTLPLogExporter as Pw}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as Nw}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as ww}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as Sw}from"@opentelemetry/resources";import{BatchLogRecordProcessor as Cw,ConsoleLogRecordExporter as yw,LoggerProvider as Ew}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as bw,MeterProvider as hw,PeriodicExportingMetricReader as xA}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as kw,ConsoleSpanExporter as Iw,SimpleSpanProcessor as xw}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as gw}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as mw,ATTR_SERVICE_VERSION as vw}from"@opentelemetry/semantic-conventions";class gA{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($,J){this.resolveProperties(J)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class t8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let J=Sw({[mw]:$.serviceName??"cline",...$.serviceVersion?{[vw]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(J),this.loggerProvider=this.createLoggerProvider(J),this.tracerProvider=this.createTracerProvider(J),this.meterProvider)Tw.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)qw.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",J){return Mw.getTracer($,J??this.options.serviceVersion)}createAdapter($){return new GJ({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let J=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new o8({...$,adapters:[J],distinctId:b0($.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 J=Y3(this.options.metricsExporter);if(J.length===0)return null;let Q=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Z=Math.min(30000,Math.floor(Q*0.8)),W=J.map((j)=>dw(j,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:Q,timeout:Z})).filter((j)=>j!==null);if(W.length===0)return null;return new hw({resource:$,readers:W})}createTracerProvider($){let J=Y3(this.options.tracesExporter);if(J.length===0)return null;let Q=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Z=this.options.otlpTracesHeaders??this.options.otlpHeaders,W=[];for(let j of J){let f=uw(j,{endpoint:Q,headers:Z,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(f)W.push(f)}if(W.length===0)return null;return new gw({resource:$,spanProcessors:W})}createLoggerProvider($){let J=Y3(this.options.logsExporter);if(J.length===0)return null;let Q=J.map((Z)=>{let W=cw(Z,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!W)return null;return new Cw(W,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Z)=>Z!==null);if(Q.length===0)return null;return new Ew({resource:$,processors:Q})}}function DJ($){let J=new t8($),Q=J.createTelemetryService($);return Q.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:J,telemetry:Q}}function s1($){if(R5())return{telemetry:new gA($)};if($.enabled!==!0)return{telemetry:new o8({...$,distinctId:b0($.distinctId)})};return DJ($)}function e8($){let{telemetry:J,provider:Q}=s1($);return{telemetry:J,provider:Q,flush:async()=>{let j=Q;if(j&&typeof j.forceFlush==="function")try{await j.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([J.dispose(),Q?.dispose()])}}}function Y3($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((Q)=>Q.trim()).filter((Q)=>Q==="console"||Q==="otlp")}function cw($,J){if($==="console")return new yw;if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/logs");return new Pw({url:Q,headers:J.headers})}function uw($,J){if($==="console")return new xw(new Iw);if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/traces");return new kw(new ww({url:Q,headers:J.headers}))}function dw($,J){if($==="console")return new xA({exporter:new bw,exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout});if(!J.endpoint)return null;let Q=V3(J.endpoint,"/v1/metrics");return new xA({exporter:new Nw({url:Q,headers:J.headers}),exportIntervalMillis:J.interval,exportTimeoutMillis:J.timeout})}function V3($,J){let Q=new URL($),Z=Q.pathname.endsWith("/")?Q.pathname.slice(0,-1):Q.pathname;return Q.pathname=Z.endsWith(J)?Z:`${Z}${J}`,Q.toString()}var YQ=h$(()=>{W1();g8();X3()});var pK={};w(pK,{resolveCoreDistinctId:()=>b0,createOpenTelemetryTelemetryService:()=>DJ,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,OpenTelemetryProvider:()=>t8,OpenTelemetryAdapter:()=>GJ});var RQ=h$(()=>{g8();YQ()});import{AgentRuntimeAbortError as hb}from"@cline/agents";import{initVcr as kb,resolveClineBuildEnv as Ib}from"@cline/shared";import{normalizeProviderId as yb}from"@cline/llms";var nG={};w(nG,{LocalRuntimeHost:()=>L1});import{readdirSync as Ob}from"node:fs";import{homedir as Tb}from"node:os";import{isAbsolute as Mb,join as Ij,resolve as xj}from"node:path";import{captureSdkError as h2,createSessionId as qb,isLikelyAuthError as Pb,normalizeUserInput as Nb}from"@cline/shared";import{setHomeDirIfUnset as wb}from"@cline/shared/storage";var Tf={};w(Tf,{saveProviderOAuthCredentials:()=>x$,resolveProviderApiKeyFromSettings:()=>HZ,loginAndSaveProviderOAuthCredentials:()=>z4,isOAuthProvider:()=>I$,getProviderOAuthCredentialsFromSettings:()=>L4,getProviderAuthStorageId:()=>VZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>l2,formatProviderOAuthApiKey:()=>BZ});import{getClineEnvironmentConfig as _f}from"@cline/shared";O0();var Wf={};w(Wf,{startClineDeviceAuth:()=>WZ,refreshClineToken:()=>tJ,loginClineOAuth:()=>A4,getValidClineCredentials:()=>K4,completeClineDeviceAuth:()=>jZ});import{getClineEnvironmentConfig as eQ}from"@cline/shared";var aj={};w(aj,{startLocalOAuthServer:()=>J1});function GF(){let $;return{promise:new Promise((Q)=>{$=Q}),resolve:$}}async function J1($){let J=await import("node:http"),Q=$.host??"127.0.0.1",Z=$.timeoutMs??300000,W=$.successHtml??FF,j=GF(),f=!1,X=null,Y=null,V=null,H=(K)=>{if(f)return;f=!0,j.resolve(K)},B=()=>{if(X)clearTimeout(X),X=null;let K=V;if(V=null,Y)Y.close(),Y=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:Q,port:K})).catch(()=>{})},A=async()=>{return X=setTimeout(()=>{B(),H(null)},Z),j.promise};for(let K of $.ports){let G=J.createServer((D,U)=>{try{let F=new URL(D.url||"",`http://${Q}:${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}`),B(),H(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(W),B(),H(O)}catch{U.statusCode=500,U.end("Internal error")}}),R=await new Promise((D)=>{let U=(F)=>{G.off("error",U),D({bound:!1,error:F})};G.once("error",U),G.listen(K,Q,()=>{G.off("error",U),Y=G,D({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw B(),R.error}if(R.bound){V=K;let D=`http://${Q}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:Q,port:K,callbackUrl:D})).catch(()=>{});return{callbackUrl:D,waitForCallback:A,cancelWait:()=>{B(),H(null)},close:()=>{B(),H(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var FF=`<!DOCTYPE html>
6
6
  <html lang="en">
7
7
  <head>
8
8
  <meta charset="utf-8">
@@ -43,22 +43,22 @@ import{createRequire as YF}from"node:module";var{defineProperty:t9,getOwnPropert
43
43
  </div>
44
44
  <script>setTimeout(() => window.close(), 3000);</script>
45
45
  </body>
46
- </html>`;function oj($){let J="";for(let Q=0;Q<$.length;Q+=1)J+=String.fromCharCode($[Q]??0);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function DF($){let Q=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(Z)}function UF($=32){let J=new Uint8Array($);return crypto.getRandomValues(J),oj(J)}async function aJ(){let $=UF(),J=oj(await DF($));return{verifier:$,challenge:J}}function sJ($){return $.endsWith("/")?$.slice(0,-1):$}function k$($,J){return new URL(J,`${sJ($)}/`).toString()}function m2($,J={}){let Q=$.trim();if(!Q)return{};try{let Z=new URL(Q);return{code:Z.searchParams.get("code")??void 0,state:Z.searchParams.get("state")??void 0,provider:J.includeProvider?Z.searchParams.get("provider")??void 0:void 0}}catch{}if(J.allowHashCodeState&&Q.includes("#")){let[Z,W]=Q.split("#",2);return{code:Z||void 0,state:W||void 0}}if(Q.includes("code=")){let Z=new URLSearchParams(Q);return{code:Z.get("code")??void 0,state:Z.get("state")??void 0,provider:J.includeProvider?Z.get("provider")??void 0:void 0}}return{code:Q}}function RF($){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 T0($){if(!$)return null;try{let J=$.split(".");if(J.length!==3)return null;let Q=J[1];if(!Q)return null;let Z=Q.replace(/-/g,"+").replace(/_/g,"/"),W=Z.padEnd(Z.length+(4-Z.length%4)%4,"="),j=RF(W);if(!j)return null;return JSON.parse(j)}catch{return null}}function v2($){try{let J=JSON.parse($),Q=J.error,Z=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,W=typeof J.error_description==="string"?J.error_description:typeof J.message==="string"?J.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:Z,message:W}}catch{return{}}}function c2($,J){return Date.now()>=$.expires-J}async function u2($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let J,Q,Z=$.onManualCodeInput().then((j)=>{J=j,$.cancelWait()}).catch((j)=>{Q=j instanceof Error?j:Error(String(j)),$.cancelWait()}),W=await $.waitForCallback();if(Q)throw Q;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if(J)return m2(J,$.parseOptions);if(await Z,Q)throw Q;if(J)return m2(J,$.parseOptions);return{}}var oJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},Jf={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},$Z="https://api.workos.com",zF="/auth",tj=Array.from({length:11},($,J)=>48801+J),LF=300000,_F=30000,d2=30000,OF=300,TF=5;class J$ extends Error{status;errorCode;constructor($,J){super($);this.name="ClineOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 MF($){let J=Date.parse($);if(Number.isNaN(J))throw Error(`Invalid expiresAt value: ${$}`);return J}function JZ($,J,Q={}){let Z=$.userInfo.clineUserId??Q.accountId,W=$.refreshToken??Q.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:W,expires:MF($.expiresAt),accountId:Z??void 0,email:$.userInfo.email||Q.email,metadata:{provider:J,tokenType:$.tokenType,userInfo:$.userInfo}}}async function QZ($){if(!$)return{};return typeof $==="function"?await $():$}function ej($,J){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return J;return Math.floor($)}async function $f($){await new Promise((J)=>setTimeout(J,$))}function ZZ($,J){if(!$.success||!$.data?.accessToken)throw Error(J);return $.data}async function Qf($,J){let Q=await fetch(k$($Z,Jf.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(J?.requestTimeoutMs??d2)}),Z=await Q.json().catch(()=>({}));if(!Q.ok)throw new J$(`Device authorization failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error});if(!Z.device_code||!Z.user_code||!Z.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Z.device_code,userCode:Z.user_code,verificationUri:Z.verification_uri,verificationUriComplete:Z.verification_uri_complete,expiresInSeconds:ej(Z.expires_in,OF),pollIntervalSeconds:ej(Z.interval,TF)}}async function Zf($){let J=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=J){let Z=await fetch(k$($.workosApiBaseUrl,Jf.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)}),W=await Z.json().catch(()=>({}));if(Z.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await $f(Q*1000);break}case"slow_down":{Q+=1,await $f(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new J$(W.error_description||"WorkOS authorization failed",{status:Z.status,errorCode:W.error});default:throw new J$(`WorkOS token polling failed: ${Z.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Z.status,errorCode:W.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function Wf($,J,Q){let Z={accessToken:$.accessToken,refreshToken:$.refreshToken},W=await fetch(k$(J.apiBaseUrl,oJ.register),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??d2)});if(!W.ok){let f=await W.text().catch(()=>""),X=v2(f);throw new J$(`Token registration failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return JZ(ZZ(j,"Invalid token exchange response"),Q??J.provider)}async function qF($,J,Q,Z){let W={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:J,provider:Z??Q.provider},j=await fetch(k$(Q.apiBaseUrl,oJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(Q.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Q.requestTimeoutMs??d2)});if(!j.ok){let X=await j.text().catch(()=>""),Y=v2(X);throw new J$(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let f=await j.json();return JZ(ZZ(f,"Invalid token exchange response"),Z??Q.provider)}async function A4($){P1($.telemetry,$.provider??"cline");let J=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:tj,Z=$.callbackPath??zF,W=J?null:await J1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=W?.callbackUrl||`http://127.0.0.1:${Q[0]??tj[0]}${Z}`;try{let f;if(J){let X=e9().workOsClientId,Y=await Qf(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await Zf({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d2,workosApiBaseUrl:$Z,onProgress:$.callbacks.onProgress});f=await Wf(V,$,$.provider)}else{let X=new URL(k$($.apiBaseUrl,oJ.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",j),X.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,H=await u2({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(Y=H.code,V=H.provider??V,!Y){let B=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=m2(B,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");f=await qF(Y,j,$,V)}return N1($.telemetry,$.provider??"cline"),S1($.telemetry,{id:f.accountId,email:f.email,provider:$.provider??"cline"}),f}catch(f){throw w1($.telemetry,$.provider??"cline",f instanceof Error?f.message:String(f)),f}finally{W?.close()}}async function WZ($){return await Qf(e9().workOsClientId,$)}async function jZ($){let J=$.provider??"cline";P1($.telemetry,J);try{let Q=await Zf({clientId:e9().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d2,workosApiBaseUrl:$Z}),Z=await Wf(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return N1($.telemetry,J),S1($.telemetry,{id:Z.accountId,email:Z.email,provider:J}),Z}catch(Q){throw w1($.telemetry,J,Q instanceof Error?Q.message:String(Q)),Q}}async function tJ($,J){let Q=await fetch(k$(J.apiBaseUrl,oJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(J.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(J.requestTimeoutMs??d2)});if(!Q.ok){let j=await Q.text().catch(()=>""),f=v2(j);throw new J$(`Token refresh failed: ${Q.status}${f.message?` - ${f.message}`:""}`,{status:Q.status,errorCode:f.code})}let Z=await Q.json(),W=$.metadata?.provider??J.provider;return JZ(ZZ(Z,"Invalid token refresh response"),W,$)}async function K4($,J,Q){if(!$)return null;let Z=Q?.refreshBufferMs??LF,W=Q?.retryableTokenGraceMs??_F;if(Q?.forceRefresh!==!0&&!c2($,Z))return $;try{return await tJ($,J)}catch(f){if(f instanceof J$&&f.isLikelyInvalidGrant())return e1(J.telemetry,J.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}O0();var Xf={};w(Xf,{refreshOpenAICodexToken:()=>$5,loginOpenAICodex:()=>G4,getValidOpenAICodexCredentials:()=>F4,OPENAI_CODEX_OAUTH_CONFIG:()=>$0});import{nanoid as PF}from"nanoid";var $0={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 eJ extends Error{status;errorCode;constructor($,J){super($);this.name="OpenAICodexOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 NF($,J,Q=$0.redirectUri){let Z=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$0.clientId,code:$,code_verifier:J,redirect_uri:Q}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!Z.ok)return{type:"failed"};let W=await Z.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function wF($){try{let J=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:$0.clientId}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!J.ok){let Z=await J.text().catch(()=>""),W=v2(Z);throw new eJ(`Token refresh failed: ${J.status}${W.message?` - ${W.message}`:""}`,{status:J.status,errorCode:W.code})}let Q=await J.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(J){if(J instanceof eJ)throw J;return{type:"failed"}}}async function SF($="pi"){let{verifier:J,challenge:Q}=await aJ(),Z=PF(32),W=new URL($0.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",$0.clientId),W.searchParams.set("redirect_uri",$0.redirectUri),W.searchParams.set("scope",$0.scopes),W.searchParams.set("code_challenge",Q),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",Z),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",$),{verifier:J,state:Z,url:W.toString()}}function CF(){try{let $=new URL($0.redirectUri),J=$.port.length>0?Number.parseInt($.port,10):$0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(J)?J:$0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:$0.callbackPort,callbackPath:"/auth/callback",redirectUri:$0.redirectUri}}}function yF($,J){let Q=J?T0(J):T0($),Z=Q?Q:T0($),j=Z?.[$0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let f=Z?.organizations;if(Array.isArray(f)&&f.length>0){let Y=f[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Z?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function ff($,J){let Q=yF($.access,$.idToken)??J?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||J?.refresh||"",expires:$.expires,accountId:Q,email:$.email??J?.email,metadata:{...J?.metadata??{},provider:"openai-codex"}}}async function G4($){P1($.telemetry,"openai-codex");let J=CF(),{verifier:Q,state:Z,url:W}=await SF($.originator),j=await J1({host:J.host,ports:[J.port],callbackPath:J.callbackPath,expectedState:Z});$.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let f;try{let X=await u2({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Z)throw Error("State mismatch");if(f=X.code,!f){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=m2(H,{allowHashCodeState:!0});if(B.state&&B.state!==Z)throw Error("State mismatch");f=B.code}if(!f)throw Error("Missing authorization code");let Y=await NF(f,Q,J.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=ff(Y);return N1($.telemetry,"openai-codex"),S1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw w1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{j.close()}}async function $5($,J){let Q=await wF($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Z=ff(Q,J);if(!Z.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Z}async function F4($,J){if(!$)return null;let Q=J?.refreshBufferMs??$0.refreshBufferMs,Z=J?.retryableTokenGraceMs??$0.retryableTokenGraceMs;if(J?.forceRefresh!==!0&&!c2($,Q))return $;try{return await $5($.refresh,$)}catch(j){if(j instanceof eJ&&j.isLikelyInvalidGrant())return e1(J?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}O0();var _f={};w(_f,{refreshOcaToken:()=>W5,loginOcaOAuth:()=>U4,getValidOcaCredentials:()=>R4,OCI_HEADER_OPC_REQUEST_ID:()=>EF,DEFAULT_INTERNAL_OCA_BASE_URL:()=>J5,DEFAULT_INTERNAL_IDCS_URL:()=>Hf,DEFAULT_INTERNAL_IDCS_SCOPES:()=>Bf,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>Vf,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>Q5,DEFAULT_EXTERNAL_IDCS_URL:()=>Kf,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>Gf,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>Af});import{nanoid as Yf}from"nanoid";class fZ{ttlMs;maxEntries;entries=new Map;constructor($,J){this.ttlMs=$;this.maxEntries=J}get($,J=Date.now()){this.pruneExpired(J);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,J,Q=Date.now(),Z=this.ttlMs){this.pruneExpired(Q),this.entries.delete($);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set($,{value:J,expiresAt:Q+Z})}pruneExpired($){for(let[J,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(J)}}var Vf="a8331954c0cf48ba99b5dd223a14c6ea",Hf="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",Bf="openid offline_access",J5="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Af="c1aba3deed5740659981a752714eba33",Kf="https://login-ext.identity.oraclecloud.com",Gf="openid offline_access",Q5="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",EF="opc-request-id",bF="/auth/oca",hF=Array.from({length:11},($,J)=>48801+J),kF=300000,IF=30000,Ff=30000,xF=600000;class Z5 extends Error{status;errorCode;constructor($,J){super($);this.name="OcaOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 Q$={internal:{clientId:Vf,idcsUrl:Hf,scopes:Bf,baseUrl:J5},external:{clientId:Af,idcsUrl:Kf,scopes:Gf,baseUrl:Q5}},D4=new Map,gF=86400000,mF=300000,vF=32,XZ=new fZ(gF,vF);function Df($){if(typeof $==="function")return $();return $??"internal"}function Uf($){return{internal:{clientId:$?.internal?.clientId??Q$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??Q$.internal.idcsUrl,scopes:$?.internal?.scopes??Q$.internal.scopes,baseUrl:$?.internal?.baseUrl??Q$.internal.baseUrl},external:{clientId:$?.external?.clientId??Q$.external.clientId,idcsUrl:$?.external?.idcsUrl??Q$.external.idcsUrl,scopes:$?.external?.scopes??Q$.external.scopes,baseUrl:$?.external?.baseUrl??Q$.external.baseUrl}}}function cF($=Date.now()){let J=$-xF;for(let[Q,Z]of D4.entries())if(Z.createdAt<J)D4.delete(Q)}function uF($,J,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let W=T0(J)?.exp;if(typeof W==="number"&&W>0)return W*1000;let f=T0(Q)?.exp;if(typeof f==="number"&&f>0)return f*1000;return Date.now()+3600000}function Rf($,J,Q){let Z=$.access_token;if(!Z)throw Error("Token response did not include an access token");let W=$.refresh_token??Q?.refresh;if(!W)throw Error("Token response did not include a refresh token");let j=T0($.id_token),f=T0(Z),X=j?.sub??f?.sub,Y=j?.email??f?.email;return{access:Z,refresh:W,expires:uF($,Z,$.id_token),accountId:X??Q?.accountId,email:Y??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:J,subject:X,idToken:$.id_token}}}async function zf($,J){let Q=sJ($),Z=XZ.get(Q);if(Z)return Z;let W=`${Q}/.well-known/openid-configuration`,j=await fetch(W,{method:"GET",signal:AbortSignal.timeout(J)});if(!j.ok){let Y=`${Q}/oauth2/v1/token`;return XZ.set(Q,Y,Date.now(),mF),Y}let X=(await j.json()).token_endpoint||`${Q}/oauth2/v1/token`;return XZ.set(Q,X),X}function Lf($){return{code:$.error,message:$.error_description}}async function dF($){let J=D4.get($.state);if(!J)throw Error("No PKCE verifier found for this state");D4.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,Z=await zf(Q.idcsUrl,$.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:J.redirectUri,client_id:Q.clientId,code_verifier:J.verifier}),j=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout($.requestTimeoutMs)}),f=await j.json();if(!j.ok){let Y=Lf(f);throw new Z5(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let X=T0(f.id_token);if(!f.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==J.nonce)throw Error("OIDC nonce verification failed");return Rf(f,$.mode)}function lF($){let J=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${sJ(J.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",J.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",J.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function U4($){P1($.telemetry,"oca");let J=Uf($.config),Q=Df($.mode),Z=$.callbackPorts?.length?$.callbackPorts:hF,W=$.callbackPath??bF,j=$.requestTimeoutMs??Ff,f=await J1({ports:Z,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=f.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=Yf(16),V=Yf(16),{verifier:H,challenge:B}=await aJ();cF(),D4.set(Y,{verifier:H,nonce:V,mode:Q,redirectUri:X,createdAt:Date.now()});let A=lF({callbackUrl:X,mode:Q,state:Y,nonce:V,challenge:B,config:J});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await u2({waitForCallback:f.waitForCallback,cancelWait:f.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!==Y)throw Error("State mismatch");let D=await dF({code:G,state:R,mode:Q,config:J,requestTimeoutMs:j});return N1($.telemetry,"oca"),S1($.telemetry,{id:D.accountId,email:D.email,provider:"oca"}),D}catch(K){throw w1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{f.close()}}async function W5($,J={}){let Q=Uf(J.config),Z=J.requestTimeoutMs??Ff,W=$.metadata?.mode,j=W==="internal"||W==="external"?W:Df(J.mode),f=j==="external"?Q.external:Q.internal,X=await zf(f.idcsUrl,Z),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:f.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Z)}),H=await V.json();if(!V.ok){let B=Lf(H);throw new Z5(`Token refresh failed: ${V.status}${B.message?` - ${B.message}`:""}`,{status:V.status,errorCode:B.code})}return Rf(H,j,$)}async function R4($,J,Q){if(!$)return null;let Z=J?.refreshBufferMs??Q?.refreshBufferMs??kF,W=J?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??IF;if(J?.forceRefresh!==!0&&!c2($,Z))return $;try{return await W5($,Q)}catch(f){if(f instanceof Z5&&f.isLikelyInvalidGrant())return e1(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}var j5="workos:";function pF($){let J=$.trim();return J.toLowerCase().startsWith(j5)?J:`${j5}${J}`}function rF($){let J=$.trim();return J.toLowerCase().startsWith(j5)?J.slice(j5.length):J}function iF($){let Q=T0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function nF($,J){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let Z=iF(J);if(Z)return Z;return Date.now()-1}function aF($,J){let Q=$.auth?.accessToken?.trim(),Z=$.auth?.refreshToken?.trim();if(!Q||!Z)return null;let W=J?.normalizeAccessToken?.(Q)??Q;if(!W)return null;return{access:W,refresh:Z,expires:nF($,W),accountId:$.auth?.accountId}}function sF($){let J=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:J,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Z={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(Z,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Z}function YZ($){let J=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:J,getApiKey(Q){let Z=Q?.auth?.accessToken?.trim();if(Z)return $.formatAccessToken?.(Z)??Z;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return sF({...Q,storageProviderId:J,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function Tf($){return YZ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:pF,normalizeStoredAccessToken:rF,login:({settings:J,callbacks:Q,telemetry:Z})=>A4({apiBaseUrl:J?.baseUrl?.trim()||Of().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:Z}),refresh:({settings:J,credentials:Q,forceRefresh:Z,telemetry:W})=>K4(Q,{apiBaseUrl:J.baseUrl?.trim()||Of().apiBaseUrl,telemetry:W},{forceRefresh:Z})})}var oF=[Tf({providerId:"cline"}),Tf({providerId:"cline-pass",storageProviderId:"cline"}),YZ({providerId:"oca",login:({settings:$,callbacks:J,telemetry:Q})=>U4({mode:$?.oca?.mode,callbacks:J,telemetry:Q}),refresh:({settings:$,credentials:J,forceRefresh:Q,telemetry:Z})=>R4(J,{forceRefresh:Q,telemetry:Z},{mode:$.oca?.mode,telemetry:Z})}),YZ({providerId:"openai-codex",login:({callbacks:$,telemetry:J})=>G4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:J}),refresh:({credentials:$,forceRefresh:J,telemetry:Q})=>F4($,{forceRefresh:J,telemetry:Q})})],tF=new Map(oF.map(($)=>[$.providerId,$]));function Z0($){return tF.get($.trim().toLowerCase())}function I$($){return Z0($)!==void 0}function VZ($){return Z0($)?.storageProviderId}function HZ($,J){let Q=Z0(J),Z=Q?.storageProviderId??J,W=$.getProviderSettings(Z);return Q?.getApiKey(W)??l2(J,W)}async function z4($,J,Q){let Z=Z0(J);if(!Z)throw Error(`Provider "${J}" does not support OAuth login`);let W=$.getProviderSettings(Z.storageProviderId),j=await Z.login({settings:W,callbacks:Q.callbacks,telemetry:Q.telemetry});return Z.saveCredentials({manager:$,settings:W,credentials:j})}function L4($,J){let Q=Z0($);if(!Q)return null;return aF(J,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function x$($){let J=Z0($.providerId);if(!J)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return J.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function l2($,J){let Q=Z0($);if(Q)return Q.getApiKey(J);return J?.auth?.accessToken?.trim()||J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0}function BZ($,J){let Q=Z0($);if(!Q)return J.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:J.access}})??J.access}O0();var of={};w(of,{createContextCompactionPrepareTurn:()=>P4});import{createHandlerAsync as ZD}from"@cline/llms";import{estimateTokens as AZ}from"@cline/shared";var Nf=200000,KZ=0.9,wf=16384,GZ=20000,qf=1024,Pf=2000,Sf=2000,Cf=8;function Z$($,J){if($.length<=J)return $;return`${$.slice(0,J)}
46
+ </html>`;function sj($){let J="";for(let Q=0;Q<$.length;Q+=1)J+=String.fromCharCode($[Q]??0);return btoa(J).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function DF($){let Q=new TextEncoder().encode($),Z=await crypto.subtle.digest("SHA-256",Q);return new Uint8Array(Z)}function UF($=32){let J=new Uint8Array($);return crypto.getRandomValues(J),sj(J)}async function aJ(){let $=UF(),J=sj(await DF($));return{verifier:$,challenge:J}}function sJ($){return $.endsWith("/")?$.slice(0,-1):$}function k$($,J){return new URL(J,`${sJ($)}/`).toString()}function m2($,J={}){let Q=$.trim();if(!Q)return{};try{let Z=new URL(Q);return{code:Z.searchParams.get("code")??void 0,state:Z.searchParams.get("state")??void 0,provider:J.includeProvider?Z.searchParams.get("provider")??void 0:void 0}}catch{}if(J.allowHashCodeState&&Q.includes("#")){let[Z,W]=Q.split("#",2);return{code:Z||void 0,state:W||void 0}}if(Q.includes("code=")){let Z=new URLSearchParams(Q);return{code:Z.get("code")??void 0,state:Z.get("state")??void 0,provider:J.includeProvider?Z.get("provider")??void 0:void 0}}return{code:Q}}function RF($){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 T0($){if(!$)return null;try{let J=$.split(".");if(J.length!==3)return null;let Q=J[1];if(!Q)return null;let Z=Q.replace(/-/g,"+").replace(/_/g,"/"),W=Z.padEnd(Z.length+(4-Z.length%4)%4,"="),j=RF(W);if(!j)return null;return JSON.parse(j)}catch{return null}}function v2($){try{let J=JSON.parse($),Q=J.error,Z=typeof Q==="string"?Q:Q&&typeof Q==="object"&&typeof Q.type==="string"?Q.type:void 0,W=typeof J.error_description==="string"?J.error_description:typeof J.message==="string"?J.message:Q&&typeof Q==="object"&&typeof Q.message==="string"?Q.message:void 0;return{code:Z,message:W}}catch{return{}}}function c2($,J){return Date.now()>=$.expires-J}async function u2($){if(!$.onManualCodeInput){let j=await $.waitForCallback();return{code:j?.code,state:j?.state,provider:j?.provider,error:j?.error}}let J,Q,Z=$.onManualCodeInput().then((j)=>{J=j,$.cancelWait()}).catch((j)=>{Q=j instanceof Error?j:Error(String(j)),$.cancelWait()}),W=await $.waitForCallback();if(Q)throw Q;if(W?.code||W?.error)return{code:W.code,state:W.state,provider:W.provider,error:W.error};if(J)return m2(J,$.parseOptions);if(await Z,Q)throw Q;if(J)return m2(J,$.parseOptions);return{}}var oJ={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},$f={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},$Z="https://api.workos.com",zF="/auth",oj=Array.from({length:11},($,J)=>48801+J),LF=300000,_F=30000,d2=30000,OF=300,TF=5;class J$ extends Error{status;errorCode;constructor($,J){super($);this.name="ClineOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 MF($){let J=Date.parse($);if(Number.isNaN(J))throw Error(`Invalid expiresAt value: ${$}`);return J}function JZ($,J,Q={}){let Z=$.userInfo.clineUserId??Q.accountId,W=$.refreshToken??Q.refresh;if(!W)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:W,expires:MF($.expiresAt),accountId:Z??void 0,email:$.userInfo.email||Q.email,metadata:{provider:J,tokenType:$.tokenType,userInfo:$.userInfo}}}async function QZ($){if(!$)return{};return typeof $==="function"?await $():$}function tj($,J){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return J;return Math.floor($)}async function ej($){await new Promise((J)=>setTimeout(J,$))}function ZZ($,J){if(!$.success||!$.data?.accessToken)throw Error(J);return $.data}async function Jf($,J){let Q=await fetch(k$($Z,$f.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(J?.requestTimeoutMs??d2)}),Z=await Q.json().catch(()=>({}));if(!Q.ok)throw new J$(`Device authorization failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error});if(!Z.device_code||!Z.user_code||!Z.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Z.device_code,userCode:Z.user_code,verificationUri:Z.verification_uri,verificationUriComplete:Z.verification_uri_complete,expiresInSeconds:tj(Z.expires_in,OF),pollIntervalSeconds:tj(Z.interval,TF)}}async function Qf($){let J=Date.now()+$.expiresInSeconds*1000,Q=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=J){let Z=await fetch(k$($.workosApiBaseUrl,$f.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)}),W=await Z.json().catch(()=>({}));if(Z.ok){if(!W.access_token||!W.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:W.access_token,refreshToken:W.refresh_token,tokenType:W.token_type??"Bearer"}}switch(W.error){case"authorization_pending":{await ej(Q*1000);break}case"slow_down":{Q+=1,await ej(Q*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new J$(W.error_description||"WorkOS authorization failed",{status:Z.status,errorCode:W.error});default:throw new J$(`WorkOS token polling failed: ${Z.status}${W.error_description?` - ${W.error_description}`:""}`,{status:Z.status,errorCode:W.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function Zf($,J,Q){let Z={accessToken:$.accessToken,refreshToken:$.refreshToken},W=await fetch(k$(J.apiBaseUrl,oJ.register),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??d2)});if(!W.ok){let f=await W.text().catch(()=>""),X=v2(f);throw new J$(`Token registration failed: ${W.status}${X.message?` - ${X.message}`:""}`,{status:W.status,errorCode:X.code})}let j=await W.json();return JZ(ZZ(j,"Invalid token exchange response"),Q??J.provider)}async function qF($,J,Q,Z){let W={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:J,provider:Z??Q.provider},j=await fetch(k$(Q.apiBaseUrl,oJ.token),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(Q.headers)},body:JSON.stringify(W),signal:AbortSignal.timeout(Q.requestTimeoutMs??d2)});if(!j.ok){let X=await j.text().catch(()=>""),Y=v2(X);throw new J$(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let f=await j.json();return JZ(ZZ(f,"Invalid token exchange response"),Z??Q.provider)}async function A4($){P1($.telemetry,$.provider??"cline");let J=$.useWorkOSDeviceAuth??!0,Q=$.callbackPorts?.length?$.callbackPorts:oj,Z=$.callbackPath??zF,W=J?null:await J1({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),j=W?.callbackUrl||`http://127.0.0.1:${Q[0]??oj[0]}${Z}`;try{let f;if(J){let X=eQ().workOsClientId,Y=await Jf(X,$);$.callbacks.onAuth({url:Y.verificationUriComplete??Y.verificationUri,instructions:`Enter this code in your browser: ${Y.userCode}`});let V=await Qf({clientId:X,deviceCode:Y.deviceCode,expiresInSeconds:Y.expiresInSeconds,initialPollIntervalSeconds:Y.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d2,workosApiBaseUrl:$Z,onProgress:$.callbacks.onProgress});f=await Zf(V,$,$.provider)}else{let X=new URL(k$($.apiBaseUrl,oJ.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",j),X.searchParams.set("redirect_uri",j),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let Y,V=$.provider,H=await u2({waitForCallback:W?.waitForCallback??(async()=>null),cancelWait:W?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(H.error)throw Error(`OAuth error: ${H.error}`);if(Y=H.code,V=H.provider??V,!Y){let B=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=m2(B,{includeProvider:!0});Y=A.code,V=A.provider??V}if(!Y)throw Error("Missing authorization code");f=await qF(Y,j,$,V)}return N1($.telemetry,$.provider??"cline"),S1($.telemetry,{id:f.accountId,email:f.email,provider:$.provider??"cline"}),f}catch(f){throw w1($.telemetry,$.provider??"cline",f instanceof Error?f.message:String(f)),f}finally{W?.close()}}async function WZ($){return await Jf(eQ().workOsClientId,$)}async function jZ($){let J=$.provider??"cline";P1($.telemetry,J);try{let Q=await Qf({clientId:eQ().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??d2,workosApiBaseUrl:$Z}),Z=await Zf(Q,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return N1($.telemetry,J),S1($.telemetry,{id:Z.accountId,email:Z.email,provider:J}),Z}catch(Q){throw w1($.telemetry,J,Q instanceof Error?Q.message:String(Q)),Q}}async function tJ($,J){let Q=await fetch(k$(J.apiBaseUrl,oJ.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await QZ(J.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(J.requestTimeoutMs??d2)});if(!Q.ok){let j=await Q.text().catch(()=>""),f=v2(j);throw new J$(`Token refresh failed: ${Q.status}${f.message?` - ${f.message}`:""}`,{status:Q.status,errorCode:f.code})}let Z=await Q.json(),W=$.metadata?.provider??J.provider;return JZ(ZZ(Z,"Invalid token refresh response"),W,$)}async function K4($,J,Q){if(!$)return null;let Z=Q?.refreshBufferMs??LF,W=Q?.retryableTokenGraceMs??_F;if(Q?.forceRefresh!==!0&&!c2($,Z))return $;try{return await tJ($,J)}catch(f){if(f instanceof J$&&f.isLikelyInvalidGrant())return e1(J.telemetry,J.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}O0();var ff={};w(ff,{refreshOpenAICodexToken:()=>$5,loginOpenAICodex:()=>G4,getValidOpenAICodexCredentials:()=>F4,OPENAI_CODEX_OAUTH_CONFIG:()=>$0});import{nanoid as PF}from"nanoid";var $0={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 eJ extends Error{status;errorCode;constructor($,J){super($);this.name="OpenAICodexOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 NF($,J,Q=$0.redirectUri){let Z=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:$0.clientId,code:$,code_verifier:J,redirect_uri:Q}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!Z.ok)return{type:"failed"};let W=await Z.json();if(!W.access_token||!W.refresh_token||typeof W.expires_in!=="number")return{type:"failed"};return{type:"success",access:W.access_token,refresh:W.refresh_token,expires:Date.now()+W.expires_in*1000,email:W.email,idToken:W.id_token}}async function wF($){try{let J=await fetch($0.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:$0.clientId}),signal:AbortSignal.timeout($0.httpTimeoutMs)});if(!J.ok){let Z=await J.text().catch(()=>""),W=v2(Z);throw new eJ(`Token refresh failed: ${J.status}${W.message?` - ${W.message}`:""}`,{status:J.status,errorCode:W.code})}let Q=await J.json();if(!Q.access_token||!Q.refresh_token||typeof Q.expires_in!=="number")return{type:"failed"};return{type:"success",access:Q.access_token,refresh:Q.refresh_token,expires:Date.now()+Q.expires_in*1000,email:Q.email,idToken:Q.id_token}}catch(J){if(J instanceof eJ)throw J;return{type:"failed"}}}async function SF($="pi"){let{verifier:J,challenge:Q}=await aJ(),Z=PF(32),W=new URL($0.authorizationEndpoint);return W.searchParams.set("response_type","code"),W.searchParams.set("client_id",$0.clientId),W.searchParams.set("redirect_uri",$0.redirectUri),W.searchParams.set("scope",$0.scopes),W.searchParams.set("code_challenge",Q),W.searchParams.set("code_challenge_method","S256"),W.searchParams.set("state",Z),W.searchParams.set("id_token_add_organizations","true"),W.searchParams.set("codex_cli_simplified_flow","true"),W.searchParams.set("originator",$),{verifier:J,state:Z,url:W.toString()}}function CF(){try{let $=new URL($0.redirectUri),J=$.port.length>0?Number.parseInt($.port,10):$0.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(J)?J:$0.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:$0.callbackPort,callbackPath:"/auth/callback",redirectUri:$0.redirectUri}}}function yF($,J){let Q=J?T0(J):T0($),Z=Q?Q:T0($),j=Z?.[$0.jwtClaimPath]?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;let f=Z?.organizations;if(Array.isArray(f)&&f.length>0){let Y=f[0];if(typeof Y?.id==="string"&&Y.id.length>0)return Y.id}let X=Z?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function jf($,J){let Q=yF($.access,$.idToken)??J?.accountId;if(!Q)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||J?.refresh||"",expires:$.expires,accountId:Q,email:$.email??J?.email,metadata:{...J?.metadata??{},provider:"openai-codex"}}}async function G4($){P1($.telemetry,"openai-codex");let J=CF(),{verifier:Q,state:Z,url:W}=await SF($.originator),j=await J1({host:J.host,ports:[J.port],callbackPath:J.callbackPath,expectedState:Z});$.onAuth({url:W,instructions:"Continue the authentication process in your browser."});let f;try{let X=await u2({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Z)throw Error("State mismatch");if(f=X.code,!f){let H=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=m2(H,{allowHashCodeState:!0});if(B.state&&B.state!==Z)throw Error("State mismatch");f=B.code}if(!f)throw Error("Missing authorization code");let Y=await NF(f,Q,J.redirectUri);if(Y.type!=="success")throw Error("Token exchange failed");let V=jf(Y);return N1($.telemetry,"openai-codex"),S1($.telemetry,{id:V.accountId,email:V.email,provider:"openai-codex"}),V}catch(X){throw w1($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{j.close()}}async function $5($,J){let Q=await wF($);if(Q.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Z=jf(Q,J);if(!Z.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Z}async function F4($,J){if(!$)return null;let Q=J?.refreshBufferMs??$0.refreshBufferMs,Z=J?.retryableTokenGraceMs??$0.retryableTokenGraceMs;if(J?.forceRefresh!==!0&&!c2($,Q))return $;try{return await $5($.refresh,$)}catch(j){if(j instanceof eJ&&j.isLikelyInvalidGrant())return e1(J?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}O0();var Lf={};w(Lf,{refreshOcaToken:()=>W5,loginOcaOAuth:()=>U4,getValidOcaCredentials:()=>R4,OCI_HEADER_OPC_REQUEST_ID:()=>EF,DEFAULT_INTERNAL_OCA_BASE_URL:()=>J5,DEFAULT_INTERNAL_IDCS_URL:()=>Vf,DEFAULT_INTERNAL_IDCS_SCOPES:()=>Hf,DEFAULT_INTERNAL_IDCS_CLIENT_ID:()=>Yf,DEFAULT_EXTERNAL_OCA_BASE_URL:()=>Q5,DEFAULT_EXTERNAL_IDCS_URL:()=>Af,DEFAULT_EXTERNAL_IDCS_SCOPES:()=>Kf,DEFAULT_EXTERNAL_IDCS_CLIENT_ID:()=>Bf});import{nanoid as Xf}from"nanoid";class fZ{ttlMs;maxEntries;entries=new Map;constructor($,J){this.ttlMs=$;this.maxEntries=J}get($,J=Date.now()){this.pruneExpired(J);let Q=this.entries.get($);if(!Q)return;return this.entries.delete($),this.entries.set($,Q),Q.value}set($,J,Q=Date.now(),Z=this.ttlMs){this.pruneExpired(Q),this.entries.delete($);while(this.entries.size>=this.maxEntries){let W=this.entries.keys().next().value;if(W===void 0)break;this.entries.delete(W)}this.entries.set($,{value:J,expiresAt:Q+Z})}pruneExpired($){for(let[J,Q]of this.entries)if(Q.expiresAt<=$)this.entries.delete(J)}}var Yf="a8331954c0cf48ba99b5dd223a14c6ea",Vf="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",Hf="openid offline_access",J5="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",Bf="c1aba3deed5740659981a752714eba33",Af="https://login-ext.identity.oraclecloud.com",Kf="openid offline_access",Q5="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",EF="opc-request-id",bF="/auth/oca",hF=Array.from({length:11},($,J)=>48801+J),kF=300000,IF=30000,Gf=30000,xF=600000;class Z5 extends Error{status;errorCode;constructor($,J){super($);this.name="OcaOAuthTokenError",this.status=J?.status,this.errorCode=J?.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 Q$={internal:{clientId:Yf,idcsUrl:Vf,scopes:Hf,baseUrl:J5},external:{clientId:Bf,idcsUrl:Af,scopes:Kf,baseUrl:Q5}},D4=new Map,gF=86400000,mF=300000,vF=32,XZ=new fZ(gF,vF);function Ff($){if(typeof $==="function")return $();return $??"internal"}function Df($){return{internal:{clientId:$?.internal?.clientId??Q$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??Q$.internal.idcsUrl,scopes:$?.internal?.scopes??Q$.internal.scopes,baseUrl:$?.internal?.baseUrl??Q$.internal.baseUrl},external:{clientId:$?.external?.clientId??Q$.external.clientId,idcsUrl:$?.external?.idcsUrl??Q$.external.idcsUrl,scopes:$?.external?.scopes??Q$.external.scopes,baseUrl:$?.external?.baseUrl??Q$.external.baseUrl}}}function cF($=Date.now()){let J=$-xF;for(let[Q,Z]of D4.entries())if(Z.createdAt<J)D4.delete(Q)}function uF($,J,Q){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let W=T0(J)?.exp;if(typeof W==="number"&&W>0)return W*1000;let f=T0(Q)?.exp;if(typeof f==="number"&&f>0)return f*1000;return Date.now()+3600000}function Uf($,J,Q){let Z=$.access_token;if(!Z)throw Error("Token response did not include an access token");let W=$.refresh_token??Q?.refresh;if(!W)throw Error("Token response did not include a refresh token");let j=T0($.id_token),f=T0(Z),X=j?.sub??f?.sub,Y=j?.email??f?.email;return{access:Z,refresh:W,expires:uF($,Z,$.id_token),accountId:X??Q?.accountId,email:Y??Q?.email,metadata:{...Q?.metadata??{},provider:"oca",mode:J,subject:X,idToken:$.id_token}}}async function Rf($,J){let Q=sJ($),Z=XZ.get(Q);if(Z)return Z;let W=`${Q}/.well-known/openid-configuration`,j=await fetch(W,{method:"GET",signal:AbortSignal.timeout(J)});if(!j.ok){let Y=`${Q}/oauth2/v1/token`;return XZ.set(Q,Y,Date.now(),mF),Y}let X=(await j.json()).token_endpoint||`${Q}/oauth2/v1/token`;return XZ.set(Q,X),X}function zf($){return{code:$.error,message:$.error_description}}async function dF($){let J=D4.get($.state);if(!J)throw Error("No PKCE verifier found for this state");D4.delete($.state);let Q=$.mode==="external"?$.config.external:$.config.internal,Z=await Rf(Q.idcsUrl,$.requestTimeoutMs),W=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:J.redirectUri,client_id:Q.clientId,code_verifier:J.verifier}),j=await fetch(Z,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:W,signal:AbortSignal.timeout($.requestTimeoutMs)}),f=await j.json();if(!j.ok){let Y=zf(f);throw new Z5(`Token exchange failed: ${j.status}${Y.message?` - ${Y.message}`:""}`,{status:j.status,errorCode:Y.code})}let X=T0(f.id_token);if(!f.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==J.nonce)throw Error("OIDC nonce verification failed");return Uf(f,$.mode)}function lF($){let J=$.mode==="external"?$.config.external:$.config.internal,Q=new URL(`${sJ(J.idcsUrl)}/oauth2/v1/authorize`);return Q.searchParams.set("client_id",J.clientId),Q.searchParams.set("response_type","code"),Q.searchParams.set("scope",J.scopes),Q.searchParams.set("code_challenge",$.challenge),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("redirect_uri",$.callbackUrl),Q.searchParams.set("state",$.state),Q.searchParams.set("nonce",$.nonce),Q.toString()}async function U4($){P1($.telemetry,"oca");let J=Df($.config),Q=Ff($.mode),Z=$.callbackPorts?.length?$.callbackPorts:hF,W=$.callbackPath??bF,j=$.requestTimeoutMs??Gf,f=await J1({ports:Z,callbackPath:W,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=f.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let Y=Xf(16),V=Xf(16),{verifier:H,challenge:B}=await aJ();cF(),D4.set(Y,{verifier:H,nonce:V,mode:Q,redirectUri:X,createdAt:Date.now()});let A=lF({callbackUrl:X,mode:Q,state:Y,nonce:V,challenge:B,config:J});$.callbacks.onAuth({url:A,instructions:"Continue the authentication process in your browser."});try{let K=await u2({waitForCallback:f.waitForCallback,cancelWait:f.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!==Y)throw Error("State mismatch");let D=await dF({code:G,state:R,mode:Q,config:J,requestTimeoutMs:j});return N1($.telemetry,"oca"),S1($.telemetry,{id:D.accountId,email:D.email,provider:"oca"}),D}catch(K){throw w1($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{f.close()}}async function W5($,J={}){let Q=Df(J.config),Z=J.requestTimeoutMs??Gf,W=$.metadata?.mode,j=W==="internal"||W==="external"?W:Ff(J.mode),f=j==="external"?Q.external:Q.internal,X=await Rf(f.idcsUrl,Z),Y=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:f.clientId}),V=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Y,signal:AbortSignal.timeout(Z)}),H=await V.json();if(!V.ok){let B=zf(H);throw new Z5(`Token refresh failed: ${V.status}${B.message?` - ${B.message}`:""}`,{status:V.status,errorCode:B.code})}return Uf(H,j,$)}async function R4($,J,Q){if(!$)return null;let Z=J?.refreshBufferMs??Q?.refreshBufferMs??kF,W=J?.retryableTokenGraceMs??Q?.retryableTokenGraceMs??IF;if(J?.forceRefresh!==!0&&!c2($,Z))return $;try{return await W5($,Q)}catch(f){if(f instanceof Z5&&f.isLikelyInvalidGrant())return e1(Q?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>W)return $;return null}}var j5="workos:";function pF($){let J=$.trim();return J.toLowerCase().startsWith(j5)?J:`${j5}${J}`}function rF($){let J=$.trim();return J.toLowerCase().startsWith(j5)?J.slice(j5.length):J}function iF($){let Q=T0($)?.exp;if(typeof Q==="number"&&Q>0)return Q*1000;return null}function nF($,J){let Q=$.auth?.expiresAt;if(typeof Q==="number"&&Number.isFinite(Q)&&Q>0)return Q;let Z=iF(J);if(Z)return Z;return Date.now()-1}function aF($,J){let Q=$.auth?.accessToken?.trim(),Z=$.auth?.refreshToken?.trim();if(!Q||!Z)return null;let W=J?.normalizeAccessToken?.(Q)??Q;if(!W)return null;return{access:W,refresh:Z,expires:nF($,W),accountId:$.auth?.accountId}}function sF($){let J=$.formatAccessToken?.($.credentials.access)??$.credentials.access,Q={...$.settings?.auth??{},accessToken:J,refreshToken:$.credentials.refresh,accountId:$.credentials.accountId,expiresAt:$.credentials.expires},Z={...$.settings??{provider:$.storageProviderId},provider:$.storageProviderId,auth:Q};if($.save!==!1)$.manager.saveProviderSettings(Z,{...$.setLastUsed===void 0?{}:{setLastUsed:$.setLastUsed},tokenSource:"oauth"});return Z}function YZ($){let J=$.storageProviderId??$.providerId;return{providerId:$.providerId,storageProviderId:J,getApiKey(Q){let Z=Q?.auth?.accessToken?.trim();if(Z)return $.formatAccessToken?.(Z)??Z;return Q?.apiKey?.trim()||Q?.auth?.apiKey?.trim()||void 0},login:$.login,refresh:$.refresh,saveCredentials(Q){return sF({...Q,storageProviderId:J,formatAccessToken:$.formatAccessToken})},isConfigured(Q){return!!Q?.auth?.accessToken},normalizeStoredAccessToken:$.normalizeStoredAccessToken}}function Of($){return YZ({providerId:$.providerId,storageProviderId:$.storageProviderId,formatAccessToken:pF,normalizeStoredAccessToken:rF,login:({settings:J,callbacks:Q,telemetry:Z})=>A4({apiBaseUrl:J?.baseUrl?.trim()||_f().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q,telemetry:Z}),refresh:({settings:J,credentials:Q,forceRefresh:Z,telemetry:W})=>K4(Q,{apiBaseUrl:J.baseUrl?.trim()||_f().apiBaseUrl,telemetry:W},{forceRefresh:Z})})}var oF=[Of({providerId:"cline"}),Of({providerId:"cline-pass",storageProviderId:"cline"}),YZ({providerId:"oca",login:({settings:$,callbacks:J,telemetry:Q})=>U4({mode:$?.oca?.mode,callbacks:J,telemetry:Q}),refresh:({settings:$,credentials:J,forceRefresh:Q,telemetry:Z})=>R4(J,{forceRefresh:Q,telemetry:Z},{mode:$.oca?.mode,telemetry:Z})}),YZ({providerId:"openai-codex",login:({callbacks:$,telemetry:J})=>G4({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput,telemetry:J}),refresh:({credentials:$,forceRefresh:J,telemetry:Q})=>F4($,{forceRefresh:J,telemetry:Q})})],tF=new Map(oF.map(($)=>[$.providerId,$]));function Z0($){return tF.get($.trim().toLowerCase())}function I$($){return Z0($)!==void 0}function VZ($){return Z0($)?.storageProviderId}function HZ($,J){let Q=Z0(J),Z=Q?.storageProviderId??J,W=$.getProviderSettings(Z);return Q?.getApiKey(W)??l2(J,W)}async function z4($,J,Q){let Z=Z0(J);if(!Z)throw Error(`Provider "${J}" does not support OAuth login`);let W=$.getProviderSettings(Z.storageProviderId),j=await Z.login({settings:W,callbacks:Q.callbacks,telemetry:Q.telemetry});return Z.saveCredentials({manager:$,settings:W,credentials:j})}function L4($,J){let Q=Z0($);if(!Q)return null;return aF(J,{normalizeAccessToken:Q.normalizeStoredAccessToken})}function x$($){let J=Z0($.providerId);if(!J)throw Error(`Provider "${$.providerId}" does not support OAuth credentials`);return J.saveCredentials({manager:$.manager,settings:$.settings,credentials:$.credentials,setLastUsed:$.setLastUsed,save:$.save})}function l2($,J){let Q=Z0($);if(Q)return Q.getApiKey(J);return J?.auth?.accessToken?.trim()||J?.apiKey?.trim()||J?.auth?.apiKey?.trim()||void 0}function BZ($,J){let Q=Z0($);if(!Q)return J.access;return Q.getApiKey({provider:Q.storageProviderId,auth:{accessToken:J.access}})??J.access}O0();var sf={};w(sf,{createContextCompactionPrepareTurn:()=>P4});import{createHandlerAsync as ZD}from"@cline/llms";import{estimateTokens as AZ}from"@cline/shared";var Pf=200000,KZ=0.9,Nf=16384,GZ=20000,Mf=1024,qf=2000,wf=2000,Sf=8;function Z$($,J){if($.length<=J)return $;return`${$.slice(0,J)}
47
47
  ...[truncated ${$.length-J} chars]`}function eF($){let J=FZ($);if(typeof J==="string")return J;return J.map((Q)=>{switch(Q.type){case"text":return Q.text;case"file":return`<file path="${Q.path}">
48
48
  ${Q.content}
49
49
  </file>`;case"image":return`[image:${Q.mediaType}]`;default:return""}}).join(`
50
- `)}function FZ($){if(typeof $==="string")return Z$($,Pf);return $.map((J)=>{switch(J.type){case"text":return{...J,text:Z$(J.text,Pf)};case"file":return{...J,content:Z$(J.content,Sf)};case"image":return J;default:return J}})}function $D($){return Object.entries($).map(([J,Q])=>`${J}=${JSON.stringify(Q)}`).join(", ")}function yf($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let J=[];for(let Q of $.content)switch(Q.type){case"text":J.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":J.push(`[Bot thinking]: ${Z$(Q.thinking,2000)}`);break;case"redacted_thinking":J.push("[Bot thinking]: [redacted]");break;case"tool_use":J.push(`[Bot tool calls]: ${Q.name}(${$D(Q.input)})`);break;case"tool_result":J.push(`[Tool result]: ${eF(Q.content)}`);break;case"file":J.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${Z$(Q.content,Sf)}`);break;case"image":J.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return J.join(`
51
- `)}function Ef($){return $.map(yf).join(`
50
+ `)}function FZ($){if(typeof $==="string")return Z$($,qf);return $.map((J)=>{switch(J.type){case"text":return{...J,text:Z$(J.text,qf)};case"file":return{...J,content:Z$(J.content,wf)};case"image":return J;default:return J}})}function $D($){return Object.entries($).map(([J,Q])=>`${J}=${JSON.stringify(Q)}`).join(", ")}function Cf($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let J=[];for(let Q of $.content)switch(Q.type){case"text":J.push(`[${$.role==="user"?"User":"Bot"}]: ${Q.text}`);break;case"thinking":J.push(`[Bot thinking]: ${Z$(Q.thinking,2000)}`);break;case"redacted_thinking":J.push("[Bot thinking]: [redacted]");break;case"tool_use":J.push(`[Bot tool calls]: ${Q.name}(${$D(Q.input)})`);break;case"tool_result":J.push(`[Tool result]: ${eF(Q.content)}`);break;case"file":J.push(`[${$.role==="user"?"User":"Bot"} file ${Q.path}]: ${Z$(Q.content,wf)}`);break;case"image":J.push(`[${$.role==="user"?"User":"Bot"} image]: ${Q.mediaType}`);break}return J.join(`
51
+ `)}function yf($){return $.map(Cf).join(`
52
52
 
53
- `).trim()}function bf(){let $=new WeakMap;return(J)=>{let Q=J,Z=$.get(Q);if(typeof Z==="number")return Z;let W;try{W=JSON.stringify(J)}catch{W=yf(J)}let j=AZ(W.length);return $.set(Q,j),j}}function T4($){return $.metadata?.kind==="compaction_summary"}function DZ($){if(!T4($))return;let J=$.metadata;if(!J)return;let Q=J.details;return{kind:"compaction_summary",summary:String(J.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[]},tokensBefore:Number(J.tokensBefore??0),generatedAt:Number(J.generatedAt??0)}}function JD($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((J)=>J.type==="tool_result")}function M4($){return $.role==="user"&&!JD($)&&!T4($)}function hf($){for(let J=0;J<$.length;J+=1)if(M4($[J]))return J;return-1}function f5($){for(let J=$.length-1;J>=0;J-=1)if(M4($[J]))return J;return 0}function kf($){for(let J=$.length-1;J>=0;J-=1)if($[J].role==="assistant")return J;return-1}function If($){for(let J=$.length-1;J>=0;J-=1)if(T4($[J]))return J;return-1}function xf($,J,Q){let Z=f5($);if(Z<=0)return 0;let W=0,j=$.length;for(let X=$.length-1;X>=0;X-=1)if(W+=Q($[X]),j=X,W>=J)break;if(j<=0)return 0;let f=Math.min(j,Z);while(f>0&&!M4($[f]))f-=1;return f}function O4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((J)=>O4(J));if($&&typeof $==="object"){let J=$,Q=[];for(let Z of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...O4(J[Z]));if(Array.isArray(J.files)){for(let Z of J.files)if(Z&&typeof Z==="object")Q.push(...O4(Z.path))}if(Array.isArray(J.file_paths))Q.push(...O4(J.file_paths));return Q}return[]}function _4($,J){let Q=new Set($);for(let Z of J){let W=Z.trim();if(!W)continue;Q.add(W)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function gf($){let J=[],Q=[];for(let Z of $){let W=DZ(Z);if(W){J=_4(J,W.details.readFiles),Q=_4(Q,W.details.modifiedFiles);continue}if(!Array.isArray(Z.content))continue;for(let j of Z.content){if(j.type==="file"){J=_4(J,[j.path]);continue}if(j.type!=="tool_use")continue;let f=O4(j.input);if(j.name==="read_files"){J=_4(J,f);continue}if(j.name==="editor"||j.name==="apply_patch")Q=_4(Q,f)}}return{readFiles:J,modifiedFiles:Q}}function QD($){let J=$.readFiles.length>0?$.readFiles.map((Z)=>`- ${Z}`).join(`
53
+ `).trim()}function Ef(){let $=new WeakMap;return(J)=>{let Q=J,Z=$.get(Q);if(typeof Z==="number")return Z;let W;try{W=JSON.stringify(J)}catch{W=Cf(J)}let j=AZ(W.length);return $.set(Q,j),j}}function T4($){return $.metadata?.kind==="compaction_summary"}function DZ($){if(!T4($))return;let J=$.metadata;if(!J)return;let Q=J.details;return{kind:"compaction_summary",summary:String(J.summary??""),details:{readFiles:Array.isArray(Q?.readFiles)?Q.readFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[],modifiedFiles:Array.isArray(Q?.modifiedFiles)?Q.modifiedFiles.filter((Z)=>typeof Z==="string").map((Z)=>Z.trim()).filter((Z)=>Z.length>0):[]},tokensBefore:Number(J.tokensBefore??0),generatedAt:Number(J.generatedAt??0)}}function JD($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((J)=>J.type==="tool_result")}function M4($){return $.role==="user"&&!JD($)&&!T4($)}function bf($){for(let J=0;J<$.length;J+=1)if(M4($[J]))return J;return-1}function f5($){for(let J=$.length-1;J>=0;J-=1)if(M4($[J]))return J;return 0}function hf($){for(let J=$.length-1;J>=0;J-=1)if($[J].role==="assistant")return J;return-1}function kf($){for(let J=$.length-1;J>=0;J-=1)if(T4($[J]))return J;return-1}function If($,J,Q){let Z=f5($);if(Z<=0)return 0;let W=0,j=$.length;for(let X=$.length-1;X>=0;X-=1)if(W+=Q($[X]),j=X,W>=J)break;if(j<=0)return 0;let f=Math.min(j,Z);while(f>0&&!M4($[f]))f-=1;return f}function O4($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((J)=>O4(J));if($&&typeof $==="object"){let J=$,Q=[];for(let Z of["path","file_path","target_file","new_file_path","old_file_path"])Q.push(...O4(J[Z]));if(Array.isArray(J.files)){for(let Z of J.files)if(Z&&typeof Z==="object")Q.push(...O4(Z.path))}if(Array.isArray(J.file_paths))Q.push(...O4(J.file_paths));return Q}return[]}function _4($,J){let Q=new Set($);for(let Z of J){let W=Z.trim();if(!W)continue;Q.add(W)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function xf($){let J=[],Q=[];for(let Z of $){let W=DZ(Z);if(W){J=_4(J,W.details.readFiles),Q=_4(Q,W.details.modifiedFiles);continue}if(!Array.isArray(Z.content))continue;for(let j of Z.content){if(j.type==="file"){J=_4(J,[j.path]);continue}if(j.type!=="tool_use")continue;let f=O4(j.input);if(j.name==="read_files"){J=_4(J,f);continue}if(j.name==="editor"||j.name==="apply_patch")Q=_4(Q,f)}}return{readFiles:J,modifiedFiles:Q}}function QD($){let J=$.readFiles.length>0?$.readFiles.map((Z)=>`- ${Z}`).join(`
54
54
  `):"- none",Q=$.modifiedFiles.length>0?$.modifiedFiles.map((Z)=>`- ${Z}`).join(`
55
55
  `):"- none";return`## Files
56
56
  Read:
57
57
  ${J}
58
58
  Modified:
59
- ${Q}`}function mf($,J){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
59
+ ${Q}`}function gf($,J){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
60
60
 
61
- ${QD(J)}`.trim()}function vf($){let J=[`Summarize this session for continuation. Be concise and factual.
61
+ ${QD(J)}`.trim()}function mf($){let J=[`Summarize this session for continuation. Be concise and factual.
62
62
 
63
63
  ## Goal
64
64
  One sentence: what is being built or fixed.
@@ -80,19 +80,19 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
80
80
  ${$.previousSummary.trim()}`);return J.push(`Conversation:
81
81
  ${$.conversationText||"(empty)"}`),J.join(`
82
82
 
83
- `)}function cf($){let J=$.summarizer,Q=(W)=>{if(W.providerId==="openai-codex"){let{maxOutputTokens:j,...f}=W;return{...f,thinking:!1}}return{...W,maxOutputTokens:W.maxOutputTokens??qf,thinking:!1}};if(!J)return Q($.activeProviderConfig);let Z=J.providerConfig?.providerId===J.providerId?J.providerConfig:void 0;return Q({...Z??{},providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey??Z?.apiKey,baseUrl:J.baseUrl??Z?.baseUrl,headers:J.headers??Z?.headers,knownModels:J.knownModels??Z?.knownModels,maxOutputTokens:J.maxOutputTokens??qf})}function uf($){return{role:"user",content:`Context summary:
83
+ `)}function vf($){let J=$.summarizer,Q=(W)=>{if(W.providerId==="openai-codex"){let{maxOutputTokens:j,...f}=W;return{...f,thinking:!1}}return{...W,maxOutputTokens:W.maxOutputTokens??Mf,thinking:!1}};if(!J)return Q($.activeProviderConfig);let Z=J.providerConfig?.providerId===J.providerId?J.providerConfig:void 0;return Q({...Z??{},providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey??Z?.apiKey,baseUrl:J.baseUrl??Z?.baseUrl,headers:J.headers??Z?.headers,knownModels:J.knownModels??Z?.knownModels,maxOutputTokens:J.maxOutputTokens??Mf})}function cf($){return{role:"user",content:`Context summary:
84
84
 
85
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function WD($){let J=await ZD($.providerConfig),Q="";for await(let Z of J.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Z.type==="text"){Q+=Z.text;continue}if(Z.type==="done"&&!Z.success&&Z.error)throw Error(Z.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function jD($){try{return JSON.stringify($).length}catch{return String($).length}}async function df($){let J=$.context.messages;if(J.length<2)return;let Q=xf(J,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=J.length)return;let Z=J.slice(0,Q),W=If(Z),j=W>=0?DZ(Z[W])?.summary:void 0,f=W>=0?Z.slice(W+1):Z;if(f.length===0)return;let X=gf(Z),Y=Ef(f),V=vf({previousSummary:j,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Z.length,newMessagesToFold:f.length,preservedMessages:J.length-Q,previousSummaryChars:j?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:AZ(V.length),newMessagesJsonChars:jD(f),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let H=await WD({providerConfig:cf({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!H.trim())return;let B=mf(H,X),A=J.reduce((R,D)=>R+$.estimateMessageTokens(D),0),K=[uf({summary:B,fileOps:X,tokensBefore:A}),...J.slice(Q)],G=K.reduce((R,D)=>R+$.estimateMessageTokens(D),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:J.length,messagesAfter:K.length,messagesSummarized:Q,messagesPreserved:J.length-Q,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function rf($){if(T4($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let J=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(J.length===0)return;return{...$,content:J.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:FZ(Q.content)}:Q)}}function q4($,J){return $.reduce((Q,Z)=>Q+J(Z),0)}function lf($,J){let Q=Math.max(1,J),Z=Math.max(16,Q*4);if(typeof $.content==="string"){let f=Z$($.content,Z).trim();return{...$,content:f||"..."}}let W=Z,j=$.content.map((f)=>{if(f.type!=="text"||W<=0)return f;let X=Z$(f.text,W).trim();return W-=X.length,{...f,text:X||"..."}});return{...$,content:j}}function fD($,J){let Q=hf($),Z=f5($),W=kf($),j=[];for(let f=0;f<$.length;f+=1){let X=rf($[f]);if(!X)continue;j.push({index:f,message:X,estimatedTokens:J(X),isFirstUser:f===Q,isLastUser:f===Z,isLastAssistant:f===W})}return j}function pf($,J,Q,Z){let W=$[J];W.message=Q,W.estimatedTokens=Z(Q)}function XD($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_use")J.add(Q.id);return J}function YD($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_result")J.add(Q.tool_use_id);return J}function nf($){return new Set([...XD($.message),...YD($.message)])}function VD($){let J=new Map;for(let Q=0;Q<$.length;Q+=1)for(let Z of nf($[Q])){let W=J.get(Z);if(W)W.add(Q);else J.set(Z,new Set([Q]))}return J}function HD($,J){let Q=VD($),Z=new Set,W=[J];while(W.length>0){let j=W.shift();if(j===void 0||Z.has(j))continue;Z.add(j);for(let f of nf($[j]))for(let X of Q.get(f)??[])if(!Z.has(X))W.push(X)}return Z}function X5($,J,Q,Z){let W=q4($.map((j)=>j.message),Z);for(let j=0;j<$.length&&W>Q;){if(!J($[j])){j+=1;continue}let f=HD($,j);W-=Array.from(f).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(f).sort((Y,V)=>V-Y))$.splice(X,1)}}function BD($,J,Q){let Z=q4($.map((j)=>j.message),Q);if(Z<=J)return;for(let j=$.length-1;j>=0&&Z>J;j-=1){let f=$[j];if(f.isFirstUser)continue;let X=Math.max(Cf,f.estimatedTokens-(Z-J));if(X>=f.estimatedTokens)continue;pf($,j,lf(f.message,X),Q),Z=q4($.map((Y)=>Y.message),Q)}if(Z<=J)return;let W=$.findIndex((j)=>j.isFirstUser);if(W>=0){let j=Math.max(1,$[W].estimatedTokens-(Z-J));pf($,W,lf($[W].message,j),Q)}}function AD($,J){return JSON.stringify($)!==JSON.stringify(J)}function KD($){let J=f5($);if(J<0||J===0&&!M4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,J),protectedTail:$.slice(J)}}function af($){let J=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:Q,protectedTail:Z}=KD($.context.messages);if(Q.length===0)return;let W=fD(Q,$.estimateMessageTokens);if(W.length===0)return;X5(W,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,J,$.estimateMessageTokens),BD(W,J,$.estimateMessageTokens);let j=[...W.map((Y)=>Y.message),...Z];if(!AD($.context.messages,j))return;let f=q4([...Q.map((Y)=>rf(Y)??Y),...Z],$.estimateMessageTokens),X=q4(j,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:j.length,messagesRemoved:$.context.messages.length-j.length,tokensBefore:f,tokensAfter:X,targetTokens:J,maxInputTokens:$.context.maxInputTokens}),{messages:j}}function sf($){try{return JSON.stringify($).length}catch{return String($).length}}function GD($){let J=0,Q=0,Z=0;for(let W of $){if(!Array.isArray(W.content))continue;for(let j of W.content){if(j.type!=="tool_result")continue;let f=sf(j.content);J+=1,Q+=f,Z=Math.max(Z,f)}}return{toolResultCount:J,toolResultSerializedChars:Q,maxToolResultSerializedChars:Z}}var FD={basic:({context:$,estimateMessageTokens:J,logger:Q})=>af({context:$,estimateMessageTokens:J,logger:Q}),agentic:({context:$,providerConfig:J,compaction:Q,mode:Z,estimateMessageTokens:W,logger:j})=>df({context:$,providerConfig:J,summarizer:Q?.summarizer,preserveRecentTokens:Z==="manual"?Math.min(Q?.preserveRecentTokens??GZ,$.triggerTokens):Q?.preserveRecentTokens??GZ,estimateMessageTokens:W,logger:j})};function DD($){if(typeof $.config.reserveTokens==="number"){let Z=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Z);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Z=Math.max(0,Math.min($.maxInputTokens-wf,$.maxInputTokens*KZ));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}let J=$.config.thresholdRatio??KZ,Q=$.maxInputTokens*J;return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:J}}function UD($){let J=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,J)),Z=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function P4($,J={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let Z=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},W=bf(),j=Q?.strategy??"basic",f=FD[j],X=J.mode??"auto",Y=Q?.compact?"custom":j;return async(V)=>{let H=V.apiMessages.reduce((z,P)=>z+W(P),0),B=Q?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??Nf;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)return;let A=DD({inputTokens:H,maxInputTokens:B,config:{reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:j,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:H,maxInputTokens:B,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:sf(V.apiMessages),...GD(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?UD({inputTokens:H,maxInputTokens:B,autoTriggerTokens:A.triggerTokens,manualTargetRatio:J.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:B,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:B>0?H/B:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:B});let D=V.messages.length,U=Date.now(),F=Q?.compact?await Q.compact(G):await f({context:G,providerConfig:{...Z,abortSignal:V.abortSignal},compaction:Q,mode:X,estimateMessageTokens:W,logger:$.logger}),O=Date.now()-U,T=$.sessionId??V.conversationId,L={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((P,S)=>P+W(S),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:B,inputTokens:H,afterTokens:z,tokensSaved:H-z,utilizationBefore:`${(H/B*100).toFixed(1)}%`,utilizationAfter:`${(z/B*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length}),iJ($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length,tokensBefore:H,tokensAfter:z,tokensSaved:H-z,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L})}else nJ($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:H,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L});return F}}var wY={};w(wY,{zodToJsonSchema:()=>Kz,validateWithZod:()=>Az,resolveToolRoutingConfig:()=>t2,resolveToolPresetName:()=>h1,resolveCoreSelectedToolIds:()=>w5,getCoreHeadlessToolNames:()=>a4,getCoreDefaultEnabledToolIds:()=>N5,getCoreBuiltinToolCatalog:()=>i$,getCoreAcpToolNames:()=>S5,createWindowsShellTool:()=>PZ,createWebFetchTool:()=>NZ,createWebFetchExecutor:()=>d4,createToolPoliciesWithPreset:()=>G5,createSubmitAndExitTool:()=>yZ,createSkillsTool:()=>v$,createSearchTool:()=>MZ,createSearchExecutor:()=>u4,createReadFilesTool:()=>TZ,createFileReadExecutor:()=>c4,createEditorTool:()=>SZ,createEditorExecutor:()=>v4,createDefaultToolsWithPreset:()=>F5,createDefaultTools:()=>X$,createDefaultExecutors:()=>s2,createBuiltinTools:()=>n$,createBashTool:()=>qZ,createBashExecutor:()=>g4,createAskQuestionTool:()=>CZ,createApplyPatchTool:()=>wZ,createApplyPatchExecutor:()=>m4,WebFetchRequestSchema:()=>zZ,ToolPresets:()=>c0,TEAM_TOOL_NAMES:()=>J8,SubmitInputSchema:()=>k4,SkillsInputSchema:()=>b4,SearchCodebaseInputSchema:()=>S4,RunCommandsInputSchema:()=>p2,ReadFilesInputSchema:()=>w4,ReadFileRequestSchema:()=>C1,FetchWebContentInputSchema:()=>C4,EditFileInputSchema:()=>y4,DefaultToolNames:()=>K0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>o2,AskQuestionInputSchema:()=>h4,ApplyPatchInputSchema:()=>E4,ALL_DEFAULT_TOOL_NAMES:()=>W$});import{validateWithZod as Az,zodToJsonSchema as Kz}from"@cline/shared";var K0={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"},W$=[K0.READ_FILES,K0.SEARCH_CODEBASE,K0.RUN_COMMANDS,K0.FETCH_WEB_CONTENT,K0.APPLY_PATCH,K0.EDITOR,K0.SKILLS,K0.ASK,K0.SUBMIT_AND_EXIT];O0();import{createTool as y1,validateWithZod as E1,zodToJsonSchema as H1}from"@cline/shared";var tf="__clineInternalTelemetry";function ef($){let J=$?.__clineInternalTelemetry;return J&&typeof J==="object"&&"capture"in J&&typeof J.capture==="function"?J:void 0}import{spawn as HX}from"node:child_process";import{StringDecoder as LD}from"node:string_decoder";import{getDefaultShell as _D,getShellArgs as OD}from"@cline/shared";import{validateWithZod as RD}from"@cline/shared";import{z as _}from"zod";var j$=6000,N4=_.string().describe("The absolute file path of a text file to read content from"),$X=_.object({start_line:_.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:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),C1=_.object({path:N4,start_line:$X.shape.start_line,end_line:$X.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),w4=_.object({files:_.array(C1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),JX=_.union([w4,C1,_.array(C1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([N4,C1]))}),_.object({files:C1}),_.object({files:N4}),_.object({file_paths:_.array(N4)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([N4,C1]))}),_.object({paths:C1}),_.object({paths:_.string()})]),S4=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),QX=_.union([S4,_.array(_.string()),_.string(),_.object({queries:_.string()})]),g$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${j$*2} characters) to avoid timeouts.`),p2=_.object({commands:_.array(g$).describe("Array of shell commands to execute")}),ZX=_.union([p2,_.object({commands:g$}),_.object({command:g$}),_.object({cmd:g$}),_.array(_.string()),_.string()]),UZ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),WX=_.union([g$,UZ]),RZ=_.object({commands:_.array(WX).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.")}),jX=_.union([p2,RZ,_.object({commands:WX}),_.array(UZ),UZ,_.object({command:g$}),_.object({cmd:g$}),_.array(_.string()),_.string()]),zZ=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),C4=_.object({requests:_.array(zZ).describe("Array of the URLs for the web fetch requests")}),y4=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.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 ${j$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.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 ${j$} 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:_.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."),E4=_.object({input:_.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."),fX=_.union([E4,_.string()]),b4=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),h4=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),k4=_.object({summary:_.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:_.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.
85
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function WD($){let J=await ZD($.providerConfig),Q="";for await(let Z of J.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Z.type==="text"){Q+=Z.text;continue}if(Z.type==="done"&&!Z.success&&Z.error)throw Error(Z.error)}return $.logger?.debug("Generated compaction summary",{outputChars:Q.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),Q.trim()}function jD($){try{return JSON.stringify($).length}catch{return String($).length}}async function uf($){let J=$.context.messages;if(J.length<2)return;let Q=If(J,$.preserveRecentTokens,$.estimateMessageTokens);if(Q<=0||Q>=J.length)return;let Z=J.slice(0,Q),W=kf(Z),j=W>=0?DZ(Z[W])?.summary:void 0,f=W>=0?Z.slice(W+1):Z;if(f.length===0)return;let X=xf(Z),Y=yf(f),V=mf({previousSummary:j,conversationText:Y,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Z.length,newMessagesToFold:f.length,preservedMessages:J.length-Q,previousSummaryChars:j?.length??0,conversationTextChars:Y.length,summaryRequestChars:V.length,summaryRequestEstimatedTokens:AZ(V.length),newMessagesJsonChars:jD(f),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let H=await WD({providerConfig:vf({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:V,logger:$.logger});if(!H.trim())return;let B=gf(H,X),A=J.reduce((R,D)=>R+$.estimateMessageTokens(D),0),K=[cf({summary:B,fileOps:X,tokensBefore:A}),...J.slice(Q)],G=K.reduce((R,D)=>R+$.estimateMessageTokens(D),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:J.length,messagesAfter:K.length,messagesSummarized:Q,messagesPreserved:J.length-Q,tokensBefore:A,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function pf($){if(T4($))return;if(typeof $.content==="string"){let Q=$.content.trim();return Q?{...$,content:Q}:void 0}let J=$.content.filter((Q)=>Q.type!=="text"||Q.text.trim());if(J.length===0)return;return{...$,content:J.map((Q)=>Q.type==="text"?{...Q,text:Q.text.trim()}:Q.type==="tool_result"?{...Q,content:FZ(Q.content)}:Q)}}function q4($,J){return $.reduce((Q,Z)=>Q+J(Z),0)}function df($,J){let Q=Math.max(1,J),Z=Math.max(16,Q*4);if(typeof $.content==="string"){let f=Z$($.content,Z).trim();return{...$,content:f||"..."}}let W=Z,j=$.content.map((f)=>{if(f.type!=="text"||W<=0)return f;let X=Z$(f.text,W).trim();return W-=X.length,{...f,text:X||"..."}});return{...$,content:j}}function fD($,J){let Q=bf($),Z=f5($),W=hf($),j=[];for(let f=0;f<$.length;f+=1){let X=pf($[f]);if(!X)continue;j.push({index:f,message:X,estimatedTokens:J(X),isFirstUser:f===Q,isLastUser:f===Z,isLastAssistant:f===W})}return j}function lf($,J,Q,Z){let W=$[J];W.message=Q,W.estimatedTokens=Z(Q)}function XD($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_use")J.add(Q.id);return J}function YD($){let J=new Set;if(!Array.isArray($.content))return J;for(let Q of $.content)if(Q.type==="tool_result")J.add(Q.tool_use_id);return J}function rf($){return new Set([...XD($.message),...YD($.message)])}function VD($){let J=new Map;for(let Q=0;Q<$.length;Q+=1)for(let Z of rf($[Q])){let W=J.get(Z);if(W)W.add(Q);else J.set(Z,new Set([Q]))}return J}function HD($,J){let Q=VD($),Z=new Set,W=[J];while(W.length>0){let j=W.shift();if(j===void 0||Z.has(j))continue;Z.add(j);for(let f of rf($[j]))for(let X of Q.get(f)??[])if(!Z.has(X))W.push(X)}return Z}function X5($,J,Q,Z){let W=q4($.map((j)=>j.message),Z);for(let j=0;j<$.length&&W>Q;){if(!J($[j])){j+=1;continue}let f=HD($,j);W-=Array.from(f).reduce((X,Y)=>X+$[Y].estimatedTokens,0);for(let X of Array.from(f).sort((Y,V)=>V-Y))$.splice(X,1)}}function BD($,J,Q){let Z=q4($.map((j)=>j.message),Q);if(Z<=J)return;for(let j=$.length-1;j>=0&&Z>J;j-=1){let f=$[j];if(f.isFirstUser)continue;let X=Math.max(Sf,f.estimatedTokens-(Z-J));if(X>=f.estimatedTokens)continue;lf($,j,df(f.message,X),Q),Z=q4($.map((Y)=>Y.message),Q)}if(Z<=J)return;let W=$.findIndex((j)=>j.isFirstUser);if(W>=0){let j=Math.max(1,$[W].estimatedTokens-(Z-J));lf($,W,df($[W].message,j),Q)}}function AD($,J){return JSON.stringify($)!==JSON.stringify(J)}function KD($){let J=f5($);if(J<0||J===0&&!M4($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,J),protectedTail:$.slice(J)}}function nf($){let J=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:Q,protectedTail:Z}=KD($.context.messages);if(Q.length===0)return;let W=fD(Q,$.estimateMessageTokens);if(W.length===0)return;X5(W,(Y)=>Y.message.role==="assistant"&&!Y.isLastAssistant,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="user"&&!Y.isFirstUser&&!Y.isLastUser,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="assistant"&&Y.isLastAssistant,J,$.estimateMessageTokens),X5(W,(Y)=>Y.message.role==="user"&&Y.isLastUser&&!Y.isFirstUser,J,$.estimateMessageTokens),BD(W,J,$.estimateMessageTokens);let j=[...W.map((Y)=>Y.message),...Z];if(!AD($.context.messages,j))return;let f=q4([...Q.map((Y)=>pf(Y)??Y),...Z],$.estimateMessageTokens),X=q4(j,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:j.length,messagesRemoved:$.context.messages.length-j.length,tokensBefore:f,tokensAfter:X,targetTokens:J,maxInputTokens:$.context.maxInputTokens}),{messages:j}}function af($){try{return JSON.stringify($).length}catch{return String($).length}}function GD($){let J=0,Q=0,Z=0;for(let W of $){if(!Array.isArray(W.content))continue;for(let j of W.content){if(j.type!=="tool_result")continue;let f=af(j.content);J+=1,Q+=f,Z=Math.max(Z,f)}}return{toolResultCount:J,toolResultSerializedChars:Q,maxToolResultSerializedChars:Z}}var FD={basic:({context:$,estimateMessageTokens:J,logger:Q})=>nf({context:$,estimateMessageTokens:J,logger:Q}),agentic:({context:$,providerConfig:J,compaction:Q,mode:Z,estimateMessageTokens:W,logger:j})=>uf({context:$,providerConfig:J,summarizer:Q?.summarizer,preserveRecentTokens:Z==="manual"?Math.min(Q?.preserveRecentTokens??GZ,$.triggerTokens):Q?.preserveRecentTokens??GZ,estimateMessageTokens:W,logger:j})};function DD($){if(typeof $.config.reserveTokens==="number"){let Z=Math.max(0,$.config.reserveTokens),W=Math.max(0,$.maxInputTokens-Z);return{shouldCompact:$.inputTokens>W,triggerTokens:W,thresholdRatio:$.maxInputTokens>0?W/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Z=Math.max(0,Math.min($.maxInputTokens-Nf,$.maxInputTokens*KZ));return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}let J=$.config.thresholdRatio??KZ,Q=$.maxInputTokens*J;return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:J}}function UD($){let J=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,Q=Math.min(0.95,Math.max(0.05,J)),Z=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*Q)));return{triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}function P4($,J={}){let Q=$.compaction;if(Q?.enabled!==!0)return;let Z=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},W=Ef(),j=Q?.strategy??"basic",f=FD[j],X=J.mode??"auto",Y=Q?.compact?"custom":j;return async(V)=>{let H=V.apiMessages.reduce((z,P)=>z+W(P),0),B=Q?.maxInputTokens??V.model.info?.maxInputTokens??V.model.info?.contextWindow??Pf;if(typeof B!=="number"||!Number.isFinite(B)||B<=0)return;let A=DD({inputTokens:H,maxInputTokens:B,config:{reserveTokens:Q?.reserveTokens,thresholdRatio:Q?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:j,iteration:V.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:H,maxInputTokens:B,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:V.messages.length,apiMessageCount:V.apiMessages.length,apiMessagesJsonChars:af(V.apiMessages),...GD(V.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let K=X==="manual"?UD({inputTokens:H,maxInputTokens:B,autoTriggerTokens:A.triggerTokens,manualTargetRatio:J.manualTargetRatio}):A,G={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId,iteration:V.iteration,messages:V.messages,model:V.model,maxInputTokens:B,triggerTokens:K.triggerTokens,thresholdRatio:K.thresholdRatio,utilizationRatio:B>0?H/B:0},R=X==="manual"?"manual_compaction":"auto_compaction";V.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:R,reason:R,iteration:V.iteration,triggerTokens:K.triggerTokens,maxInputTokens:B});let D=V.messages.length,U=Date.now(),F=Q?.compact?await Q.compact(G):await f({context:G,providerConfig:{...Z,abortSignal:V.abortSignal},compaction:Q,mode:X,estimateMessageTokens:W,logger:$.logger}),O=Date.now()-U,T=$.sessionId??V.conversationId,L={agentId:V.agentId,conversationId:V.conversationId,parentAgentId:V.parentAgentId??void 0};if(F?.messages){let z=F.messages.reduce((P,S)=>P+W(S),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:j,maxInputTokens:B,inputTokens:H,afterTokens:z,tokensSaved:H-z,utilizationBefore:`${(H/B*100).toFixed(1)}%`,utilizationAfter:`${(z/B*100).toFixed(1)}%`,thresholdTrigger:`${(K.thresholdRatio*100).toFixed(1)}%`,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length}),iJ($.telemetry,{ulid:T,strategy:Y,mode:X,messagesBefore:D,messagesAfter:F.messages.length,messagesRemoved:D-F.messages.length,tokensBefore:H,tokensAfter:z,tokensSaved:H-z,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L})}else nJ($.telemetry,{ulid:T,strategy:Y,mode:X,reason:"no_result",tokensBefore:H,triggerTokens:K.triggerTokens,maxInputTokens:B,thresholdRatio:K.thresholdRatio,durationMs:O,provider:$.providerId,modelId:$.modelId,...L});return F}}var NY={};w(NY,{zodToJsonSchema:()=>Kz,validateWithZod:()=>Az,resolveToolRoutingConfig:()=>t2,resolveToolPresetName:()=>h1,resolveCoreSelectedToolIds:()=>w5,getCoreHeadlessToolNames:()=>a4,getCoreDefaultEnabledToolIds:()=>N5,getCoreBuiltinToolCatalog:()=>i$,getCoreAcpToolNames:()=>S5,createWindowsShellTool:()=>PZ,createWebFetchTool:()=>NZ,createWebFetchExecutor:()=>d4,createToolPoliciesWithPreset:()=>G5,createSubmitAndExitTool:()=>yZ,createSkillsTool:()=>v$,createSearchTool:()=>MZ,createSearchExecutor:()=>u4,createReadFilesTool:()=>TZ,createFileReadExecutor:()=>c4,createEditorTool:()=>SZ,createEditorExecutor:()=>v4,createDefaultToolsWithPreset:()=>F5,createDefaultTools:()=>X$,createDefaultExecutors:()=>s2,createBuiltinTools:()=>n$,createBashTool:()=>qZ,createBashExecutor:()=>g4,createAskQuestionTool:()=>CZ,createApplyPatchTool:()=>wZ,createApplyPatchExecutor:()=>m4,WebFetchRequestSchema:()=>zZ,ToolPresets:()=>c0,TEAM_TOOL_NAMES:()=>J8,SubmitInputSchema:()=>k4,SkillsInputSchema:()=>b4,SearchCodebaseInputSchema:()=>S4,RunCommandsInputSchema:()=>p2,ReadFilesInputSchema:()=>w4,ReadFileRequestSchema:()=>C1,FetchWebContentInputSchema:()=>C4,EditFileInputSchema:()=>y4,DefaultToolNames:()=>K0,DEFAULT_MODEL_TOOL_ROUTING_RULES:()=>o2,AskQuestionInputSchema:()=>h4,ApplyPatchInputSchema:()=>E4,ALL_DEFAULT_TOOL_NAMES:()=>W$});import{validateWithZod as Az,zodToJsonSchema as Kz}from"@cline/shared";var K0={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"},W$=[K0.READ_FILES,K0.SEARCH_CODEBASE,K0.RUN_COMMANDS,K0.FETCH_WEB_CONTENT,K0.APPLY_PATCH,K0.EDITOR,K0.SKILLS,K0.ASK,K0.SUBMIT_AND_EXIT];O0();import{createTool as y1,validateWithZod as E1,zodToJsonSchema as H1}from"@cline/shared";var of="__clineInternalTelemetry";function tf($){let J=$?.__clineInternalTelemetry;return J&&typeof J==="object"&&"capture"in J&&typeof J.capture==="function"?J:void 0}import{spawn as VX}from"node:child_process";import{StringDecoder as LD}from"node:string_decoder";import{getDefaultShell as _D,getShellArgs as OD}from"@cline/shared";import{validateWithZod as RD}from"@cline/shared";import{z as _}from"zod";var j$=6000,N4=_.string().describe("The absolute file path of a text file to read content from"),ef=_.object({start_line:_.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:_.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit to read to the end of the file or the read cap, whichever comes first")}).describe("Optional inclusive one-based file line range"),C1=_.object({path:N4,start_line:ef.shape.start_line,end_line:ef.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),w4=_.object({files:_.array(C1).describe("Array of file read requests. Omit start_line/end_line or set them to null to read from the start; provide integers to return only that inclusive one-based line range. Reads are capped, so page through long files with start_line/end_line. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),$X=_.union([w4,C1,_.array(C1),_.array(_.string()),_.string(),_.object({files:_.array(_.union([N4,C1]))}),_.object({files:C1}),_.object({files:N4}),_.object({file_paths:_.array(N4)}),_.object({file_paths:_.string()}),_.object({paths:_.array(_.union([N4,C1]))}),_.object({paths:C1}),_.object({paths:_.string()})]),S4=_.object({queries:_.array(_.string()).describe("Array of regex search queries to execute")}),JX=_.union([S4,_.array(_.string()),_.string(),_.object({queries:_.string()})]),g$=_.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${j$*2} characters) to avoid timeouts.`),p2=_.object({commands:_.array(g$).describe("Array of shell commands to execute")}),QX=_.union([p2,_.object({commands:g$}),_.object({command:g$}),_.object({cmd:g$}),_.array(_.string()),_.string()]),UZ=_.object({command:_.string().min(1).describe("The executable to run directly without shell parsing."),args:_.array(_.string()).optional().describe("Optional argv list passed directly to the executable.")}),ZX=_.union([g$,UZ]),RZ=_.object({commands:_.array(ZX).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.")}),WX=_.union([p2,RZ,_.object({commands:ZX}),_.array(UZ),UZ,_.object({command:g$}),_.object({cmd:g$}),_.array(_.string()),_.string()]),zZ=_.object({url:_.string().describe("The URL to fetch"),prompt:_.string().min(2).describe("Analysis prompt for the fetched content")}),C4=_.object({requests:_.array(zZ).describe("Array of the URLs for the web fetch requests")}),y4=_.object({path:_.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:_.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 ${j$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:_.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 ${j$} 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:_.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."),E4=_.object({input:_.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."),jX=_.union([E4,_.string()]),b4=_.object({skill:_.string().min(1).describe("Name of the skill to execute."),args:_.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),h4=_.object({question:_.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:_.array(_.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),k4=_.object({summary:_.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:_.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.
86
86
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
87
- 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 f$($){if($ instanceof Error)return $.message;return String($)}function XX($){if(typeof $.old_text==="string"&&$.old_text.length>j$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${j$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>j$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${j$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class m$ extends Error{timeoutMs;constructor($,J){super($);this.name="TimeoutError",this.timeoutMs=J}}function V1($,J,Q){return Promise.race([$,new Promise((Z,W)=>{setTimeout(()=>W(new m$(Q,J)),J)})])}function Y5($){let{path:J,start_line:Q,end_line:Z}=$;if(Q==null&&Z==null)return J;return`${J}:${Q??1}-${Z??"EOF"}`}function YX($){let{start_line:J,end_line:Q}=$;if(J==null||Q==null||J<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${J}, end_line: ${Q})`}function VX($){let J=RD(jX,$);if(typeof J==="string")return[J];if(Array.isArray(J))return J;if("commands"in J)return Array.isArray(J.commands)?J.commands:[J.commands];if("command"in J)return"args"in J?[J]:[J.command];if("cmd"in J)return[J.cmd];return[J]}function zD($){if(typeof $==="string")return $;let J=$.args??[];if(J.length===0)return $.command;let Q=J.map((Z)=>/[\s"]/u.test(Z)?JSON.stringify(Z):Z);return`${$.command} ${Q.join(" ")}`}var LZ=200;function _Z($){let J=zD($);if(J.length<=LZ)return J;let Q=J.length-LZ;return`${J.slice(0,LZ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var I4=48000,r2=2000,OZ=2000,V5=48000,i2=48000;class x4 extends Error{exitCode;output;constructor($,J){super(`Command exited with code ${$}`);this.exitCode=$;this.output=J;this.name="CommandExitError"}}function BX($){let J=Math.ceil($/2),Q=Math.max(1,$-J),Z=new LD("utf8"),W="",j="",f=0,X=(Y)=>{if(!Y)return;f+=Y.length;let V=J-W.length;if(V>0){W+=Y.slice(0,V),j=(j+Y.slice(V)).slice(-Q);return}j=(j+Y).slice(-Q)};return{append(Y){X(Z.write(Y))},snapshot(){return X(Z.end()),{text:W+j,totalChars:f,dropped:f>W.length+j.length}}}}function AX($,J,Q){let Z=Math.ceil(J/2),W=Math.max(1,J-Z);return`${$.slice(0,Z)}
87
+ 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 f$($){if($ instanceof Error)return $.message;return String($)}function fX($){if(typeof $.old_text==="string"&&$.old_text.length>j$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${j$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>j$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${j$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}class m$ extends Error{timeoutMs;constructor($,J){super($);this.name="TimeoutError",this.timeoutMs=J}}function V1($,J,Q){return Promise.race([$,new Promise((Z,W)=>{setTimeout(()=>W(new m$(Q,J)),J)})])}function Y5($){let{path:J,start_line:Q,end_line:Z}=$;if(Q==null&&Z==null)return J;return`${J}:${Q??1}-${Z??"EOF"}`}function XX($){let{start_line:J,end_line:Q}=$;if(J==null||Q==null||J<=Q)return null;return`start_line must be less than or equal to end_line (received start_line: ${J}, end_line: ${Q})`}function YX($){let J=RD(WX,$);if(typeof J==="string")return[J];if(Array.isArray(J))return J;if("commands"in J)return Array.isArray(J.commands)?J.commands:[J.commands];if("command"in J)return"args"in J?[J]:[J.command];if("cmd"in J)return[J.cmd];return[J]}function zD($){if(typeof $==="string")return $;let J=$.args??[];if(J.length===0)return $.command;let Q=J.map((Z)=>/[\s"]/u.test(Z)?JSON.stringify(Z):Z);return`${$.command} ${Q.join(" ")}`}var LZ=200;function _Z($){let J=zD($);if(J.length<=LZ)return J;let Q=J.length-LZ;return`${J.slice(0,LZ)} ... [command truncated: ${Q} more chars; full command is in the tool call input]`}var I4=48000,r2=2000,OZ=2000,V5=48000,i2=48000;class x4 extends Error{exitCode;output;constructor($,J){super(`Command exited with code ${$}`);this.exitCode=$;this.output=J;this.name="CommandExitError"}}function HX($){let J=Math.ceil($/2),Q=Math.max(1,$-J),Z=new LD("utf8"),W="",j="",f=0,X=(Y)=>{if(!Y)return;f+=Y.length;let V=J-W.length;if(V>0){W+=Y.slice(0,V),j=(j+Y.slice(V)).slice(-Q);return}j=(j+Y).slice(-Q)};return{append(Y){X(Z.write(Y))},snapshot(){return X(Z.end()),{text:W+j,totalChars:f,dropped:f>W.length+j.length}}}}function BX($,J,Q){let Z=Math.ceil(J/2),W=Math.max(1,J-Z);return`${$.slice(0,Z)}
88
88
  [... output truncated: ${Q} chars total. Refine the command (grep, head, tail) to view the elided middle ...]
89
- `+$.slice(-W)}function TD($,J,Q,Z,W){return new Promise((j,f)=>{let X=process.platform==="win32",Y=HX($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,H=BX(Z),B=BX(Z),A=!1,K=!1,G=(T)=>{if(K)return;K=!0,T()},R=()=>{if(!V)return;if(X){HX("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},D=(T)=>{A=!0,R(),G(()=>f(T))},U=setTimeout(()=>D(new m$(`Command timed out after ${Q}ms`,Q)),Q),F=()=>D(Error("Command was aborted"));if(J.signal)J.signal.addEventListener("abort",F);let O=()=>{clearTimeout(U),J.signal?.removeEventListener("abort",F)};Y.stdout?.on("data",(T)=>{H.append(T)}),Y.stderr?.on("data",(T)=>{B.append(T)}),Y.on("close",(T)=>{if(O(),A)return;let L=H.snapshot(),z=B.snapshot();if(T!==0){let P=T??1,S=W?L.text+(z.text?`
89
+ `+$.slice(-W)}function TD($,J,Q,Z,W){return new Promise((j,f)=>{let X=process.platform==="win32",Y=VX($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X,windowsHide:!0}),V=Y.pid,H=HX(Z),B=HX(Z),A=!1,K=!1,G=(T)=>{if(K)return;K=!0,T()},R=()=>{if(!V)return;if(X){VX("taskkill",["/pid",String(V),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-V,"SIGKILL")}catch{Y.kill("SIGKILL")}},D=(T)=>{A=!0,R(),G(()=>f(T))},U=setTimeout(()=>D(new m$(`Command timed out after ${Q}ms`,Q)),Q),F=()=>D(Error("Command was aborted"));if(J.signal)J.signal.addEventListener("abort",F);let O=()=>{clearTimeout(U),J.signal?.removeEventListener("abort",F)};Y.stdout?.on("data",(T)=>{H.append(T)}),Y.stderr?.on("data",(T)=>{B.append(T)}),Y.on("close",(T)=>{if(O(),A)return;let L=H.snapshot(),z=B.snapshot();if(T!==0){let P=T??1,S=W?L.text+(z.text?`
90
90
  [stderr]
91
- ${z.text}`:""):L.text,b=L.dropped||W&&z.dropped,u=W?L.totalChars+z.totalChars:L.totalChars;if(b||S.length>Z)S=AX(S,Z,u);let o=S.length>0?`[Command exited with code ${P}]
91
+ ${z.text}`:""):L.text,b=L.dropped||W&&z.dropped,u=W?L.totalChars+z.totalChars:L.totalChars;if(b||S.length>Z)S=BX(S,Z,u);let o=S.length>0?`[Command exited with code ${P}]
92
92
  ${S}`:`[Command exited with code ${P}]`;G(()=>f(new x4(P,o)))}else{let P=W?L.text+(z.text?`
93
93
  [stderr]
94
- ${z.text}`:""):L.text;if(L.dropped||W&&z.dropped||P.length>Z){let b=W?L.totalChars+z.totalChars:L.totalChars;P=AX(P,Z,b)}G(()=>j(P))}}),Y.on("error",(T)=>{O(),G(()=>f(Error(`Failed to execute command: ${T.message}`)))})})}function g4($={}){let{shell:J=_D(process.platform),timeoutMs:Q=30000,env:Z={},combineOutput:W=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??I4;return(f,X,Y)=>{let V=typeof f!=="string";return TD({executable:V?f.command:J,args:V?f.args??[]:OD(J,f),cwd:X,env:Z},Y,Q,j,W)}}function KX($,J){let Q=$.metadata?.[J];return typeof Q==="string"?Q:void 0}function GX($,J){aj(ef($.metadata),{tool_name:"run_commands",effective_timeout_ms:J.effectiveTimeoutMs,timeout_source:J.timeoutSource,command_count:J.commandCount,duration_ms:J.durationMs,ulid:$.sessionId,mode:KX($,"mode"),source:KX($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function MD($){let J=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return J?.[1]??J?.[2]??J?.[3]}function qD($){let J=[];for(let Q=0;Q<$.length;Q+=1){let Z=$[Q],W=MD(Z);if(!W){J.push(Z);continue}let j=$.findIndex((X,Y)=>Y>Q&&X.trim()===W);if(j===-1){J.push(Z);continue}let f=[Z];while(Q<j){Q+=1;let X=$[Q];f.push(X)}J.push(f.join(`
95
- `))}return J}function TZ($,J={}){let Q=J.fileReadTimeoutMs??1e4;return y1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${r2} lines / ~${Math.round(V5/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:H1(w4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=E1(JX,Z),f;if(typeof j==="string")f=[{path:j}];else if(Array.isArray(j))f=j.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in j)f=(Array.isArray(j.files)?j.files:[j.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in j)f=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((Y)=>({path:Y}));else if("paths"in j)f=(Array.isArray(j.paths)?j.paths:[j.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else f=[j];return Promise.all(f.map(async(X)=>{let Y=YX(X);if(Y)return{query:Y5(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await V1($(X,W),Q,`File read timed out after ${Q}ms`);return{query:Y5(X),result:V,success:!0}}catch(V){let H=f$(V);return{query:Y5(X),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function MZ($,J={}){let Q=J.searchTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(i2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:H1(S4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,j)=>{let f=E1(QX,W),X=Array.isArray(f)?f:typeof f==="object"?Array.isArray(f.queries)?f.queries:[f.queries]:[f];return Promise.all(X.map(async(Y)=>{try{let V=await V1($(Y,Z,j),Q,`Search timed out after ${Q}ms`);return{query:Y,result:V,success:!0}}catch(V){let H=f$(V);return{query:Y,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}function qZ($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return y1({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. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round(I4/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:H1(p2),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=E1(ZX,j),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=qD(Y),Promise.all(Y.map(async(V)=>{let H=Date.now(),B=_Z(V);try{let A=await V1($(V,W,f),Q,`Command timed out after ${Q}ms`);return{query:B,result:A,success:!0}}catch(A){if(A instanceof m$)GX(f,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Z,commandCount:Y.length,durationMs:Date.now()-H});if(A instanceof x4)return{query:B,result:A.output,error:A.message,success:!1};let K=f$(A);return{query:B,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function PZ($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return y1({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. Output beyond ~${Math.round(I4/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:H1(RZ),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=VX(j);return Promise.all(X.map(async(Y)=>{let V=Date.now(),H=_Z(Y);try{let B=await V1($(Y,W,f),Q,`Command timed out after ${Q}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof m$)GX(f,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Z,commandCount:X.length,durationMs:Date.now()-V});if(B instanceof x4)return{query:H,result:B.output,error:B.message,success:!1};let A=f$(B);return{query:H,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function NZ($,J={}){let Q=J.webFetchTimeoutMs??30000;return y1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:H1(C4),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(Z,W)=>{let j=E1(C4,Z);return Promise.all(j.requests.map(async(f)=>{try{let X=await V1($(f.url,f.prompt,W),Q,`Web fetch timed out after ${Q}ms`);return{query:f.url,result:X,success:!0}}catch(X){let Y=f$(X);return{query:f.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var PD=`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:
94
+ ${z.text}`:""):L.text;if(L.dropped||W&&z.dropped||P.length>Z){let b=W?L.totalChars+z.totalChars:L.totalChars;P=BX(P,Z,b)}G(()=>j(P))}}),Y.on("error",(T)=>{O(),G(()=>f(Error(`Failed to execute command: ${T.message}`)))})})}function g4($={}){let{shell:J=_D(process.platform),timeoutMs:Q=30000,env:Z={},combineOutput:W=!0}=$,j=$.maxOutputChars??$.maxOutputBytes??I4;return(f,X,Y)=>{let V=typeof f!=="string";return TD({executable:V?f.command:J,args:V?f.args??[]:OD(J,f),cwd:X,env:Z},Y,Q,j,W)}}function AX($,J){let Q=$.metadata?.[J];return typeof Q==="string"?Q:void 0}function KX($,J){nj(tf($.metadata),{tool_name:"run_commands",effective_timeout_ms:J.effectiveTimeoutMs,timeout_source:J.timeoutSource,command_count:J.commandCount,duration_ms:J.durationMs,ulid:$.sessionId,mode:AX($,"mode"),source:AX($,"source"),session_id:$.sessionId,agent_id:$.agentId,conversation_id:$.conversationId,run_id:$.runId,iteration:$.iteration,tool_call_id:$.toolCallId})}function MD($){let J=$.match(/(?<![<])<<-?\s*(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9_./-]+))/);return J?.[1]??J?.[2]??J?.[3]}function qD($){let J=[];for(let Q=0;Q<$.length;Q+=1){let Z=$[Q],W=MD(Z);if(!W){J.push(Z);continue}let j=$.findIndex((X,Y)=>Y>Q&&X.trim()===W);if(j===-1){J.push(Z);continue}let f=[Z];while(Q<j){Q+=1;let X=$[Q];f.push(X)}J.push(f.join(`
95
+ `))}return J}function TZ($,J={}){let Q=J.fileReadTimeoutMs??1e4;return y1({name:"read_files",description:`Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. When you already know multiple files you need, read them together in one call, and call this tool in the same response as other independent tool calls. Each read returns at most ${r2} lines / ~${Math.round(V5/1024)}k characters; longer files report their total line count, page through them with start_line/end_line. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. `,inputSchema:H1(w4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=E1($X,Z),f;if(typeof j==="string")f=[{path:j}];else if(Array.isArray(j))f=j.map((X)=>typeof X==="string"?{path:X}:X);else if("files"in j)f=(Array.isArray(j.files)?j.files:[j.files]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else if("file_paths"in j)f=(Array.isArray(j.file_paths)?j.file_paths:[j.file_paths]).map((Y)=>({path:Y}));else if("paths"in j)f=(Array.isArray(j.paths)?j.paths:[j.paths]).map((Y)=>typeof Y==="string"?{path:Y}:Y);else f=[j];return Promise.all(f.map(async(X)=>{let Y=XX(X);if(Y)return{query:Y5(X),result:"",error:`Invalid file range: ${Y}`,success:!1};try{let V=await V1($(X,W),Q,`File read timed out after ${Q}ms`);return{query:Y5(X),result:V,success:!0}}catch(V){let H=f$(V);return{query:Y5(X),result:"",error:`Error reading file: ${H}`,success:!1}}}))}})}function MZ($,J={}){let Q=J.searchTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({name:"search_codebase",description:`Perform regex pattern searches across the codebase. Supports multiple parallel searches. When several search patterns could be useful and do not depend on each other, run them together in one call, and call this tool in the same response as other independent tool calls. Use for finding code patterns, function definitions, class names, imports, etc. Output beyond ~${Math.round(i2/1000)}k characters per query is middle-truncated; narrow patterns beat broad ones.`,inputSchema:H1(S4),timeoutMs:Q*2,retryable:!0,maxRetries:1,execute:async(W,j)=>{let f=E1(JX,W),X=Array.isArray(f)?f:typeof f==="object"?Array.isArray(f.queries)?f.queries:[f.queries]:[f];return Promise.all(X.map(async(Y)=>{try{let V=await V1($(Y,Z,j),Q,`Search timed out after ${Q}ms`);return{query:Y,result:V,success:!0}}catch(V){let H=f$(V);return{query:Y,result:"",error:`Search failed: ${H}`,success:!1}}}))}})}function qZ($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return y1({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. Include multiple commands only when they are independent complete shell commands and safe to run concurrently; multiline scripts and heredocs must be a single command string. Output beyond ~${Math.round(I4/1000)}k characters is middle-truncated (start and end preserved); pipe through grep/head/tail when you need specific sections of large output. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.`,inputSchema:H1(p2),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=E1(QX,j),Y;if(typeof X==="string")Y=[X];else if(Array.isArray(X))Y=X;else if("commands"in X)Y=Array.isArray(X.commands)?X.commands:[X.commands];else if("command"in X)Y=[X.command];else Y=[X.cmd];return Y=qD(Y),Promise.all(Y.map(async(V)=>{let H=Date.now(),B=_Z(V);try{let A=await V1($(V,W,f),Q,`Command timed out after ${Q}ms`);return{query:B,result:A,success:!0}}catch(A){if(A instanceof m$)KX(f,{effectiveTimeoutMs:A.timeoutMs,timeoutSource:Z,commandCount:Y.length,durationMs:Date.now()-H});if(A instanceof x4)return{query:B,result:A.output,error:A.message,success:!1};let K=f$(A);return{query:B,result:"",error:`Command failed: ${K}`,success:!1}}}))}})}function PZ($,J={}){let Q=J.bashTimeoutMs??30000,Z=J.bashTimeoutMs===void 0?"default_setting":"configured_setting",W=J.cwd??process.cwd();return y1({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. Output beyond ~${Math.round(I4/1000)}k characters is middle-truncated (start and end preserved); filter output when you need specific sections. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped. Include multiple commands when they are independent and safe to run concurrently.`,inputSchema:H1(RZ),timeoutMs:Q*2,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=YX(j);return Promise.all(X.map(async(Y)=>{let V=Date.now(),H=_Z(Y);try{let B=await V1($(Y,W,f),Q,`Command timed out after ${Q}ms`);return{query:H,result:B,success:!0}}catch(B){if(B instanceof m$)KX(f,{effectiveTimeoutMs:B.timeoutMs,timeoutSource:Z,commandCount:X.length,durationMs:Date.now()-V});if(B instanceof x4)return{query:H,result:B.output,error:B.message,success:!1};let A=f$(B);return{query:H,result:"",error:`Command failed: ${A}`,success:!1}}}))}})}function NZ($,J={}){let Q=J.webFetchTimeoutMs??30000;return y1({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract. Fetch independent URLs together in one call, and call this tool in the same response as other independent tool calls.",inputSchema:H1(C4),timeoutMs:Q*2,retryable:!0,maxRetries:2,execute:async(Z,W)=>{let j=E1(C4,Z);return Promise.all(j.requests.map(async(f)=>{try{let X=await V1($(f.url,f.prompt,W),Q,`Web fetch timed out after ${Q}ms`);return{query:f.url,result:X,success:!0}}catch(X){let Y=f$(X);return{query:f.url,result:"",error:`Error fetching web content: ${Y}`,success:!1}}}))}})}var PD=`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:
96
96
 
97
97
  *** Begin Patch
98
98
  *** Update File: path/to/file.ts
@@ -128,19 +128,19 @@ Example:
128
128
  </div>
129
129
  );
130
130
  }
131
- *** End Patch`;function wZ($,J={}){let Q=J.applyPatchTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({name:"apply_patch",description:PD,inputSchema:H1(E4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=E1(fX,W),X=typeof f==="string"?f:f.input;try{return{query:"apply_patch",result:await V1($({input:X},Z,j),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f$(Y)}`,success:!1}}}})}function SZ($,J={}){let Q=J.editorTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({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:H1(y4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=E1(y4,W),X=f.insert_line==null?"edit":"insert",Y=XX(f);if(Y)return{query:`${X}:${f.path}`,result:"",error:Y,success:!1};try{let V=await V1($(f,Z,j),Q,`Editor operation timed out after ${Q}ms`);return{query:`${X}:${f.path}`,result:V,success:!0}}catch(V){let H=f$(V);return{query:`${X}:${f.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function v$($,J={}){let Q=J.skillsTimeoutMs??15000,Z='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.',W=y1({name:"skills",description:Z,inputSchema:H1(b4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=E1(b4,j);return V1($(X.skill,X.args||void 0,f),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(W,"description",{get(){let j=$.configuredSkills?.filter((f)=>!f.disabled).map((f)=>f.name);if(j&&j.length>0)return`${Z} Available skills: ${j.join(", ")}.`;return Z},enumerable:!0,configurable:!0}),W}function CZ($){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:H1(h4),retryable:!1,maxRetries:0,execute:async(J,Q)=>{let Z=E1(h4,J);return $(Z.question,Z.options,Q)}}}function yZ($,J={}){let Q=J.submitTimeoutMs??15000;return y1({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:H1(k4),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=E1(k4,Z);return V1($(j.summary,j.verified,W),Q,`submit_and_exit timed out after ${Q}ms`)}})}function X$($){let{executors:J,enableReadFiles:Q=!0,enableSearch:Z=!0,enableBash:W=!0,enableWebFetch:j=!0,enableApplyPatch:f=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:H=!1,...B}=$,A=[];if(Q&&J.readFile)A.push(TZ(J.readFile,B));if(Z&&J.search)A.push(MZ(J.search,B));if(W&&J.bash)if(process.platform==="win32")A.push(PZ(J.bash,B));else A.push(qZ(J.bash,B));if(j&&J.webFetch)A.push(NZ(J.webFetch,B));if(X&&J.editor)A.push(SZ(J.editor,B));else if(f&&J.applyPatch)A.push(wZ(J.applyPatch,B));if(Y&&J.skills)A.push(v$(J.skills,B));let K=H?J.submit:void 0;if(V&&J.askQuestion&&!K)A.push(CZ(J.askQuestion));if(K)A.push(yZ(K,B));return A}import*as m0 from"node:fs/promises";import*as v0 from"node:path";var d={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},DX=["%%bash","apply_patch","EOF","```"];class W0 extends Error{constructor($){super($);this.name="DiffError"}}function g0($){let J={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>J[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class EZ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,J){this.lines=$;this.currentFiles=J}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(d.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(d.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(d.UPDATE)){this.parseUpdate($.substring(d.UPDATE.length).trim());return}if($?.startsWith(d.DELETE)){this.parseDelete($.substring(d.DELETE.length).trim());return}if($?.startsWith(d.ADD)){this.parseAdd($.substring(d.ADD.length).trim());return}throw new W0(`Unknown line while parsing: ${$}`)}checkDuplicate($,J){if($ in this.patch.actions)throw new W0(`Duplicate ${J} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let J=this.lines[this.index]?.startsWith(d.MOVE)?(this.lines[this.index++]??"").substring(d.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new W0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",Z=this.parseUpdateFile(Q,$);Z.movePath=J,this.patch.actions[$]=Z,this.currentPath=void 0}parseUpdateFile($,J){let Q={type:"update",chunks:[]},Z=$.split(`
131
+ *** End Patch`;function wZ($,J={}){let Q=J.applyPatchTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({name:"apply_patch",description:PD,inputSchema:H1(E4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=E1(jX,W),X=typeof f==="string"?f:f.input;try{return{query:"apply_patch",result:await V1($({input:X},Z,j),Q,`apply_patch timed out after ${Q}ms`),success:!0}}catch(Y){return{query:"apply_patch",result:"",error:`apply_patch failed: ${f$(Y)}`,success:!1}}}})}function SZ($,J={}){let Q=J.editorTimeoutMs??30000,Z=J.cwd??process.cwd();return y1({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:H1(y4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(W,j)=>{let f=E1(y4,W),X=f.insert_line==null?"edit":"insert",Y=fX(f);if(Y)return{query:`${X}:${f.path}`,result:"",error:Y,success:!1};try{let V=await V1($(f,Z,j),Q,`Editor operation timed out after ${Q}ms`);return{query:`${X}:${f.path}`,result:V,success:!0}}catch(V){let H=f$(V);return{query:`${X}:${f.path}`,result:"",error:`Editor operation failed: ${H}`,success:!1}}}})}function v$($,J={}){let Q=J.skillsTimeoutMs??15000,Z='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.',W=y1({name:"skills",description:Z,inputSchema:H1(b4),timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(j,f)=>{let X=E1(b4,j);return V1($(X.skill,X.args||void 0,f),Q,`Skills operation timed out after ${Q}ms`)}});return Object.defineProperty(W,"description",{get(){let j=$.configuredSkills?.filter((f)=>!f.disabled).map((f)=>f.name);if(j&&j.length>0)return`${Z} Available skills: ${j.join(", ")}.`;return Z},enumerable:!0,configurable:!0}),W}function CZ($){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:H1(h4),retryable:!1,maxRetries:0,execute:async(J,Q)=>{let Z=E1(h4,J);return $(Z.question,Z.options,Q)}}}function yZ($,J={}){let Q=J.submitTimeoutMs??15000;return y1({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:H1(k4),lifecycle:{completesRun:!0},timeoutMs:Q,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=E1(k4,Z);return V1($(j.summary,j.verified,W),Q,`submit_and_exit timed out after ${Q}ms`)}})}function X$($){let{executors:J,enableReadFiles:Q=!0,enableSearch:Z=!0,enableBash:W=!0,enableWebFetch:j=!0,enableApplyPatch:f=!1,enableEditor:X=!0,enableSkills:Y=!0,enableAskQuestion:V=!0,enableSubmitAndExit:H=!1,...B}=$,A=[];if(Q&&J.readFile)A.push(TZ(J.readFile,B));if(Z&&J.search)A.push(MZ(J.search,B));if(W&&J.bash)if(process.platform==="win32")A.push(PZ(J.bash,B));else A.push(qZ(J.bash,B));if(j&&J.webFetch)A.push(NZ(J.webFetch,B));if(X&&J.editor)A.push(SZ(J.editor,B));else if(f&&J.applyPatch)A.push(wZ(J.applyPatch,B));if(Y&&J.skills)A.push(v$(J.skills,B));let K=H?J.submit:void 0;if(V&&J.askQuestion&&!K)A.push(CZ(J.askQuestion));if(K)A.push(yZ(K,B));return A}import*as m0 from"node:fs/promises";import*as v0 from"node:path";var d={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},FX=["%%bash","apply_patch","EOF","```"];class W0 extends Error{constructor($){super($);this.name="DiffError"}}function g0($){let J={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(Q)=>J[Q]??Q).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class EZ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,J){this.lines=$;this.currentFiles=J}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(d.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(d.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(d.UPDATE)){this.parseUpdate($.substring(d.UPDATE.length).trim());return}if($?.startsWith(d.DELETE)){this.parseDelete($.substring(d.DELETE.length).trim());return}if($?.startsWith(d.ADD)){this.parseAdd($.substring(d.ADD.length).trim());return}throw new W0(`Unknown line while parsing: ${$}`)}checkDuplicate($,J){if($ in this.patch.actions)throw new W0(`Duplicate ${J} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let J=this.lines[this.index]?.startsWith(d.MOVE)?(this.lines[this.index++]??"").substring(d.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new W0(`Update File Error: Missing File: ${$}`);let Q=this.currentFiles[$]??"",Z=this.parseUpdateFile(Q,$);Z.movePath=J,this.patch.actions[$]=Z,this.currentPath=void 0}parseUpdateFile($,J){let Q={type:"update",chunks:[]},Z=$.split(`
132
132
  `),W=0,j=[d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(!j.some((f)=>this.lines[this.index]?.startsWith(f.trim()))){let f=this.lines[this.index],X=f?.startsWith("@@ ")?f.substring(3):void 0;if(X!==void 0||(f==="@@"?f:void 0)!==void 0)this.index++;else if(W!==0)throw new W0(`Invalid Line:
133
133
  ${this.lines[this.index]}`);if(X?.trim()){let D=g0(X.trim());for(let U=W;U<Z.length;U++){let F=Z[U];if(F&&(g0(F)===D||g0(F.trim())===D)){if(W=U+1,g0(F.trim())===D&&g0(F)!==D)this.fuzz++;break}}}let[V,H,B,A]=SD(this.lines,this.index),[K,G,R]=wD(Z,V,W,A);if(K===-1){let D=V.join(`
134
134
  `);this.addWarning({path:this.currentPath||J,chunkIndex:Q.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:D.length>200?`${D.substring(0,200)}...`:D}),this.index=B}else{this.fuzz+=G;for(let D of H)D.origIndex+=K,Q.chunks.push(D);W=K+V.length,this.index=B}}return Q}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new W0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new W0(`Add File Error: File already exists: ${$}`);this.index++;let J=[],Q=[d.END,d.UPDATE,d.DELETE,d.ADD];while(this.hasMoreLines()&&!Q.some((Z)=>this.lines[this.index]?.startsWith(Z.trim()))){let Z=this.lines[this.index++];if(Z===void 0)break;if(!Z.startsWith("+"))throw new W0(`Invalid Add File line (missing '+'): ${Z}`);J.push(Z.substring(1))}this.patch.actions[$]={type:"add",newFile:J.join(`
135
- `),chunks:[]}}}function FX($,J){let Q=$.length>J.length?$:J,Z=$.length>J.length?J:$;if(Q.length===0)return 1;let W=ND(Z,Q);return(Q.length-W)/Q.length}function ND($,J){let Q=J.length+1,Z=$.length+1,W=Array(Q*Z).fill(0),j=(X,Y)=>W[X*Z+Y]??0,f=(X,Y,V)=>{W[X*Z+Y]=V};for(let X=0;X<=J.length;X++)f(X,0,X);for(let X=0;X<=$.length;X++)f(0,X,X);for(let X=1;X<=J.length;X++)for(let Y=1;Y<=$.length;Y++)if(J[X-1]===$[Y-1])f(X,Y,j(X-1,Y-1));else f(X,Y,1+Math.min(j(X-1,Y-1),j(X,Y-1),j(X-1,Y)));return j(J.length,$.length)}function wD($,J,Q,Z){if(J.length===0)return[Q,0,1];let W=0,j=(f)=>{let X=g0(J.join(`
135
+ `),chunks:[]}}}function GX($,J){let Q=$.length>J.length?$:J,Z=$.length>J.length?J:$;if(Q.length===0)return 1;let W=ND(Z,Q);return(Q.length-W)/Q.length}function ND($,J){let Q=J.length+1,Z=$.length+1,W=Array(Q*Z).fill(0),j=(X,Y)=>W[X*Z+Y]??0,f=(X,Y,V)=>{W[X*Z+Y]=V};for(let X=0;X<=J.length;X++)f(X,0,X);for(let X=0;X<=$.length;X++)f(0,X,X);for(let X=1;X<=J.length;X++)for(let Y=1;Y<=$.length;Y++)if(J[X-1]===$[Y-1])f(X,Y,j(X-1,Y-1));else f(X,Y,1+Math.min(j(X-1,Y-1),j(X,Y-1),j(X-1,Y)));return j(J.length,$.length)}function wD($,J,Q,Z){if(J.length===0)return[Q,0,1];let W=0,j=(f)=>{let X=g0(J.join(`
136
136
  `));for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).join(`
137
- `));if(H===X)return[V,0,1];let B=FX(H,X);if(B>W)W=B}for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).map((A)=>A.trimEnd()).join(`
137
+ `));if(H===X)return[V,0,1];let B=GX(H,X);if(B>W)W=B}for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).map((A)=>A.trimEnd()).join(`
138
138
  `)),B=g0(J.map((A)=>A.trimEnd()).join(`
139
139
  `));if(H===B)return[V,1,1]}for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).map((A)=>A.trim()).join(`
140
140
  `)),B=g0(J.map((A)=>A.trim()).join(`
141
141
  `));if(H===B)return[V,100,1]}let Y=0.66;for(let V=f;V<$.length;V++){let H=g0($.slice(V,V+J.length).join(`
142
- `)),B=FX(H,X);if(B>=Y)return[V,1000,B];if(B>W)W=B}return[-1,0,W]};if(Z){let[f,X,Y]=j($.length-J.length);if(f!==-1)return[f,X,Y];return[f,X,Y]=j(Q),[f,X+1e4,Y]}return j(Q)}function SD($,J){let Q=J,Z=[],W=[],j=[],f=[],X="keep",Y=["@@",d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(Q<$.length){let V=$[Q];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new W0(`Invalid line: ${V}`);Q++;let H=X,B=V;if(B[0]==="+")X="add";else if(B[0]==="-")X="delete";else if(B[0]===" ")X="keep";else X="keep",B=` ${B}`;if(B=B.slice(1),X==="keep"&&H!==X){if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});W=[],j=[]}if(X==="delete")W.push(B),Z.push(B);else if(X==="add")j.push(B);else Z.push(B)}if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});if(Q<$.length&&$[Q]===d.END_FILE)return Q++,[Z,f,Q,!0];return[Z,f,Q,!1]}function bZ($,J,Q){let Z=v0.isAbsolute(J),W=Z?v0.normalize(J):v0.resolve($,J);if(!Q||Z)return W;let j=v0.relative($,W);if(j.startsWith("..")||v0.isAbsolute(j))throw new W0(`Path must stay within cwd: ${J}`);return W}function CD($){return $.split(`
143
- `).map((J)=>J.replace(/\r$/,""))}function UX($){if($.trim()==="")return!1;return DX.some((J)=>$.startsWith(J))}function yD($){let J=0,Q=$.length;while(J<Q&&UX($[J]??""))J++;while(Q>J&&UX($[Q-1]??""))Q--;return $.slice(J,Q)}function ED($){let J=CD($),Q=J.findIndex((f)=>f.startsWith(d.BEGIN)),Z=-1;for(let f=J.length-1;f>=0;f--)if(J[f]?.startsWith(d.END)){Z=f;break}if(Q!==-1||Z!==-1){if(Q===-1||Z===-1||Z<Q)throw new W0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:J.slice(Q,Z+1)}}let W=yD(J);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[d.BEGIN,...W,d.END]}}function bD($,J){let Q=new Set;for(let Z of $)for(let W of J)if(Z.startsWith(W)){Q.add(Z.substring(W.length).trim());break}return[...Q]}function hD($,J,Q){if(J.length===0)return $;let Z=$.split(`
142
+ `)),B=GX(H,X);if(B>=Y)return[V,1000,B];if(B>W)W=B}return[-1,0,W]};if(Z){let[f,X,Y]=j($.length-J.length);if(f!==-1)return[f,X,Y];return[f,X,Y]=j(Q),[f,X+1e4,Y]}return j(Q)}function SD($,J){let Q=J,Z=[],W=[],j=[],f=[],X="keep",Y=["@@",d.END,d.UPDATE,d.DELETE,d.ADD,d.END_FILE];while(Q<$.length){let V=$[Q];if(!V||Y.some((A)=>V.startsWith(A.trim())))break;if(V==="***")break;if(V.startsWith("***"))throw new W0(`Invalid line: ${V}`);Q++;let H=X,B=V;if(B[0]==="+")X="add";else if(B[0]==="-")X="delete";else if(B[0]===" ")X="keep";else X="keep",B=` ${B}`;if(B=B.slice(1),X==="keep"&&H!==X){if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});W=[],j=[]}if(X==="delete")W.push(B),Z.push(B);else if(X==="add")j.push(B);else Z.push(B)}if(j.length||W.length)f.push({origIndex:Z.length-W.length,delLines:W,insLines:j});if(Q<$.length&&$[Q]===d.END_FILE)return Q++,[Z,f,Q,!0];return[Z,f,Q,!1]}function bZ($,J,Q){let Z=v0.isAbsolute(J),W=Z?v0.normalize(J):v0.resolve($,J);if(!Q||Z)return W;let j=v0.relative($,W);if(j.startsWith("..")||v0.isAbsolute(j))throw new W0(`Path must stay within cwd: ${J}`);return W}function CD($){return $.split(`
143
+ `).map((J)=>J.replace(/\r$/,""))}function DX($){if($.trim()==="")return!1;return FX.some((J)=>$.startsWith(J))}function yD($){let J=0,Q=$.length;while(J<Q&&DX($[J]??""))J++;while(Q>J&&DX($[Q-1]??""))Q--;return $.slice(J,Q)}function ED($){let J=CD($),Q=J.findIndex((f)=>f.startsWith(d.BEGIN)),Z=-1;for(let f=J.length-1;f>=0;f--)if(J[f]?.startsWith(d.END)){Z=f;break}if(Q!==-1||Z!==-1){if(Q===-1||Z===-1||Z<Q)throw new W0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:J.slice(Q,Z+1)}}let W=yD(J);while(W.length>0&&W[0]==="")W.shift();while(W.length>0&&W[W.length-1]==="")W.pop();return{lines:[d.BEGIN,...W,d.END]}}function bD($,J){let Q=new Set;for(let Z of $)for(let W of J)if(Z.startsWith(W)){Q.add(Z.substring(W.length).trim());break}return[...Q]}function hD($,J,Q){if(J.length===0)return $;let Z=$.split(`
144
144
  `),W=[],j=0;for(let f of J){if(f.origIndex>Z.length)throw new W0(`${Q}: chunk.origIndex ${f.origIndex} > lines.length ${Z.length}`);if(j>f.origIndex)throw new W0(`${Q}: currentIndex ${j} > chunk.origIndex ${f.origIndex}`);W.push(...Z.slice(j,f.origIndex)),W.push(...f.insLines),j=f.origIndex+f.delLines.length}return W.push(...Z.slice(j)),W.join(`
145
145
  `)}async function kD($,J,Q,Z){let W=bD($,[d.UPDATE,d.DELETE]),j={};for(let f of W){let X=bZ(J,f,Z),Y;try{Y=await m0.readFile(X,Q)}catch{throw new W0(`File not found: ${f}`)}j[f]=Y.replace(/\r\n/g,`
146
146
  `)}return j}function ID($,J){let Q={};for(let[Z,W]of Object.entries($.actions))switch(W.type){case"delete":Q[Z]={type:"delete",oldContent:J[Z]};break;case"add":if(W.newFile===void 0)throw new W0("ADD action without file content");Q[Z]={type:"add",newContent:W.newFile};break;case"update":Q[Z]={type:"update",oldContent:J[Z],newContent:hD(J[Z]??"",W.chunks,Z),movePath:W.movePath};break}return Q}function xD($){let J=[`Patch could not be applied because ${$.length} hunk${$.length===1?"":"s"} did not match the current file content.`];for(let Q of $){let Z=Q.chunkIndex===void 0?"unknown":String(Q.chunkIndex+1);if(J.push(`${Q.path}: hunk ${Z}: ${Q.message}`),Q.context)J.push(`Context:
@@ -153,15 +153,15 @@ ${Q.context}`)}return J.join(`
153
153
  ${Y}`}async function pD($,J,Q,Z){let j=(await Z1.readFile($,Z)).split(`
154
154
  `),f=j.length+1;if(J<1||J>f)throw Error(`Invalid insert_line: ${J}. insert_line must be a positive one-based boundary line in the range 1-${f}. Use ${f} to append at EOF.`);let X=J-1;return j.splice(X,0,...Q.split(`
155
155
  `)),await Z1.writeFile($,j.join(`
156
- `),{encoding:Z}),`Inserted content at line ${J} in ${$}.`}function v4($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0,maxDiffLines:Z=200}=$;return async(W,j,f)=>{let X=mD(j,W.path,Q);if(W.insert_line!=null)return pD(X,W.insert_line,W.new_text,J);if(!await dD(X))return uD(X,W.new_text,J);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return lD(X,W.old_text,W.new_text,J,Z)}}import{createReadStream as rD}from"node:fs";import*as H5 from"node:fs/promises";import*as Y$ from"node:path";import{createInterface as iD}from"node:readline";import{resolveExistingFilePath as nD}from"@cline/shared/storage";var aD=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),sD={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},RX=1e8,oD=50000;function zX($){let{reason:J}=$;if(J instanceof Error)return J;if(J!==void 0)return Error(String(J));return Error("File read was aborted")}async function tD($,J,Q,Z,W,j){if(j?.aborted)throw zX(j);let f=Math.max(Z??1,1),X=W??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:f+oD-1,H=[],B=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,f+r2-1):f+r2-1,D=Q?String(R).length+3:0,U=rD($,{encoding:J}),F=iD({input:U,crlfDelay:Number.POSITIVE_INFINITY}),O=j?()=>U.destroy(zX(j)):void 0;if(j&&O)j.addEventListener("abort",O,{once:!0});try{for await(let b of F){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<f||K)continue;if(H.length>=r2){K=!0;continue}let u=b;if(u.length>OZ)u=`${u.slice(0,OZ)} [line truncated]`;let o=B+u.length+D+1;if(o>V5&&H.length>0){K=!0;continue}H.push({lineNumber:A,text:u}),B=o}}finally{if(j&&O)j.removeEventListener("abort",O);F.close(),U.destroy()}let T=String(H[H.length-1]?.lineNumber??A).length,L=H.map(({lineNumber:b,text:u})=>Q?`${String(b).padStart(T," ")} | ${u}`:u).join(`
156
+ `),{encoding:Z}),`Inserted content at line ${J} in ${$}.`}function v4($={}){let{encoding:J="utf-8",restrictToCwd:Q=!0,maxDiffLines:Z=200}=$;return async(W,j,f)=>{let X=mD(j,W.path,Q);if(W.insert_line!=null)return pD(X,W.insert_line,W.new_text,J);if(!await dD(X))return uD(X,W.new_text,J);if(W.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return lD(X,W.old_text,W.new_text,J,Z)}}import{createReadStream as rD}from"node:fs";import*as H5 from"node:fs/promises";import*as Y$ from"node:path";import{createInterface as iD}from"node:readline";import{resolveExistingFilePath as nD}from"@cline/shared/storage";var aD=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),sD={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0},UX=1e8,oD=50000;function RX($){let{reason:J}=$;if(J instanceof Error)return J;if(J!==void 0)return Error(String(J));return Error("File read was aborted")}async function tD($,J,Q,Z,W,j){if(j?.aborted)throw RX(j);let f=Math.max(Z??1,1),X=W??Number.POSITIVE_INFINITY,Y=Number.isFinite(X),V=Y?X:f+oD-1,H=[],B=0,A=0,K=!1,G=!1,R=Number.isFinite(X)?Math.min(X,f+r2-1):f+r2-1,D=Q?String(R).length+3:0,U=rD($,{encoding:J}),F=iD({input:U,crlfDelay:Number.POSITIVE_INFINITY}),O=j?()=>U.destroy(RX(j)):void 0;if(j&&O)j.addEventListener("abort",O,{once:!0});try{for await(let b of F){if(A+=1,A>X){A=X;break}if(!Y&&K&&A>=V){G=!0;break}if(A<f||K)continue;if(H.length>=r2){K=!0;continue}let u=b;if(u.length>OZ)u=`${u.slice(0,OZ)} [line truncated]`;let o=B+u.length+D+1;if(o>V5&&H.length>0){K=!0;continue}H.push({lineNumber:A,text:u}),B=o}}finally{if(j&&O)j.removeEventListener("abort",O);F.close(),U.destroy()}let T=String(H[H.length-1]?.lineNumber??A).length,L=H.map(({lineNumber:b,text:u})=>Q?`${String(b).padStart(T," ")} | ${u}`:u).join(`
157
157
  `),z=H[H.length-1]?.lineNumber;if(z===void 0)return L;let P=Math.min(X,A);if(z>=P)return L;let S=G?`${A}+ lines`:P;return`${L}
158
158
 
159
- [Showing lines ${f}-${z} of ${S}. Use start_line/end_line to read other sections.]`}function c4($={}){let{maxFileSizeBytes:J,encoding:Q,includeLineNumbers:Z}={...sD,...$};return async(W,j)=>{let{path:f,start_line:X,end_line:Y}=W,V=Y$.isAbsolute(f)?Y$.normalize(f):Y$.resolve(process.cwd(),f),H=nD(V)??V,B=Y$.extname(H).toLowerCase(),A=aD.get(B),K=await H5.stat(H);if(!K.isFile())throw Error(`Path is not a file: ${H}`);if(A){if(K.size>J)throw Error(`Image file too large: ${K.size} bytes (max: ${J} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await H5.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>RX)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${RX} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return tD(H,Q,Z,X,Y,j.signal)}}import{spawn as NX}from"node:child_process";import*as wX from"node:fs/promises";import*as K5 from"node:path";var qX={};w(qX,{prewarmFileIndex:()=>A5,getFileIndex:()=>b1,enrichPromptWithMentions:()=>a2});import{spawn as eD}from"node:child_process";import{readdir as $U}from"node:fs/promises";import kZ from"node:path";import{isMainThread as OX,parentPort as LX,Worker as JU}from"node:worker_threads";var QU=15000,ZU=600000,WU=1000,jU=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function _X($){let J=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return J==="EACCES"||J==="EPERM"||J==="ENOENT"}var n2=new Map;function fU(){if(!OX)return!1;return!0}function XU($){if(n2.size<=1)return;for(let[J,Q]of n2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>ZU)n2.delete(J)}}function YU($,J){return kZ.relative($,J).split(kZ.sep).join("/")}async function VU($){let Q=(await new Promise((Z,W)=>{let j=eD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),f="",X="";j.stdout.on("data",(Y)=>{f+=Y.toString()}),j.stderr.on("data",(Y)=>{X+=Y.toString()}),j.on("error",W),j.on("close",(Y)=>{if(Y===0){Z(f);return}W(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Z.replace(/\\/g,"/"));return new Set(Q)}async function TX($,J,Q){let Z;try{Z=await $U(J,{withFileTypes:!0})}catch(W){if(_X(W))return;throw W}for(let W of Z){let j=kZ.join(J,W.name);if(W.isDirectory()){if(jU.has(W.name))continue;try{await TX($,j,Q)}catch(f){if(_X(f))continue;throw f}continue}if(W.isFile())Q.add(YU($,j))}}async function HU($){let J=new Set;return await TX($,$,J),J}async function B5($){try{return await VU($)}catch{return HU($)}}function BU(){if(OX||!LX)return;let $=LX;$.on("message",(J)=>{if(J.type!=="index")return;B5(J.cwd).then((Q)=>{let Z={type:"indexResult",requestId:J.requestId,files:Array.from(Q)};$.postMessage(Z)}).catch((Q)=>{let Z={type:"indexResult",requestId:J.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(Z)})})}class MX{worker=new JU(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let J=this.pending.get($.requestId);if(!J)return;if(this.pending.delete($.requestId),$.error){J.reject(Error($.error));return}J.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 J=++this.nextRequestId,Q=new Promise((W,j)=>{let f=setTimeout(()=>{this.pending.delete(J),W(null)},WU);f.unref(),this.pending.set(J,{resolve:(X)=>{clearTimeout(f),W(X)},reject:(X)=>{clearTimeout(f),j(X)}})}),Z={type:"index",requestId:J,cwd:$};return this.worker.postMessage(Z),Q}flushPending($){for(let[J,Q]of this.pending.entries())Q.reject($),this.pending.delete(J)}}BU();var hZ;function AU(){if(!fU())return null;if(hZ===void 0)hZ=new MX;return hZ}async function KU($){let J=AU();if(!J)return B5($);try{let Q=await J.requestIndex($);if(Q===null)return B5($);return new Set(Q)}catch{return B5($)}}async function b1($,J={}){let Q=J.ttlMs??QU,Z=Date.now();XU(Z);let W=n2.get($);if(W&&Q>0&&Z-W.lastBuiltAt<=Q&&W.files.size>0)return W.lastAccessedAt=Z,W.files;if(W?.pending)return W.lastAccessedAt=Z,W.pending;let j=KU($).then((f)=>{return n2.set($,{files:f,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),f});return n2.set($,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:Z,pending:j}),j}async function A5($,J={}){await b1($,{...J,ttlMs:0})}import{stat as GU}from"node:fs/promises";import c$ from"node:path";var FU=/[),.:;!?`'"]+$/,DU=/^[(`'"]+/;function UU($){let J=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let Z of J){let W=(Z[2]??"").trim();if(W.length===0)continue;let j=W.replace(DU,"").replace(FU,"");if(j.length===0||j.includes("@"))continue;Q.push(j)}return Array.from(new Set(Q))}function RU($,J){let Q=$.replace(/\\/g,"/"),Z=c$.isAbsolute(Q)?c$.resolve(Q):c$.resolve(J,Q),W=c$.relative(J,Z);if(W.startsWith("..")||c$.isAbsolute(W))return;return W.split(c$.sep).join("/")}async function a2($,J,Q={}){let Z=UU($);if(Z.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:j,maxTotalBytes:f}=Q,X=await b1(J,{ttlMs:Q.ttlMs}),Y=[],V=[],H=[],B=0;for(let A of Z){if(W&&H.length>=W){V.push(A);continue}let K=RU(A,J);if(!K||!X.has(K)){V.push(A);continue}if(!j||!f){Y.push(K);continue}let G=c$.join(J,K);try{if(!(await GU(G)).isFile()){V.push(A);continue}let D=B+j;if(D>f){V.push(A);continue}B=D,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Z,matchedFiles:Y,ignoredMentions:V}}var zU=["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"],LU=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],u$=null;function _U(){if(u$!==null)return Promise.resolve(u$);return new Promise(($)=>{let J=NX("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});J.on("close",(Q)=>{u$=Q===0,$(u$)}),J.on("error",()=>{u$=!1,$(!1)}),setTimeout(()=>{if(!J.killed)J.kill("SIGTERM");if(u$===null)u$=!1,$(!1)},1000)})}function OU($,J,Q,Z,W=5000,j){return new Promise((f)=>{let X=NX("rg",["--json",`--context=${Z}`,"--max-count=1","-i",$],{cwd:J,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,H=()=>{if(!X.killed)X.kill("SIGTERM")},B=setTimeout(()=>{if(!V)V=!0,H(),f(null)},W),A=(K)=>{if(!V)V=!0,clearTimeout(B),H(),f(K)};if(j?.aborted){H(),f(null);return}j?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
160
- `).filter((D)=>D.trim());for(let D of R){if(G.length>=Q)break;let U=JSON.parse(D);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let T=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(T?.start??0)+1,match:T?.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??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function TU($,J,Q,Z){let W=$.split("/"),j=W[W.length-1]??"";if(W.length-1>Z)return!1;for(let Y=0;Y<W.length-1;Y++)if(J.has(W[Y]??""))return!1;let X=K5.posix.extname(j).slice(1).toLowerCase();return Q.has(X)||!X&&!j.startsWith(".")}function u4($={}){let{includeExtensions:J=zU,excludeDirs:Q=LU,maxResults:Z=100,contextLines:W=2,maxDepth:j=20}=$,f=new Set(Q),X=new Set(J.map((Y)=>Y.toLowerCase()));return async(Y,V,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let B=await _U(),A=null;if(B)A=await OU(Y,V,Z,W,5000,H.signal);if(A){let F=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let O of A)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(A.length>=Z)F.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return PX(F.join(`
161
- `))}let K;try{K=new RegExp(Y,"gim")}catch(F){throw Error(`Invalid regex pattern: ${Y}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,D=await b1(V);for(let F of D){if(H.signal?.aborted)throw Error("Search operation aborted");if(!TU(F,f,X,j))continue;if(G.length>=Z)break;R++;let O=K5.join(V,F);try{let L=(await wX.readFile(O,"utf-8")).split(`
159
+ [Showing lines ${f}-${z} of ${S}. Use start_line/end_line to read other sections.]`}function c4($={}){let{maxFileSizeBytes:J,encoding:Q,includeLineNumbers:Z}={...sD,...$};return async(W,j)=>{let{path:f,start_line:X,end_line:Y}=W,V=Y$.isAbsolute(f)?Y$.normalize(f):Y$.resolve(process.cwd(),f),H=nD(V)??V,B=Y$.extname(H).toLowerCase(),A=aD.get(B),K=await H5.stat(H);if(!K.isFile())throw Error(`Path is not a file: ${H}`);if(A){if(K.size>J)throw Error(`Image file too large: ${K.size} bytes (max: ${J} bytes).`);if(j.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let G=await H5.readFile(H);return[{type:"text",text:"Successfully read image"},{type:"image",data:G.toString("base64"),mediaType:A}]}if(K.size>UX)throw Error(`Text file too large to stream safely: ${K.size} bytes (max: ${UX} bytes). Use a targeted command such as sed, grep, head, or tail to inspect specific sections.`);return tD(H,Q,Z,X,Y,j.signal)}}import{spawn as PX}from"node:child_process";import*as NX from"node:fs/promises";import*as K5 from"node:path";var MX={};w(MX,{prewarmFileIndex:()=>A5,getFileIndex:()=>b1,enrichPromptWithMentions:()=>a2});import{spawn as eD}from"node:child_process";import{readdir as $U}from"node:fs/promises";import kZ from"node:path";import{isMainThread as _X,parentPort as zX,Worker as JU}from"node:worker_threads";var QU=15000,ZU=600000,WU=1000,jU=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function LX($){let J=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return J==="EACCES"||J==="EPERM"||J==="ENOENT"}var n2=new Map;function fU(){if(!_X)return!1;return!0}function XU($){if(n2.size<=1)return;for(let[J,Q]of n2.entries()){if(Q.pending)continue;if($-Q.lastAccessedAt>ZU)n2.delete(J)}}function YU($,J){return kZ.relative($,J).split(kZ.sep).join("/")}async function VU($){let Q=(await new Promise((Z,W)=>{let j=eD("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"],windowsHide:!0}),f="",X="";j.stdout.on("data",(Y)=>{f+=Y.toString()}),j.stderr.on("data",(Y)=>{X+=Y.toString()}),j.on("error",W),j.on("close",(Y)=>{if(Y===0){Z(f);return}W(Error(X||`rg exited with code ${Y}`))})})).split(/\r?\n/).map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Z.replace(/\\/g,"/"));return new Set(Q)}async function OX($,J,Q){let Z;try{Z=await $U(J,{withFileTypes:!0})}catch(W){if(LX(W))return;throw W}for(let W of Z){let j=kZ.join(J,W.name);if(W.isDirectory()){if(jU.has(W.name))continue;try{await OX($,j,Q)}catch(f){if(LX(f))continue;throw f}continue}if(W.isFile())Q.add(YU($,j))}}async function HU($){let J=new Set;return await OX($,$,J),J}async function B5($){try{return await VU($)}catch{return HU($)}}function BU(){if(_X||!zX)return;let $=zX;$.on("message",(J)=>{if(J.type!=="index")return;B5(J.cwd).then((Q)=>{let Z={type:"indexResult",requestId:J.requestId,files:Array.from(Q)};$.postMessage(Z)}).catch((Q)=>{let Z={type:"indexResult",requestId:J.requestId,error:Q instanceof Error?Q.message:"Failed to build file index"};$.postMessage(Z)})})}class TX{worker=new JU(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let J=this.pending.get($.requestId);if(!J)return;if(this.pending.delete($.requestId),$.error){J.reject(Error($.error));return}J.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 J=++this.nextRequestId,Q=new Promise((W,j)=>{let f=setTimeout(()=>{this.pending.delete(J),W(null)},WU);f.unref(),this.pending.set(J,{resolve:(X)=>{clearTimeout(f),W(X)},reject:(X)=>{clearTimeout(f),j(X)}})}),Z={type:"index",requestId:J,cwd:$};return this.worker.postMessage(Z),Q}flushPending($){for(let[J,Q]of this.pending.entries())Q.reject($),this.pending.delete(J)}}BU();var hZ;function AU(){if(!fU())return null;if(hZ===void 0)hZ=new TX;return hZ}async function KU($){let J=AU();if(!J)return B5($);try{let Q=await J.requestIndex($);if(Q===null)return B5($);return new Set(Q)}catch{return B5($)}}async function b1($,J={}){let Q=J.ttlMs??QU,Z=Date.now();XU(Z);let W=n2.get($);if(W&&Q>0&&Z-W.lastBuiltAt<=Q&&W.files.size>0)return W.lastAccessedAt=Z,W.files;if(W?.pending)return W.lastAccessedAt=Z,W.pending;let j=KU($).then((f)=>{return n2.set($,{files:f,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),f});return n2.set($,{files:W?.files??new Set,lastBuiltAt:W?.lastBuiltAt??0,lastAccessedAt:Z,pending:j}),j}async function A5($,J={}){await b1($,{...J,ttlMs:0})}import{stat as GU}from"node:fs/promises";import c$ from"node:path";var FU=/[),.:;!?`'"]+$/,DU=/^[(`'"]+/;function UU($){let J=$.matchAll(/(^|[\s])@([^\s]+)/g),Q=[];for(let Z of J){let W=(Z[2]??"").trim();if(W.length===0)continue;let j=W.replace(DU,"").replace(FU,"");if(j.length===0||j.includes("@"))continue;Q.push(j)}return Array.from(new Set(Q))}function RU($,J){let Q=$.replace(/\\/g,"/"),Z=c$.isAbsolute(Q)?c$.resolve(Q):c$.resolve(J,Q),W=c$.relative(J,Z);if(W.startsWith("..")||c$.isAbsolute(W))return;return W.split(c$.sep).join("/")}async function a2($,J,Q={}){let Z=UU($);if(Z.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:W,maxFileBytes:j,maxTotalBytes:f}=Q,X=await b1(J,{ttlMs:Q.ttlMs}),Y=[],V=[],H=[],B=0;for(let A of Z){if(W&&H.length>=W){V.push(A);continue}let K=RU(A,J);if(!K||!X.has(K)){V.push(A);continue}if(!j||!f){Y.push(K);continue}let G=c$.join(J,K);try{if(!(await GU(G)).isFile()){V.push(A);continue}let D=B+j;if(D>f){V.push(A);continue}B=D,Y.push(K)}catch{V.push(A)}}return{prompt:$,mentions:Z,matchedFiles:Y,ignoredMentions:V}}var zU=["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"],LU=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],u$=null;function _U(){if(u$!==null)return Promise.resolve(u$);return new Promise(($)=>{let J=PX("rg",["--version"],{stdio:["ignore","pipe","pipe"],windowsHide:!0});J.on("close",(Q)=>{u$=Q===0,$(u$)}),J.on("error",()=>{u$=!1,$(!1)}),setTimeout(()=>{if(!J.killed)J.kill("SIGTERM");if(u$===null)u$=!1,$(!1)},1000)})}function OU($,J,Q,Z,W=5000,j){return new Promise((f)=>{let X=PX("rg",["--json",`--context=${Z}`,"--max-count=1","-i",$],{cwd:J,stdio:["ignore","pipe","pipe"],windowsHide:!0}),Y="",V=!1,H=()=>{if(!X.killed)X.kill("SIGTERM")},B=setTimeout(()=>{if(!V)V=!0,H(),f(null)},W),A=(K)=>{if(!V)V=!0,clearTimeout(B),H(),f(K)};if(j?.aborted){H(),f(null);return}j?.addEventListener("abort",()=>{A(null)}),X.stdout.on("data",(K)=>{Y+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=Y.split(`
160
+ `).filter((D)=>D.trim());for(let D of R){if(G.length>=Q)break;let U=JSON.parse(D);if(U.type==="match"){let F=U.data,O=[];if(U.data.submatches&&U.data.submatches.length>0){let T=U.data.submatches[0];G.push({file:F.path.text,line:F.line_number,column:(T?.start??0)+1,match:T?.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??""}`)}}A(G.length>0?G:null)}catch{A(null)}return}A(null)}),X.on("error",()=>{A(null)})})}function TU($,J,Q,Z){let W=$.split("/"),j=W[W.length-1]??"";if(W.length-1>Z)return!1;for(let Y=0;Y<W.length-1;Y++)if(J.has(W[Y]??""))return!1;let X=K5.posix.extname(j).slice(1).toLowerCase();return Q.has(X)||!X&&!j.startsWith(".")}function u4($={}){let{includeExtensions:J=zU,excludeDirs:Q=LU,maxResults:Z=100,contextLines:W=2,maxDepth:j=20}=$,f=new Set(Q),X=new Set(J.map((Y)=>Y.toLowerCase()));return async(Y,V,H)=>{if(H.signal?.aborted)throw Error("Search operation aborted");let B=await _U(),A=null;if(B)A=await OU(Y,V,Z,W,5000,H.signal);if(A){let F=[`Found ${A.length} result${A.length===1?"":"s"} for pattern: ${Y}`,""];for(let O of A)F.push(`${O.file}:${O.line}:${O.column}`),F.push(...O.context),F.push("");if(A.length>=Z)F.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return qX(F.join(`
161
+ `))}let K;try{K=new RegExp(Y,"gim")}catch(F){throw Error(`Invalid regex pattern: ${Y}. ${F instanceof Error?F.message:""}`)}let G=[],R=0,D=await b1(V);for(let F of D){if(H.signal?.aborted)throw Error("Search operation aborted");if(!TU(F,f,X,j))continue;if(G.length>=Z)break;R++;let O=K5.join(V,F);try{let L=(await NX.readFile(O,"utf-8")).split(`
162
162
  `);for(let z=0;z<L.length;z++){let P=L[z];K.lastIndex=0;let S=K.exec(P);while(S!==null){if(G.length>=Z)break;let b=Math.max(0,z-W),u=Math.min(L.length-1,z+W),o=[];for(let J0=b;J0<=u;J0++){let t=J0===z?">":" ";o.push(`${t} ${J0+1}: ${L[J0]}`)}if(G.push({file:F,line:z+1,column:S.index+1,match:S[0],context:o}),S.index===K.lastIndex)K.lastIndex++;S=K.exec(P)}}}catch{}}if(G.length===0)return`No results found for pattern: ${Y}
163
- Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=Z)U.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return PX(U.join(`
164
- `))}}function PX($){if($.length<=i2)return $;let J=Math.ceil(i2/2),Q=Math.max(1,i2-J);return`${$.slice(0,J)}
163
+ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${Y}`,`Searched ${R} files.`,""];for(let F of G)U.push(`${F.file}:${F.line}:${F.column}`),U.push(...F.context),U.push("");if(G.length>=Z)U.push(`(Showing first ${Z} results. Refine your search for more specific results.)`);return qX(U.join(`
164
+ `))}}function qX($){if($.length<=i2)return $;let J=Math.ceil(i2/2),Q=Math.max(1,i2-J);return`${$.slice(0,J)}
165
165
  [... search output truncated: ${$.length} chars total. Narrow the pattern or scope to view the elided matches ...]
166
166
  `+$.slice(-Q)}function MU($){return $.replace(/<script[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<!--[\s\S]*?-->/g,"").replace(/<(p|div|br|hr|h[1-6]|li|tr)[^>]*>/gi,`
167
167
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(J,Q)=>String.fromCharCode(parseInt(Q,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
@@ -169,7 +169,7 @@ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for
169
169
 
170
170
  `).trim()}function d4($={}){let{timeoutMs:J=30000,maxResponseBytes:Q=5000000,userAgent:Z="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:W={},followRedirects:j=!0}=$;return async(f,X,Y)=>{let V;try{V=new URL(f)}catch{throw Error(`Invalid URL: ${f}`)}if(!["http:","https:"].includes(V.protocol))throw Error(`Invalid protocol: ${V.protocol}. Only http and https are supported.`);let H=new AbortController,B=setTimeout(()=>H.abort(),J),A;if(Y.signal)A=()=>H.abort(),Y.signal.addEventListener("abort",A);try{let K=await fetch(f,{method:"GET",headers:{"User-Agent":Z,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",...W},redirect:j?"follow":"manual",signal:H.signal});if(clearTimeout(B),!j&&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 D=[],U=0;while(!0){let{done:P,value:S}=await R.read();if(P)break;if(U+=S.length,U>Q)throw R.cancel(),Error(`Response too large: exceeded ${Q} bytes`);D.push(S)}let F=new Uint8Array(U),O=0;for(let P of D)F.set(P,O),O+=P.length;let T=new TextDecoder("utf-8").decode(F),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=MU(T);else if(G.includes("application/json"))try{let P=JSON.parse(T);L=JSON.stringify(P,null,2)}catch{L=T}else L=T;let z=[`URL: ${f}`,`Content-Type: ${G}`,`Size: ${U} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)z.push(`
171
171
  [Content truncated: showing first 50000 of ${L.length} characters]`);return z.push("","--- Analysis Request ---",`Prompt: ${X}`),z.join(`
172
- `)}catch(K){if(clearTimeout(B),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${J}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function s2($={}){return{readFile:c4($.fileRead),search:u4($.search),bash:g4($.bash),webFetch:d4($.webFetch),applyPatch:m4($.applyPatch),editor:v4($.editor)}}var qU={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"},o2=[{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 SX($,J){if(!J||J.length===0)return!0;let Q=$.toLowerCase();return J.some((Z)=>Q.includes(Z.toLowerCase()))}function PU($,J,Q,Z){if($.mode&&$.mode!=="any"&&$.mode!==Z)return!1;return SX(J,$.providerIdIncludes)&&SX(Q,$.modelIdIncludes)}function t2($,J,Q,Z){if(!Z||Z.length===0)return{};let W=new Map;for(let f of Z){if(!PU(f,$,J,Q))continue;for(let X of f.disableTools??[])W.set(X,!1);for(let X of f.enableTools??[])W.set(X,!0)}let j={};for(let[f,X]of W.entries())j[qU[f]]=X;return j}var c0={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 h1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function G5($){if($!=="yolo")return{};let J={enabled:!0,autoApprove:!0},Q={"*":J};for(let Z of W$)Q[Z]=J;return Q}function F5($,J){let Q=c0[$],{enableSpawnAgent:Z,enableAgentTeams:W,...j}=Q;return X$({...j,...J})}import{createTool as dR,zodToJsonSchema as lR}from"@cline/shared";import{z as sZ}from"zod";W1();import{createAgentRuntime as yR}from"@cline/agents";import{createContributionRegistry as ER,mergeModelOptions as tX}from"@cline/shared";import{createGateway as pU,createHandlerAsync as rU,hasRegisteredHandler as iU,MODEL_COLLECTIONS_BY_PROVIDER_ID as nU,normalizeProviderId as aU}from"@cline/llms";import{EMPTY_CONTENT_TEXT as IU}from"@cline/shared";function xU($){let J=mU($.content),Q=[],Z=$.id??uU(),W=0,j=[],f=()=>{if(j.length===0)return;let X=W===0?Z:`${Z}_part_${W}`;W+=1,Q.push({id:X,role:$.role,content:j.map(vU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:mX($.metrics)}),j=[]};if(J.length===0)return Q.push({id:Z,role:$.role,content:[{type:"text",text:IU}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:mX($.metrics)}),Q;for(let X of J){if(X.type!=="tool_result"){j.push(X);continue}f(),Q.push({id:`${Z}_tool_${X.tool_use_id}`,role:"tool",content:[cX(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return f(),Q}function O5($){return $.flatMap(xU)}function gU($){let J=$.content.map(uX).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:J,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:cU($.metrics)}}function $8($){return $.map(gU)}function T5($){let J=[];for(let Q of $){let Z=Q.content.map(uX).filter((f)=>f!==void 0),W=Q.role==="tool"?"user":Q.role,j=J[J.length-1];if(W==="user"&&Z.length>0&&Z.every((f)=>f.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((f)=>f.type==="tool_result")){j.content.push(...Z);continue}J.push({role:W,content:Z})}return J}function mU($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function vU($){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 cX($)}}function cX($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function uX($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let J=$.metadata;return{type:"thinking",thinking:$.text,signature:J?.signature,details:J?.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 J=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:J?.thoughtSignature??J?.signature}}case"tool-result":{let J=$.output,Q=typeof J==="string"?J:Array.isArray(J)?J:JSON.stringify(J);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function mX($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function cU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var vX=0;function uU(){return vX+=1,`msg_${Date.now().toString(36)}_${vX.toString(36)}`}function dU($){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 J=$.tool_call.function,Q=J.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??J.id,toolName:J.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:lU($),error:$.error}];default:return[]}}function lU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function dX($){return{async*stream(J){let Q=!1,Z=!1;try{let W=typeof $==="function"?await $():$;W.setAbortSignal?.(J.signal);let j=T5(J.messages),f=J.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of W.createMessage(J.systemPrompt??"",j,f))for(let Y of dU(X)){if(Y.type==="finish")Q=!0;else if(Y.type==="tool-call-delta")Z=!0;yield Y}if(!Q)yield{type:"finish",reason:Z?"tool-calls":"stop"}}catch(W){if(!Q)yield{type:"finish",reason:J.signal?.aborted?"aborted":"error",error:W instanceof Error?W.message:String(W)}}}}}function sU($){let J=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(J).length>0?J:void 0}function oU($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function tU($){let J={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(oU($))Object.assign(J,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(J,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Q=$.gcp?.region??$.region;Object.assign(J,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}return sU(J)}function xZ($){let J=$.providerConfig;if(J?.knownModels)return J.knownModels;if($.knownModels)return $.knownModels;return nU[$.providerId]?.models??void 0}function eU($){if(!$?.length)return;let J=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":J.add(Q);break;case"structured_output":J.add("structured-output");break;default:J.add("text")}return J.add("text"),[...J]}function $R($,J){return{id:$,name:J.name??$,description:J.description,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxOutputTokens:J.maxTokens,capabilities:eU(J.capabilities),metadata:{family:J.family,pricing:J.pricing,status:J.status,releaseDate:J.releaseDate}}}function lX($,J,Q){let Z=$.providerConfig,W=Z?.providerId===$.providerId?Z:void 0,j={...W??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.headers??W?.headers,knownModels:xZ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:J,extensionContext:$.extensionContext};if(iU(aU(j.providerId)))return dX(()=>rU(j));return pU({providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,options:tU(j),models:j.knownModels?Object.entries(j.knownModels).map(([f,X])=>$R(f,X)):void 0}],logger:J,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as JR,IMAGE_OMITTED_PLACEHOLDER as pX,normalizeUserInput as rX,resolveMediaBudget as QR,validateAndReserveImageMedia as ZR}from"@cline/shared";var WR=50000,jR=6000000,iX=8000,fR=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),XR=new Set(["read","read_files"]),d$="[outdated - see the latest file content]",nX="Tool execution was interrupted before a result was produced.",YR=($)=>`
172
+ `)}catch(K){if(clearTimeout(B),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${J}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(Y.signal&&A)Y.signal.removeEventListener("abort",A)}}}function s2($={}){return{readFile:c4($.fileRead),search:u4($.search),bash:g4($.bash),webFetch:d4($.webFetch),applyPatch:m4($.applyPatch),editor:v4($.editor)}}var qU={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"},o2=[{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 wX($,J){if(!J||J.length===0)return!0;let Q=$.toLowerCase();return J.some((Z)=>Q.includes(Z.toLowerCase()))}function PU($,J,Q,Z){if($.mode&&$.mode!=="any"&&$.mode!==Z)return!1;return wX(J,$.providerIdIncludes)&&wX(Q,$.modelIdIncludes)}function t2($,J,Q,Z){if(!Z||Z.length===0)return{};let W=new Map;for(let f of Z){if(!PU(f,$,J,Q))continue;for(let X of f.disableTools??[])W.set(X,!1);for(let X of f.enableTools??[])W.set(X,!0)}let j={};for(let[f,X]of W.entries())j[qU[f]]=X;return j}var c0={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 h1($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function G5($){if($!=="yolo")return{};let J={enabled:!0,autoApprove:!0},Q={"*":J};for(let Z of W$)Q[Z]=J;return Q}function F5($,J){let Q=c0[$],{enableSpawnAgent:Z,enableAgentTeams:W,...j}=Q;return X$({...j,...J})}import{createTool as dR,zodToJsonSchema as lR}from"@cline/shared";import{z as sZ}from"zod";W1();import{createAgentRuntime as yR}from"@cline/agents";import{createContributionRegistry as ER,mergeModelOptions as oX}from"@cline/shared";import{createGateway as pU,createHandlerAsync as rU,hasRegisteredHandler as iU,MODEL_COLLECTIONS_BY_PROVIDER_ID as nU,normalizeProviderId as aU}from"@cline/llms";import{EMPTY_CONTENT_TEXT as IU}from"@cline/shared";function xU($){let J=mU($.content),Q=[],Z=$.id??uU(),W=0,j=[],f=()=>{if(j.length===0)return;let X=W===0?Z:`${Z}_part_${W}`;W+=1,Q.push({id:X,role:$.role,content:j.map(vU),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:gX($.metrics)}),j=[]};if(J.length===0)return Q.push({id:Z,role:$.role,content:[{type:"text",text:IU}],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:gX($.metrics)}),Q;for(let X of J){if(X.type!=="tool_result"){j.push(X);continue}f(),Q.push({id:`${Z}_tool_${X.tool_use_id}`,role:"tool",content:[vX(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return f(),Q}function O5($){return $.flatMap(xU)}function gU($){let J=$.content.map(cX).filter((Q)=>Q!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:J,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:cU($.metrics)}}function $8($){return $.map(gU)}function T5($){let J=[];for(let Q of $){let Z=Q.content.map(cX).filter((f)=>f!==void 0),W=Q.role==="tool"?"user":Q.role,j=J[J.length-1];if(W==="user"&&Z.length>0&&Z.every((f)=>f.type==="tool_result")&&j?.role==="user"&&Array.isArray(j.content)&&j.content.every((f)=>f.type==="tool_result")){j.content.push(...Z);continue}J.push({role:W,content:Z})}return J}function mU($){if(typeof $==="string")return $.trim().length>0?[{type:"text",text:$}]:[];return[...$]}function vU($){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 vX($)}}function vX($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function cX($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let J=$.metadata;return{type:"thinking",thinking:$.text,signature:J?.signature,details:J?.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 J=$.metadata;return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:J?.thoughtSignature??J?.signature}}case"tool-result":{let J=$.output,Q=typeof J==="string"?J:Array.isArray(J)?J:JSON.stringify(J);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:Q,is_error:$.isError}}}}function gX($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function cU($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var mX=0;function uU(){return mX+=1,`msg_${Date.now().toString(36)}_${mX.toString(36)}`}function dU($){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 J=$.tool_call.function,Q=J.arguments;return[{type:"tool-call-delta",toolCallId:$.tool_call.call_id??J.id,toolName:J.name,inputText:typeof Q==="string"?Q:void 0,input:typeof Q==="string"?void 0:Q,...$.signature?{metadata:{thoughtSignature:$.signature}}:{}}]}case"usage":return[{type:"usage",usage:{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost}}];case"done":return[{type:"finish",reason:lU($),error:$.error}];default:return[]}}function lU($){if($.success===!1)return"error";if($.incompleteReason==="max_output_tokens"||$.incompleteReason==="max-tokens")return"max-tokens";return"stop"}function uX($){return{async*stream(J){let Q=!1,Z=!1;try{let W=typeof $==="function"?await $():$;W.setAbortSignal?.(J.signal);let j=T5(J.messages),f=J.tools.map((X)=>({name:X.name,description:X.description,inputSchema:X.inputSchema}));for await(let X of W.createMessage(J.systemPrompt??"",j,f))for(let Y of dU(X)){if(Y.type==="finish")Q=!0;else if(Y.type==="tool-call-delta")Z=!0;yield Y}if(!Q)yield{type:"finish",reason:Z?"tool-calls":"stop"}}catch(W){if(!Q)yield{type:"finish",reason:J.signal?.aborted?"aborted":"error",error:W instanceof Error?W.message:String(W)}}}}}function sU($){let J=Object.fromEntries(Object.entries($).filter(([,Q])=>Q!==void 0));return Object.keys(J).length>0?J:void 0}function oU($){return $.providerId==="openai-compatible"||$.clientType==="openai-compatible"}function tU($){let J={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if(oU($))Object.assign(J,{apiVersion:$.azure?.apiVersion,useIdentity:$.azure?.useIdentity});if($.providerId==="bedrock")Object.assign(J,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let Q=$.gcp?.region??$.region;Object.assign(J,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:Q,region:Q})}return sU(J)}function xZ($){let J=$.providerConfig;if(J?.knownModels)return J.knownModels;if($.knownModels)return $.knownModels;return nU[$.providerId]?.models??void 0}function eU($){if(!$?.length)return;let J=new Set;for(let Q of $)switch(Q){case"tools":case"reasoning":case"prompt-cache":case"images":J.add(Q);break;case"structured_output":J.add("structured-output");break;default:J.add("text")}return J.add("text"),[...J]}function $R($,J){return{id:$,name:J.name??$,description:J.description,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxOutputTokens:J.maxTokens,capabilities:eU(J.capabilities),metadata:{family:J.family,pricing:J.pricing,status:J.status,releaseDate:J.releaseDate}}}function dX($,J,Q){let Z=$.providerConfig,W=Z?.providerId===$.providerId?Z:void 0,j={...W??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.headers??W?.headers,knownModels:xZ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:J,extensionContext:$.extensionContext};if(iU(aU(j.providerId)))return uX(()=>rU(j));return pU({providerConfigs:[{providerId:j.providerId,apiKey:j.apiKey,baseUrl:j.baseUrl,headers:j.headers,options:tU(j),models:j.knownModels?Object.entries(j.knownModels).map(([f,X])=>$R(f,X)):void 0}],logger:J,telemetry:Q??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:j.providerId,modelId:j.modelId},{maxTokens:j.maxOutputTokens})}import{createMediaBudgetState as JR,IMAGE_OMITTED_PLACEHOLDER as lX,normalizeUserInput as pX,resolveMediaBudget as QR,validateAndReserveImageMedia as ZR}from"@cline/shared";var WR=50000,jR=6000000,rX=8000,fR=new Set(["read","read_files","search","search_codebase","bash","run_commands","fetch_web_content"]),XR=new Set(["read","read_files"]),d$="[outdated - see the latest file content]",iX="Tool execution was interrupted before a result was produced.",YR=($)=>`
173
173
 
174
174
  ...[truncated ${$} chars]...
175
175
 
@@ -177,19 +177,19 @@ Searched ${R} files.`;let U=[`Found ${G.length} result${G.length===1?"":"s"} for
177
177
 
178
178
  ...[truncated ${$} chars to fit provider request budget]...
179
179
 
180
- `;class uZ{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=WR,J=fR,Q=jR,Z={}){this.maxToolResultChars=$;this.targetToolNames=J;this.maxTotalTextBytes=Q;this.mediaBudget=Z}buildForApi($){this.reindex($);let Q=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let X=rX(W.content);if(X!==W.content)return{...W,content:X}}return W}let j=!1,f=W.content.map((X)=>{let Y=this.transformBlock(X,W.role);if(Y!==X)j=!0;return Y});return j?{...W,content:f}:W}),Z=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(Z)}transformBlock($,J){if(J==="user"&&$.type==="text"&&typeof $.text==="string"){let W=rX($.text);if(W!==$.text)return{...$,text:W};return $}if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="tool_result")return $;let Q=this.toolNameByIdCache.get($.tool_use_id),Z=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let W=this.getReadLocators($);if(W.length>0){let j=W.filter((f)=>this.isOutdatedReadLocator(f,$.tool_use_id));if(j.length>0)Z=this.replaceOutdatedReadContent(Z,j)}}if(this.shouldTruncateTool(Q))Z=this.truncateToolResultContent(Z);return Z===$.content?$:{...$,content:Z}}reindex($){let J=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!J)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let Z=$[Q];if(!Array.isArray(Z.content))continue;for(let W=0;W<Z.content.length;W++){let j=Z.content[W];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Q}:${W}`);else if(j.type==="tool_use"){let f=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,f),this.isReadTool(f)){let X=this.extractLocatorsFromReadToolInput(j.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(j.id,X)}}else if(j.type==="tool_result"){let f=this.toolNameByIdCache.get(j.tool_use_id);if(!this.isReadTool(f)||j.is_error===!0)continue;let X=this.getReadLocators(j);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),j.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let J=this.collectToolResultIds($),Q=[],Z=new Map,W=!1,j=()=>{if(Z.size===0)return;f(this.createMissingToolResultMessage(Z)),Z.clear(),W=!0},f=(X)=>{let Y=Q.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){Q[Q.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},W=!0;return}Q.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(f(this.appendMissingToolResults(X,Z)),Z.size>0)Z.clear(),W=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((H)=>H.type==="tool_result"),V=X.content.filter((H)=>H.type!=="tool_result");if(Y.length>0){let H=this.appendMissingToolResults({...X,role:"user",content:Y},Z);if(f(H),Z.size>0)Z.clear();W=!0}if(V.length>0||Y.length===0){if(Y.length===0)j();let H=Y.length>0?{...X,content:V}:X;if(f(H),H.role==="assistant")this.trackMissingToolCalls(H,J,Z)}continue}j(),f(X)}return j(),W?Q:$}appendMissingToolResults($,J){if(J.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(J)]}}shouldMergeUserAfterToolResults($,J){return $?.role==="user"&&J.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(J.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let J=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content)if(Z.type==="tool_result")J.add(Z.tool_use_id)}return J}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((J)=>J.type==="tool_result")}trackMissingToolCalls($,J,Q){if(!Array.isArray($.content))return;for(let Z of $.content){if(Z.type!=="tool_use"||J.has(Z.id))continue;Q.set(Z.id,Z.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([J,Q])=>({type:"tool_result",tool_use_id:J,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${nX} Tool: ${$}.`:nX}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 J=$,Q=this.readResultLocatorCache.get(J);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(J,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let J=$,Q=[],Z=this.extractLocatorFromReadRequest(J);if(Z)Q.push(Z);if(Array.isArray(J.files))for(let W of J.files){let j=this.extractLocatorFromReadRequest(W);if(j)Q.push(j)}if(Array.isArray(J.file_paths)){for(let W of J.file_paths)if(typeof W==="string"&&W.length>0)Q.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let J of $){if(J.type!=="text")continue;let Q=this.tryParseReadLocators(J.text);if(Q.length>0)return Q}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let Z of $){let W=this.extractLocatorFromResultEntry(Z);if(W)Q.push(W)}return this.dedupeReadLocators(Q)}let J=this.extractLocatorFromResultEntry($);return J?[J]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(Q)return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)};if(typeof J.query==="string"&&J.query.length>0)return this.parseReadQuery(J.query);return}extractPath($){let J=[$.path,$.file_path,$.filePath];for(let Q of J)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let J=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!J)return{path:$,startLine:null,endLine:null};return{path:J[1],startLine:Number(J[2]),endLine:J[3]==="EOF"?null:Number(J[3])}}dedupeReadLocators($){let J=new Map;for(let Q of $)J.set(this.toReadLocatorKey(Q),Q);return Array.from(J.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,J){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==J)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==J}replaceOutdatedReadContent($,J){let Q=new Set(J.map((j)=>this.toReadLocatorKey(j))),Z=new Set(J.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??d$;let W=0;for(let j of $)if(j.type==="text")W+=this.countOutdatedImageEntries(j.text,Q);return $.map((j)=>{if(j.type==="file"){if(!Z.has(j.path))return j;return{...j,content:d$}}if(j.type==="image"){if(W===0)return j;return W-=1,{type:"text",text:d$}}if(j.type!=="text")return j;let f=this.replaceOutdatedInString(j.text,Q);if(f===null)return{...j,text:d$};return f===j.text?j:{...j,text:f}})}countOutdatedImageEntries($,J){let Q;try{Q=JSON.parse($)}catch{return 0}let Z=Array.isArray(Q)?Q:[Q],W=0;for(let j of Z){if(!j||typeof j!=="object")continue;let f=j,X=this.extractLocatorFromResultEntry(f);if(!X)continue;if(!J.has(this.toReadLocatorKey(X)))continue;if(f.result==="Successfully read image"||f.content==="Successfully read image")W+=1}return W}replaceOutdatedInString($,J){let Q;try{Q=JSON.parse($)}catch{return null}let Z=Array.isArray(Q)?Q.map((W)=>this.replaceOutdatedReadEntry(W,J)):this.replaceOutdatedReadEntry(Q,J);return JSON.stringify(Z)}replaceOutdatedReadEntry($,J){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!J.has(this.toReadLocatorKey(Q)))return $;let Z={...$};if(typeof Z.result==="string")Z.result=d$;else if(typeof Z.content==="string")Z.content=d$;else Z.result=d$;return Z}isReadTool($){return!!$&&XR.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((J)=>{if(J.type==="file"){let Q=this.truncateMiddle(J.content);return Q===J.content?J:{...J,content:Q}}if(J.type==="text"){let Q=this.truncateMiddle(J.text);return Q===J.text?J:{...J,text:Q}}if(r4(J))return this.truncateNestedStrings(J);return J})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let J=!1,Q=$.map((Z)=>{let W=this.truncateNestedStrings(Z);if(W!==Z)J=!0;return W});return J?Q:$}if($!==null&&typeof $==="object"){if(M5($))return $;let J=!1,Q={};for(let[Z,W]of Object.entries($)){let j=this.truncateNestedStrings(W);if(j!==W)J=!0;Q[Z]=j}return J?Q:$}return $}truncateMiddle($){return gZ($,this.maxToolResultChars,YR)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let J=this.countMessageTextBytes($);if(J<=this.maxTotalTextBytes)return $;let Q=$.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((j)=>BR(j))}}),Z=this.collectTruncationCandidates(Q);for(let W of Z){if(J<=this.maxTotalTextBytes)break;let j=W.byteLength;if(j<=iX)continue;let f=J-this.maxTotalTextBytes,X=Math.max(iX,j-f),Y=HR(W.get(),X,VR);W.set(Y),J-=j-D0(Y)}return Q}countMessageTextBytes($){let J=0;for(let Q of $){if(typeof Q.content==="string"){J+=D0(Q.content);continue}for(let Z of Q.content)if(Z.type==="text")J+=D0(Z.text);else if(Z.type==="thinking")J+=D0(Z.thinking);else if(Z.type==="file")J+=D0(Z.content);else if(Z.type==="tool_result"){if(typeof Z.content==="string")J+=D0(Z.content);else for(let W of Z.content)if(W.type==="text")J+=D0(W.text);else if(W.type==="file")J+=D0(W.content);else if(r4(W))J+=mZ(W)}}return J}collectTruncationCandidates($){let J=[];for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content){if(Z.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(Z.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof Z.content==="string"){J.push({byteLength:D0(Z.content),get:()=>Z.content,set:(j)=>{Z.content=j}});continue}for(let j of Z.content)if(j.type==="text")J.push({byteLength:D0(j.text),get:()=>j.text,set:(f)=>{j.text=f}});else if(j.type==="file")J.push({byteLength:D0(j.content),get:()=>j.content,set:(f)=>{j.content=f}});else if(r4(j))vZ(j,J)}}return J.sort((Q,Z)=>Z.byteLength-Q.byteLength)}applyMediaBudget($){let J=this.resolveMediaBudget();if(J.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&J.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&J.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=JR(),Z=!1,W=$.map((j)=>{if(!Array.isArray(j.content))return j;let f=!1,X=j.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,J,Q);if(V!==Y)f=!0;return V});if(!f)return j;return Z=!0,{...j,content:X}});return Z?W:$}resolveMediaBudget(){return QR(this.mediaBudget)}applyMediaBudgetToBlock($,J,Q){if(M5($))return this.limitImageContent($,J,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let Z=!1,W=$.content.map((j)=>{let f=this.applyMediaBudgetToToolResultEntry(j,J,Q);if(f!==j)Z=!0;return f});return Z?{...$,content:W}:$}applyMediaBudgetToToolResultEntry($,J,Q){if(M5($))return this.limitImageContent($,J,Q);if(r4($))return this.limitNestedMedia($,J,Q);return $}limitNestedMedia($,J,Q){if(M5($)){let Z=this.limitImageContent($,J,Q);return Z.type==="text"?Z.text:Z}if(Array.isArray($)){let Z=!1,W=$.map((j)=>{let f=this.limitNestedMedia(j,J,Q);if(f!==j)Z=!0;return f});return Z?W:$}if($!==null&&typeof $==="object"){let Z=!1,W={};for(let[j,f]of Object.entries($)){let X=this.limitNestedMedia(f,J,Q);if(X!==f)Z=!0;W[j]=X}return Z?W:$}return $}limitImageContent($,J,Q){if(!dZ($))return{type:"text",text:pX};let Z=ZR($.mediaType,$.data,{maxImageEncodedBytes:J.maxImageEncodedBytes,maxImageDecodedBytes:J.maxImageDecodedBytes,maxTotalMediaBytes:J.maxTotalMediaBytes},Q);if(!Z.ok)return{type:"text",text:pX};return{...$,data:Z.base64,mediaType:Z.mediaType}}}function D0($){return Buffer.byteLength($,"utf8")}function gZ($,J,Q){if($.length<=J)return $;let Z=Q($.length-J),W=Math.max(0,Math.floor((J-Z.length)/2)),j=Math.max(0,$.length-W*2),f=Q(j),X=Math.max(0,Math.floor((J-f.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${f}${V}`}function HR($,J,Q){if(D0($)<=J)return $;let Z=0,W=$.length,j=gZ($,0,Q);while(Z<=W){let f=Z+W>>>1,X=gZ($,f,Q);if(D0(X)<=J)j=X,Z=f+1;else W=f-1}return j}function BR($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((J)=>r4(J)?cZ(J):{...J})}}function r4($){if($===null||typeof $!=="object")return!1;let J=$.type;return J!=="text"&&J!=="image"&&J!=="file"}function M5($){return $!==null&&typeof $==="object"&&$.type==="image"}function dZ($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function mZ($){if(typeof $==="string")return D0($);if(Array.isArray($)){let J=0;for(let Q of $)J+=mZ(Q);return J}if($!==null&&typeof $==="object"){if(dZ($))return 0;let J=0;for(let Q of Object.values($))J+=mZ(Q);return J}return 0}function vZ($,J){if(Array.isArray($)){$.forEach((Q,Z)=>{if(typeof Q==="string")J.push({byteLength:D0(Q),get:()=>$[Z],set:(W)=>{$[Z]=W}});else vZ(Q,J)});return}if($!==null&&typeof $==="object"){if(dZ($))return;let Q=$;for(let Z of Object.keys(Q)){let W=Q[Z];if(typeof W==="string")J.push({byteLength:D0(W),get:()=>Q[Z],set:(j)=>{Q[Z]=j}});else vZ(W,J)}}}function cZ($){if(Array.isArray($))return $.map(cZ);if($!==null&&typeof $==="object"){let J={};for(let[Q,Z]of Object.entries($))J[Q]=cZ(Z);return J}return $}function lZ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class pZ{messages=[];conversationId=lZ();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=lZ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=lZ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function aX($){let{agentConfig:J}=$,Q=AR(J),Z=KR(J),W=$.hooks,j=GR(J.maxParallelToolCalls);return{sessionId:$.sessionId??J.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??J.systemPrompt,messageModelInfo:Z,model:$.model,modelOptions:Q,tools:$.tools,hooks:W,prepareTurn:$.prepareTurn,consumePendingUserMessage:J.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??J.logger,telemetry:$.telemetry??J.telemetry,initialMessages:$.initialMessages,completionPolicy:J.completionPolicy,maxIterations:J.maxIterations,toolExecution:j,toolPolicies:J.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:J.requestToolApproval}}function AR($){let J={};if($.thinking!==void 0)J.thinking=$.thinking;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)J.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)J.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(J).length>0?J:void 0}function KR($){let J=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:J}}function GR($){if($===void 0)return;return $>=2?"parallel":"sequential"}function FR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function DR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function rZ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(rZ);let J={};for(let Q of Object.keys($).sort())J[Q]=rZ($[Q]);return J}function UR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(rZ($))}catch{return String($)}}function RR($,J,Q,Z){if(J===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=J,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===Z.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Z.hardThreshold}}var sX={softThreshold:3,hardThreshold:5};class iZ{config;state=FR();constructor($){this.config={softThreshold:$?.softThreshold??sX.softThreshold,hardThreshold:$?.hardThreshold??sX.hardThreshold}}inspect($){let J=UR($.input),Q=RR(this.state,$.name,J,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){DR(this.state)}}class nZ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let J=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&J?J:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let Z=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Z),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!J||Q<J)return{action:"continue"};let W=await LR({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details},this.options.onLimitReached);if(W.action==="continue"){let j=W.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:W.reason?.trim()||void 0,message:zR({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function zR($){let J=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)J.push(`Error: ${Q}`);let Z=$.stopReason?.trim();if(Z)J.push(`Decision: ${Z}`);return J.push("Session state was preserved. Send a new prompt to resume from the latest state."),J.join(" ")}async function LR($,J){if(!J)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await J($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function _R($){let J=$.content.filter((Q)=>Q.type==="text");if(J.length===0)return;return J.map((Q)=>Q.text).join("")}function OR($){let J=$.content.filter((Q)=>Q.type==="reasoning");if(J.length===0)return;return{reasoning:J.map((Q)=>Q.text).join(""),redacted:J.some((Q)=>Q.redacted===!0)}}function TR($){return $.content.find((J)=>J.type==="tool-result")}function MR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function qR($){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 aZ{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 J=[],Q=_R($);if(Q!==void 0)J.push({type:"content_end",contentType:"text",text:Q});let Z=OR($);if(Z!==void 0)J.push({type:"content_end",contentType:"reasoning",reasoning:Z.reasoning});return J}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 J=this.toolStartedAt.get($.toolCall.toolCallId),Q=J===void 0?void 0:Date.now()-J;this.toolStartedAt.delete($.toolCall.toolCallId);let Z=TR($.message),W=Z?.output,j=qR(Z);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:W,error:j,durationMs:Q}]}translateUsage($){let J=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,Z=$.cacheReadTokens-this.lastUsage.cacheReadTokens,W=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,X=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,J),outputTokens:Math.max(0,Q),cacheReadTokens:Z===0?void 0:Math.max(0,Z),cacheWriteTokens:W===0?void 0:Math.max(0,W),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 J={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:MR($.status),text:$.outputText,iterations:$.iterations,usage:J}]}}function bR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function hR($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function kR($,J){let Q=$.trim(),Z=J.map((W)=>W.trim()).filter(Boolean).join(`
180
+ `;class uZ{maxToolResultChars;targetToolNames;maxTotalTextBytes;mediaBudget;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=WR,J=fR,Q=jR,Z={}){this.maxToolResultChars=$;this.targetToolNames=J;this.maxTotalTextBytes=Q;this.mediaBudget=Z}buildForApi($){this.reindex($);let Q=this.addMissingToolResults($).map((W)=>{if(!Array.isArray(W.content)){if(W.role==="user"&&typeof W.content==="string"){let X=pX(W.content);if(X!==W.content)return{...W,content:X}}return W}let j=!1,f=W.content.map((X)=>{let Y=this.transformBlock(X,W.role);if(Y!==X)j=!0;return Y});return j?{...W,content:f}:W}),Z=this.applyMediaBudget(Q);return this.truncateToTotalTextBudget(Z)}transformBlock($,J){if(J==="user"&&$.type==="text"&&typeof $.text==="string"){let W=pX($.text);if(W!==$.text)return{...$,text:W};return $}if($.type==="file"){let W=this.truncateMiddle($.content);return W===$.content?$:{...$,content:W}}if($.type!=="tool_result")return $;let Q=this.toolNameByIdCache.get($.tool_use_id),Z=$.content;if(this.isReadTool(Q)&&$.is_error!==!0){let W=this.getReadLocators($);if(W.length>0){let j=W.filter((f)=>this.isOutdatedReadLocator(f,$.tool_use_id));if(j.length>0)Z=this.replaceOutdatedReadContent(Z,j)}}if(this.shouldTruncateTool(Q))Z=this.truncateToolResultContent(Z);return Z===$.content?$:{...$,content:Z}}reindex($){let J=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!J)this.resetIndexes();for(let Q=this.indexedMessageCount;Q<$.length;Q++){let Z=$[Q];if(!Array.isArray(Z.content))continue;for(let W=0;W<Z.content.length;W++){let j=Z.content[W];if(j.type==="file")this.latestFullContentOwnerByPathCache.set(j.path,`file:${Q}:${W}`);else if(j.type==="tool_use"){let f=j.name.toLowerCase();if(this.toolNameByIdCache.set(j.id,f),this.isReadTool(f)){let X=this.extractLocatorsFromReadToolInput(j.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(j.id,X)}}else if(j.type==="tool_result"){let f=this.toolNameByIdCache.get(j.tool_use_id);if(!this.isReadTool(f)||j.is_error===!0)continue;let X=this.getReadLocators(j);for(let Y of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(Y),j.tool_use_id),this.isFullFileRead(Y))this.latestFullContentOwnerByPathCache.set(Y.path,j.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let J=this.collectToolResultIds($),Q=[],Z=new Map,W=!1,j=()=>{if(Z.size===0)return;f(this.createMissingToolResultMessage(Z)),Z.clear(),W=!0},f=(X)=>{let Y=Q.at(-1);if(this.shouldMergeUserAfterToolResults(Y,X)){Q[Q.length-1]={...Y,content:[...Y.content,...this.contentBlocksForUserMerge(X.content)]},W=!0;return}Q.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(f(this.appendMissingToolResults(X,Z)),Z.size>0)Z.clear(),W=!0;continue}if(Array.isArray(X.content)){let Y=X.content.filter((H)=>H.type==="tool_result"),V=X.content.filter((H)=>H.type!=="tool_result");if(Y.length>0){let H=this.appendMissingToolResults({...X,role:"user",content:Y},Z);if(f(H),Z.size>0)Z.clear();W=!0}if(V.length>0||Y.length===0){if(Y.length===0)j();let H=Y.length>0?{...X,content:V}:X;if(f(H),H.role==="assistant")this.trackMissingToolCalls(H,J,Z)}continue}j(),f(X)}return j(),W?Q:$}appendMissingToolResults($,J){if(J.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(J)]}}shouldMergeUserAfterToolResults($,J){return $?.role==="user"&&J.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(J.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let J=new Set;for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content)if(Z.type==="tool_result")J.add(Z.tool_use_id)}return J}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((J)=>J.type==="tool_result")}trackMissingToolCalls($,J,Q){if(!Array.isArray($.content))return;for(let Z of $.content){if(Z.type!=="tool_use"||J.has(Z.id))continue;Q.set(Z.id,Z.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([J,Q])=>({type:"tool_result",tool_use_id:J,name:Q,content:[{type:"text",text:this.formatMissingToolResultText(Q)}],is_error:!0}))}formatMissingToolResultText($){return $?`${iX} Tool: ${$}.`:iX}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 J=$,Q=this.readResultLocatorCache.get(J);if(Q===void 0)Q=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(J,Q);if(Q.length>0)return Q;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let J=$,Q=[],Z=this.extractLocatorFromReadRequest(J);if(Z)Q.push(Z);if(Array.isArray(J.files))for(let W of J.files){let j=this.extractLocatorFromReadRequest(W);if(j)Q.push(j)}if(Array.isArray(J.file_paths)){for(let W of J.file_paths)if(typeof W==="string"&&W.length>0)Q.push({path:W,startLine:null,endLine:null})}return this.dedupeReadLocators(Q)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let J of $){if(J.type!=="text")continue;let Q=this.tryParseReadLocators(J.text);if(Q.length>0)return Q}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let Q=[];for(let Z of $){let W=this.extractLocatorFromResultEntry(Z);if(W)Q.push(W)}return this.dedupeReadLocators(Q)}let J=this.extractLocatorFromResultEntry($);return J?[J]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(!Q)return;return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let J=$,Q=this.extractPath(J);if(Q)return{path:Q,startLine:this.extractLineNumber(J.start_line),endLine:this.extractLineNumber(J.end_line)};if(typeof J.query==="string"&&J.query.length>0)return this.parseReadQuery(J.query);return}extractPath($){let J=[$.path,$.file_path,$.filePath];for(let Q of J)if(typeof Q==="string"&&Q.length>0)return Q;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let J=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!J)return{path:$,startLine:null,endLine:null};return{path:J[1],startLine:Number(J[2]),endLine:J[3]==="EOF"?null:Number(J[3])}}dedupeReadLocators($){let J=new Map;for(let Q of $)J.set(this.toReadLocatorKey(Q),Q);return Array.from(J.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,J){let Q=this.latestFullContentOwnerByPathCache.get($.path);if(Q&&Q!==J)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==J}replaceOutdatedReadContent($,J){let Q=new Set(J.map((j)=>this.toReadLocatorKey(j))),Z=new Set(J.map((j)=>j.path));if(typeof $==="string")return this.replaceOutdatedInString($,Q)??d$;let W=0;for(let j of $)if(j.type==="text")W+=this.countOutdatedImageEntries(j.text,Q);return $.map((j)=>{if(j.type==="file"){if(!Z.has(j.path))return j;return{...j,content:d$}}if(j.type==="image"){if(W===0)return j;return W-=1,{type:"text",text:d$}}if(j.type!=="text")return j;let f=this.replaceOutdatedInString(j.text,Q);if(f===null)return{...j,text:d$};return f===j.text?j:{...j,text:f}})}countOutdatedImageEntries($,J){let Q;try{Q=JSON.parse($)}catch{return 0}let Z=Array.isArray(Q)?Q:[Q],W=0;for(let j of Z){if(!j||typeof j!=="object")continue;let f=j,X=this.extractLocatorFromResultEntry(f);if(!X)continue;if(!J.has(this.toReadLocatorKey(X)))continue;if(f.result==="Successfully read image"||f.content==="Successfully read image")W+=1}return W}replaceOutdatedInString($,J){let Q;try{Q=JSON.parse($)}catch{return null}let Z=Array.isArray(Q)?Q.map((W)=>this.replaceOutdatedReadEntry(W,J)):this.replaceOutdatedReadEntry(Q,J);return JSON.stringify(Z)}replaceOutdatedReadEntry($,J){if(!$||typeof $!=="object")return $;let Q=this.extractLocatorFromResultEntry($);if(!Q||!J.has(this.toReadLocatorKey(Q)))return $;let Z={...$};if(typeof Z.result==="string")Z.result=d$;else if(typeof Z.content==="string")Z.content=d$;else Z.result=d$;return Z}isReadTool($){return!!$&&XR.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((J)=>{if(J.type==="file"){let Q=this.truncateMiddle(J.content);return Q===J.content?J:{...J,content:Q}}if(J.type==="text"){let Q=this.truncateMiddle(J.text);return Q===J.text?J:{...J,text:Q}}if(r4(J))return this.truncateNestedStrings(J);return J})}truncateNestedStrings($){if(typeof $==="string")return this.truncateMiddle($);if(Array.isArray($)){let J=!1,Q=$.map((Z)=>{let W=this.truncateNestedStrings(Z);if(W!==Z)J=!0;return W});return J?Q:$}if($!==null&&typeof $==="object"){if(M5($))return $;let J=!1,Q={};for(let[Z,W]of Object.entries($)){let j=this.truncateNestedStrings(W);if(j!==W)J=!0;Q[Z]=j}return J?Q:$}return $}truncateMiddle($){return gZ($,this.maxToolResultChars,YR)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let J=this.countMessageTextBytes($);if(J<=this.maxTotalTextBytes)return $;let Q=$.map((W)=>{if(!Array.isArray(W.content))return W;return{...W,content:W.content.map((j)=>BR(j))}}),Z=this.collectTruncationCandidates(Q);for(let W of Z){if(J<=this.maxTotalTextBytes)break;let j=W.byteLength;if(j<=rX)continue;let f=J-this.maxTotalTextBytes,X=Math.max(rX,j-f),Y=HR(W.get(),X,VR);W.set(Y),J-=j-D0(Y)}return Q}countMessageTextBytes($){let J=0;for(let Q of $){if(typeof Q.content==="string"){J+=D0(Q.content);continue}for(let Z of Q.content)if(Z.type==="text")J+=D0(Z.text);else if(Z.type==="thinking")J+=D0(Z.thinking);else if(Z.type==="file")J+=D0(Z.content);else if(Z.type==="tool_result"){if(typeof Z.content==="string")J+=D0(Z.content);else for(let W of Z.content)if(W.type==="text")J+=D0(W.text);else if(W.type==="file")J+=D0(W.content);else if(r4(W))J+=mZ(W)}}return J}collectTruncationCandidates($){let J=[];for(let Q of $){if(!Array.isArray(Q.content))continue;for(let Z of Q.content){if(Z.type!=="tool_result")continue;let W=this.toolNameByIdCache.get(Z.tool_use_id);if(!this.shouldTruncateTool(W))continue;if(typeof Z.content==="string"){J.push({byteLength:D0(Z.content),get:()=>Z.content,set:(j)=>{Z.content=j}});continue}for(let j of Z.content)if(j.type==="text")J.push({byteLength:D0(j.text),get:()=>j.text,set:(f)=>{j.text=f}});else if(j.type==="file")J.push({byteLength:D0(j.content),get:()=>j.content,set:(f)=>{j.content=f}});else if(r4(j))vZ(j,J)}}return J.sort((Q,Z)=>Z.byteLength-Q.byteLength)}applyMediaBudget($){let J=this.resolveMediaBudget();if(J.maxImageEncodedBytes===Number.POSITIVE_INFINITY&&J.maxImageDecodedBytes===Number.POSITIVE_INFINITY&&J.maxTotalMediaBytes===Number.POSITIVE_INFINITY)return $;let Q=JR(),Z=!1,W=$.map((j)=>{if(!Array.isArray(j.content))return j;let f=!1,X=j.content.map((Y)=>{let V=this.applyMediaBudgetToBlock(Y,J,Q);if(V!==Y)f=!0;return V});if(!f)return j;return Z=!0,{...j,content:X}});return Z?W:$}resolveMediaBudget(){return QR(this.mediaBudget)}applyMediaBudgetToBlock($,J,Q){if(M5($))return this.limitImageContent($,J,Q);if($.type!=="tool_result"||typeof $.content==="string")return $;let Z=!1,W=$.content.map((j)=>{let f=this.applyMediaBudgetToToolResultEntry(j,J,Q);if(f!==j)Z=!0;return f});return Z?{...$,content:W}:$}applyMediaBudgetToToolResultEntry($,J,Q){if(M5($))return this.limitImageContent($,J,Q);if(r4($))return this.limitNestedMedia($,J,Q);return $}limitNestedMedia($,J,Q){if(M5($)){let Z=this.limitImageContent($,J,Q);return Z.type==="text"?Z.text:Z}if(Array.isArray($)){let Z=!1,W=$.map((j)=>{let f=this.limitNestedMedia(j,J,Q);if(f!==j)Z=!0;return f});return Z?W:$}if($!==null&&typeof $==="object"){let Z=!1,W={};for(let[j,f]of Object.entries($)){let X=this.limitNestedMedia(f,J,Q);if(X!==f)Z=!0;W[j]=X}return Z?W:$}return $}limitImageContent($,J,Q){if(!dZ($))return{type:"text",text:lX};let Z=ZR($.mediaType,$.data,{maxImageEncodedBytes:J.maxImageEncodedBytes,maxImageDecodedBytes:J.maxImageDecodedBytes,maxTotalMediaBytes:J.maxTotalMediaBytes},Q);if(!Z.ok)return{type:"text",text:lX};return{...$,data:Z.base64,mediaType:Z.mediaType}}}function D0($){return Buffer.byteLength($,"utf8")}function gZ($,J,Q){if($.length<=J)return $;let Z=Q($.length-J),W=Math.max(0,Math.floor((J-Z.length)/2)),j=Math.max(0,$.length-W*2),f=Q(j),X=Math.max(0,Math.floor((J-f.length)/2)),Y=$.slice(0,X),V=X>0?$.slice(-X):"";return`${Y}${f}${V}`}function HR($,J,Q){if(D0($)<=J)return $;let Z=0,W=$.length,j=gZ($,0,Q);while(Z<=W){let f=Z+W>>>1,X=gZ($,f,Q);if(D0(X)<=J)j=X,Z=f+1;else W=f-1}return j}function BR($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((J)=>r4(J)?cZ(J):{...J})}}function r4($){if($===null||typeof $!=="object")return!1;let J=$.type;return J!=="text"&&J!=="image"&&J!=="file"}function M5($){return $!==null&&typeof $==="object"&&$.type==="image"}function dZ($){return $!==null&&typeof $==="object"&&$.type==="image"&&typeof $.data==="string"&&typeof $.mediaType==="string"}function mZ($){if(typeof $==="string")return D0($);if(Array.isArray($)){let J=0;for(let Q of $)J+=mZ(Q);return J}if($!==null&&typeof $==="object"){if(dZ($))return 0;let J=0;for(let Q of Object.values($))J+=mZ(Q);return J}return 0}function vZ($,J){if(Array.isArray($)){$.forEach((Q,Z)=>{if(typeof Q==="string")J.push({byteLength:D0(Q),get:()=>$[Z],set:(W)=>{$[Z]=W}});else vZ(Q,J)});return}if($!==null&&typeof $==="object"){if(dZ($))return;let Q=$;for(let Z of Object.keys(Q)){let W=Q[Z];if(typeof W==="string")J.push({byteLength:D0(W),get:()=>Q[Z],set:(j)=>{Q[Z]=j}});else vZ(W,J)}}}function cZ($){if(Array.isArray($))return $.map(cZ);if($!==null&&typeof $==="object"){let J={};for(let[Q,Z]of Object.entries($))J[Q]=cZ(Z);return J}return $}function lZ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class pZ{messages=[];conversationId=lZ();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=lZ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=lZ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function nX($){let{agentConfig:J}=$,Q=AR(J),Z=KR(J),W=$.hooks,j=GR(J.maxParallelToolCalls);return{sessionId:$.sessionId??J.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??J.systemPrompt,messageModelInfo:Z,model:$.model,modelOptions:Q,tools:$.tools,hooks:W,prepareTurn:$.prepareTurn,consumePendingUserMessage:J.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??J.logger,telemetry:$.telemetry??J.telemetry,initialMessages:$.initialMessages,completionPolicy:J.completionPolicy,maxIterations:J.maxIterations,toolExecution:j,toolPolicies:J.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:J.requestToolApproval}}function AR($){let J={};if($.thinking!==void 0)J.thinking=$.thinking;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)J.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)J.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(J).length>0?J:void 0}function KR($){let J=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:J}}function GR($){if($===void 0)return;return $>=2?"parallel":"sequential"}function FR(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function DR($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function rZ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(rZ);let J={};for(let Q of Object.keys($).sort())J[Q]=rZ($[Q]);return J}function UR($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(rZ($))}catch{return String($)}}function RR($,J,Q,Z){if(J===$.lastToolName&&Q===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=J,$.lastToolSignature=Q,{softWarning:$.consecutiveIdenticalCount===Z.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Z.hardThreshold}}var aX={softThreshold:3,hardThreshold:5};class iZ{config;state=FR();constructor($){this.config={softThreshold:$?.softThreshold??aX.softThreshold,hardThreshold:$?.hardThreshold??aX.hardThreshold}}inspect($){let J=UR($.input),Q=RR(this.state,$.name,J,this.config);if(Q.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(Q.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){DR(this.state)}}class nZ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let J=this.options.maxConsecutiveMistakes,Q=$.forceAtLimit&&J?J:this.consecutiveMistakes+1;this.consecutiveMistakes=Q;let Z=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Z),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:Q,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!J||Q<J)return{action:"continue"};let W=await LR({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details},this.options.onLimitReached);if(W.action==="continue"){let j=W.guidance?.trim();if(j)this.options.appendRecoveryNotice(j,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:j}}return{action:"stop",reason:W.reason?.trim()||void 0,message:zR({iteration:$.iteration,consecutiveMistakes:Q,maxConsecutiveMistakes:J,reason:$.reason,details:$.details,stopReason:W.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function zR($){let J=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],Q=$.details?.trim();if(Q)J.push(`Error: ${Q}`);let Z=$.stopReason?.trim();if(Z)J.push(`Decision: ${Z}`);return J.push("Session state was preserved. Send a new prompt to resume from the latest state."),J.join(" ")}async function LR($,J){if(!J)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await J($)}catch(Q){return{action:"stop",reason:Q instanceof Error?Q.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function _R($){let J=$.content.filter((Q)=>Q.type==="text");if(J.length===0)return;return J.map((Q)=>Q.text).join("")}function OR($){let J=$.content.filter((Q)=>Q.type==="reasoning");if(J.length===0)return;return{reasoning:J.map((Q)=>Q.text).join(""),redacted:J.some((Q)=>Q.redacted===!0)}}function TR($){return $.content.find((J)=>J.type==="tool-result")}function MR($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function qR($){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 aZ{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 J=[],Q=_R($);if(Q!==void 0)J.push({type:"content_end",contentType:"text",text:Q});let Z=OR($);if(Z!==void 0)J.push({type:"content_end",contentType:"reasoning",reasoning:Z.reasoning});return J}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 J=this.toolStartedAt.get($.toolCall.toolCallId),Q=J===void 0?void 0:Date.now()-J;this.toolStartedAt.delete($.toolCall.toolCallId);let Z=TR($.message),W=Z?.output,j=qR(Z);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:W,error:j,durationMs:Q}]}translateUsage($){let J=$.inputTokens-this.lastUsage.inputTokens,Q=$.outputTokens-this.lastUsage.outputTokens,Z=$.cacheReadTokens-this.lastUsage.cacheReadTokens,W=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,j=this.lastUsage.totalCost??0,X=($.totalCost??0)-j;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,J),outputTokens:Math.max(0,Q),cacheReadTokens:Z===0?void 0:Math.max(0,Z),cacheWriteTokens:W===0?void 0:Math.max(0,W),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 J={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:MR($.status),text:$.outputText,iterations:$.iterations,usage:J}]}}function bR($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function hR($){let Q=(typeof $.content==="function"?await $.content():$.content).trim();return Q.length>0?Q:void 0}function kR($,J){let Q=$.trim(),Z=J.map((W)=>W.trim()).filter(Boolean).join(`
181
181
 
182
182
  `);if(Q&&Z)return`${Q}
183
183
 
184
- ${Z}`;return Q||Z}function IR($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function xR($,J){return $.filter((Q)=>IR(Q.name,J))}function gR($,J){return I1(xR($,J))}function mR($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return{};return{beforeRun:async(Q)=>{for(let Z of J){let W=await Z.beforeRun?.(Q);if(W?.stop)return W}return},afterRun:async(Q)=>{for(let Z of J)await Z.afterRun?.(Q)},beforeModel:async(Q)=>{let Z=Q.request,W;for(let j of J){let f=await j.beforeModel?.({...Q,request:Z});if(!f)continue;if(f.stop)return f;W={...W,...f,options:tX(W?.options,f.options)},Z={...Z,...f.messages?{messages:f.messages}:{},...f.tools?{tools:f.tools}:{},...f.options?{options:tX(Z.options,f.options)}:{}}}return W},afterModel:async(Q)=>{for(let Z of J){let W=await Z.afterModel?.(Q);if(W?.stop)return W}return},beforeTool:async(Q)=>{let Z=Q.input,W;for(let j of J){let f=await j.beforeTool?.({...Q,input:Z});if(!f)continue;if(f.stop||f.skip)return f;if(W={...W,...f},Object.hasOwn(f,"input"))Z=f.input}return W},afterTool:async(Q)=>{let Z=Q.result,W;for(let j of J){let f=await j.afterTool?.({...Q,result:Z});if(!f)continue;if(f.stop)return f;if(W={...W,...f},f.result)Z=f.result}return W},onEvent:async(Q)=>{for(let Z of J)await Z.onEvent?.(Q)}}}class V${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 aZ;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($,J={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=J.logger??$.logger,this.telemetry=J.telemetry??$.telemetry,this.createAgentRuntimeImpl=J.createAgentRuntimeImpl??yR,this.conversation=new pZ($.initialMessages),this.messageBuilder=new uZ,this.contributionRegistry=ER({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new nZ({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,f,X)=>vR(this.logger,j,f,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,f)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Z=$.execution?.loopDetection;this.loopDetectionDisabled=Z===!1;let W=Z===!1||Z===void 0?void 0:Z;this.loopTracker=new iZ(W)}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 J=new Set(this.config.tools.map((Z)=>Z.name)),Q=[...this.config.tools];for(let Z of $)if(!J.has(Z.name))Q.push(Z),J.add(Z.name);this.config={...this.config,tools:Q}}updateConnection($){let J={...this.config};if($.providerId!==void 0)J.providerId=$.providerId;if($.modelId!==void 0)J.modelId=$.modelId;if($.apiKey!==void 0)J.apiKey=$.apiKey;if($.baseUrl!==void 0)J.baseUrl=$.baseUrl;if($.headers!==void 0)J.headers=$.headers;if($.providerConfig!==void 0)J.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)J.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=J}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 J=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=J,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(J)}async shutdown($,J){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($,J,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!1})}continue($,J,Q){return this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let J of this.contributionRegistry.getRegisteredRules()){let Q=await hR(J);if(Q)$.push(Q)}return kR(this.config.systemPrompt,$)}executeRun($){let J;return J=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===J)this.activeRunPromise=null}),this.activeRunPromise=J,J}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 J=new Date,Q=$.userMessage;if(Q!==void 0){let F=await uR(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Z=await this.composeSystemPrompt(),W=lX(this.config,this.logger,this.telemetry),j=new Map;for(let F of this.contributionRegistry.getRegisteredTools())j.set(F.name,F);let f=gR([...j.values()],this.config.toolPolicies),X=new Map;for(let F of f)X.set(F.name,F);for(let F of this.config.tools)X.set(F.name,F);let Y=this.conversation.getConversationId(),V=eX(this.config),H=Array.from(X.values()),B=O5(this.conversation.getMessages()),A=aX({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:Y,parentAgentId:this.parentAgentId,model:W,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:V?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[tf]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(V,H),initialMessages:B,systemPrompt:Z}),K=this.createAgentRuntimeImpl(A);if(this.activeRuntime=K,this.abortRequested)K.abort(this.abortReason);let G=K.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,D;try{if($.isContinue)R=await K.continue(void 0);else R=await K.run("")}catch(F){D=F instanceof Error?F:Error(String(F))}finally{G();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=$8(R.messages);this.conversation.replaceMessages(F)}let U=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:D,startedAt:J,endedAt:U})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=mR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((J)=>J.hooks)]);return{...$,beforeModel:async(J)=>{let Q=await $.beforeModel?.(J);if(Q?.stop)return Q;let Z=Q?.messages??J.request.messages,W=await this.prepareMessagesForModelRequest(Z);return{...Q,messages:W}}}}createRuntimePrepareTurn($,J){let Q=this.config.prepareTurn;if(!Q)return;return async(Z)=>{let W=$8(Z.messages),j=await this.prepareProviderMessagesForApi(W),f=await Q({agentId:Z.agentId,conversationId:Z.conversationId??this.conversation.getConversationId(),parentAgentId:Z.parentAgentId??null,iteration:Z.iteration,messages:W,apiMessages:j,abortSignal:Z.signal??new AbortController().signal,systemPrompt:Z.systemPrompt??"",tools:J,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Z.emitStatusNotice});if(!f)return;return{...f.messages?{messages:O5(f.messages)}:{},...f.systemPrompt!==void 0?{systemPrompt:f.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let J=await this.prepareProviderMessagesForApi(T5($));return O5(J)}async prepareProviderMessagesForApi($){let J=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Z of Q)J=await Z.build(J);return this.messageBuilder.buildForApi(J)}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 J=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,Z=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let W=$.message.content.find((Y)=>Y.type==="tool-result"),j=W?.type==="tool-result"&&W.isError===!0,f=j?bR(W?.type==="tool-result"?W.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Z,output:W?.type==="tool-result"?W.output:void 0,error:f,durationMs:J===void 0?0:Q.getTime()-J.getTime(),startedAt:J??Q,endedAt:Q};if(this.currentRunToolCalls.push(X),j){if(this.currentTurnFailedTools+=1,f)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${f}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let J=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(J>0&&Q===0){let Z=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${J} tool call(s) failed${Z?`: ${Z}`:""}`})}else if(Q>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let J of this.eventAdapter.translate($))this.emitLegacyEvent(J)}syncConversationFromRuntimeMessage($,J){if($.length>0){this.conversation.replaceMessages($8($));return}if(J.length===0)return;let Q=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),Z=$8(J).filter((W)=>!W.id||!Q.has(W.id));if(Z.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Z])}emitLegacyEvent($){for(let J of this.listeners)try{J($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,J,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Z=this.loopTracker.inspect({name:$,input:J});if(Z.kind==="ok")return;if(Z.kind==="soft"){if(Z.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:Z.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 J=await this.mistakeTracker.record($);if(J.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:J.message}]}),this.activeRuntime?.abort(J.reason??J.message)})}buildLegacyResult($){let{runResult:J,thrownError:Q,startedAt:Z,endedAt:W}=$,j=W.getTime()-Z.getTime(),f=Q?"error":cR(J),X=J?.outputText||(J?.status==="failed"?J.error?.message:void 0)||"",Y=J?{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens>0?J.usage.cacheReadTokens:void 0,cacheWriteTokens:J.usage.cacheWriteTokens>0?J.usage.cacheWriteTokens:void 0,totalCost:J.usage.totalCost}:this.currentRunUsage,V=J?$8(J.messages):this.conversation.getMessages(),H=eX(this.config);if(Q)throw Q;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:J?.iterations??0,finishReason:f,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Z,endedAt:W,durationMs:j}}}function vR($,J,Q,Z){if(!$)return;if(J==="debug"){$.debug(Q,Z);return}if(J==="error"&&$.error){$.error(Q,Z);return}let W=J==="warn"?"warn":J==="error"?"error":"info";$.log(Q,{...Z,severity:W})}function cR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function uR($,J,Q,Z){let{buildInitialUserContent:W}=await Promise.resolve().then(() => oX);return W($,J,Q,Z)}function eX($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let J=xZ($);if(J?.[$.modelId])return J[$.modelId];return}import{buildClineSystemPrompt as $Y}from"@cline/shared";function JY($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return $Y({ide:J.clineIdeName?.trim()||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,rules:`# Team Teammate Role
185
- ${Q}`,platform:J.clinePlatform,metadata:J.workspaceMetadata})}function QY($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return $Y({ide:J.clineIdeName||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,overridePrompt:Q,metadata:J.workspaceMetadata,platform:J.clinePlatform})}function H$($){let J={...$};return{getRuntimeConfig:()=>J,getConnectionConfig:()=>({providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking}),updateConnectionDefaults:(Q)=>{J={...J,...Q}}}}function l$($){let J=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?JY($.prompt,J):QY($.prompt,J);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??J.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:J.hooks,extensions:J.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:J.logger,role:$.role}}function B$($){let J=l$($),Q=new V$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);return Q}var pR=sZ.object({systemPrompt:sZ.string().describe("System prompt defining the sub-agent's behavior"),task:sZ.string().describe("Task for the sub-agent to complete")});function A$($){return dR({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:lR(pR),execute:async(J,Q)=>{let Z=$.createSubAgentTools?await $.createSubAgentTools(J,Q):$.subAgentTools??[],W=B$({kind:"subagent",prompt:J.systemPrompt,configProvider:$.configProvider,tools:Z,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=W.getAgentId(),f=W.getConversationId(),X=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:f,parentAgentId:X,input:J})}catch{}try{let Y=await W.run(J.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as X0,TEAM_AWAIT_TIMEOUT_MS as rR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as iR,TEAM_RUN_TEXT_PREVIEW_LIMIT as nR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as aR,TeamAttachOutcomeFragmentInputSchema as ZY,TeamAwaitRunsInputSchema as WY,TeamBroadcastInputSchema as jY,TeamBroadcastToolResultSchema as sR,TeamCancelRunInputSchema as fY,TeamCancelRunToolResultSchema as oR,TeamCleanupInputSchema as XY,TeamCleanupToolResultSchema as tR,TeamCreateOutcomeInputSchema as YY,TeamCreateOutcomeToolResultSchema as eR,TeamFinalizeOutcomeInputSchema as VY,TeamFinalizeOutcomeToolResultSchema as $z,TeamListOutcomesInputSchema as HY,TeamListRunsInputSchema as BY,TeamMailboxMessageToolResultSchema as Jz,TeamMissionLogInputSchema as AY,TeamMissionLogToolResultSchema as Qz,TeamOutcomeFragmentToolResultSchema as KY,TeamOutcomeToolResultSchema as Zz,TeamReadMailboxInputSchema as GY,TeamReviewOutcomeFragmentInputSchema as FY,TeamRunTaskInputSchema as DY,TeamRunTaskToolResultSchema as oZ,TeamRunToolSummarySchema as tZ,TeamSendMessageInputSchema as UY,TeamSendMessageToolResultSchema as Wz,TeamShutdownTeammateInputSchema as RY,TeamSimpleAgentStatusToolResultSchema as zY,TeamSpawnTeammateInputSchema as LY,TeamStatusInputSchema as _Y,TeamStatusToolResultSchema as jz,TeamTaskInputSchema as OY,TeamTaskToolResultSchema as n4,validateWithZod as k,zodToJsonSchema as Y0}from"@cline/shared";function TY($,J){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=J)return Q;return`${Q.slice(0,Math.max(0,J-3)).trimEnd()}...`}function p$($,J){if($===void 0)throw Error(`Missing required field: ${J}`);return $}function fz($){let J=$.result;if(!J)return;return{textPreview:TY(J.text,nR),iterations:J.iterations,finishReason:J.finishReason,durationMs:J.durationMs,usage:{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens,cacheWriteTokens:J.usage.cacheWriteTokens,totalCost:J.usage.totalCost}}}function q5($){return $?.toISOString()}function eZ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:TY($.message,iR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:q5($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:q5($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:q5($.heartbeatAt),lastProgressAt:q5($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:fz($)}}function Xz($){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 J8=["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 MY($){let J=[];if($.createBaseTools)J.push(...$.createBaseTools());J.push(...r$({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:l$({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:J,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function Q8($){let J=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,Z=r$({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),W=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;MY({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),W.push(j.agentId)}return{tools:Z,restoredFromPersistence:Q,restoredTeammates:W}}function r$($){let J=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,Z=$.includeManagementTools??!0,W=[];if(Q)W.push(X0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Y0(LY),execute:async(f)=>{let X=k(LY,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!J)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(MY({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Z)$.onLeadToolsUnlocked?.(r$({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return k(zY,{agentId:X.agentId,status:"spawned"})}}));if(!Z)return W;W.push(X0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Y0(RY),execute:async(f)=>{let X=k(RY,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),k(zY,{agentId:X.agentId,status:"stopped"})}})),W.push(X0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Y0(_Y),execute:async(f)=>{return k(_Y,f),k(jz,$.runtime.getSnapshot())}})),W.push(X0({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:Y0(OY),execute:async(f)=>{let X=k(OY,f);switch(X.action){case"create":{let Y=new Set(aR.create??[]),V=Object.entries(f).filter(([B,A])=>Y.has(B)&&A!=null).map(([B])=>B),H=$.runtime.createTask({title:p$(X.title,"title"),description:p$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return k(n4,{action:"create",taskId:H.id,status:H.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return k(n4,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(p$(X.taskId,"taskId"),$.requesterId);return k(n4,{action:"claim",taskId:Y.id,status:Y.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 Y=$.runtime.completeTask(p$(X.taskId,"taskId"),$.requesterId,p$(X.summary,"summary"));return k(n4,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(p$(X.taskId,"taskId"),$.requesterId,p$(X.reason,"reason"));return k(n4,{action:"block",taskId:Y.id,status:Y.status})}}}}));let j=new Map;return W.push(X0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Y0(DY),execute:async(f)=>{let X=k(DY,f);if(X.runMode==="async"){let H=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return k(oZ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${H.id}.`,runId:H.id})}let Y=j.get(X.agentId);if(Y){let H=await Y;return k(oZ,{...H,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((H)=>k(oZ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(X.agentId)});return j.set(X.agentId,V),await V}})),W.push(X0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Y0(fY),execute:async(f)=>{let X=k(fY,f),Y=$.runtime.cancelRun(X.runId,X.reason);return k(oR,{runId:Y.id,status:Y.status})}})),W.push(X0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Y0(BY),execute:async(f)=>k(tZ.array(),$.runtime.listRuns(k(BY,f)).map(eZ))})),W.push(X0({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:Y0(WY),timeoutMs:rR,execute:async(f)=>{let X=k(WY,f);if(X.runId){let H=await $.runtime.awaitRun(X.runId);return Xz(H),k(tZ,eZ(H))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(V.length>0){let H=V.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return k(tZ.array(),Y.map(eZ))}})),W.push(X0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Y0(UY),execute:async(f)=>{let X=k(UY,f),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return k(Wz,{id:Y.id,toAgentId:Y.toAgentId})}})),W.push(X0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Y0(jY),execute:async(f)=>{let X=k(jY,f),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return k(sR,{delivered:Y.length})}})),W.push(X0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Y0(GY),execute:async(f)=>{let X=k(GY,f);return k(Jz.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),W.push(X0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Y0(AY),execute:async(f)=>{let X=k(AY,f),Y=$.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 k(Qz,{id:Y.id})}})),W.push(X0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Y0(XY),execute:async(f)=>{if(k(XY,f),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),k(tR,{status:"cleaned"})}})),W.push(X0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Y0(YY),execute:async(f)=>{let X=k(YY,f),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return k(eR,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),W.push(X0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Y0(ZY),execute:async(f)=>{let X=k(ZY,f),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return k(KY,{fragmentId:Y.id,status:Y.status})}})),W.push(X0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Y0(FY),execute:async(f)=>{let X=k(FY,f),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return k(KY,{fragmentId:Y.id,status:Y.status})}})),W.push(X0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Y0(VY),execute:async(f)=>{let X=k(VY,f),Y=$.runtime.finalizeOutcome(X.outcomeId);return k($z,{outcomeId:Y.id,status:Y.status})}})),W.push(X0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Y0(HY),execute:async(f)=>{return k(HY,f),k(Zz.array(),$.runtime.listOutcomes())}})),W}function P5($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}function qY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var Yz=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:A$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...J8]}],Vz={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function Hz($){return $==="plan"||$==="yolo"?$:"act"}function NY($){let J=Hz($.mode),Q=c0[h1({mode:J})],Z=t2($.providerId??"",$.modelId??"",J,o2);return{mode:J,flags:{...Q,...Z,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function PY($,J){if(J.disabledToolIds?.has($))return!1;let{flags:Q}=NY(J);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let Z=Vz[$];return Z?Q[Z]===!0:!1}function Bz($,J){if($.id==="editor"){let{flags:Q}=NY(J),Z=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:PY($.id,J),headlessToolNames:[Z?"apply_patch":"editor"]}}return{...$,defaultEnabled:PY($.id,J)}}function i$($={}){return Yz.map((J)=>Bz(J,$))}function N5($={}){return i$($).filter((J)=>J.defaultEnabled).map((J)=>J.id)}function w5($){if(!$.enabled)return new Set;let J=i$($.availabilityContext),Q=new Set(J.map((Z)=>Z.id));if(!$.allowlist||$.allowlist.length===0)return new Set(J.filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id));for(let Z of $.allowlist)if(!Q.has(Z))throw Error(`Unknown tool "${Z}". Available tools: ${J.map((W)=>W.id).join(", ")}`);return new Set($.allowlist)}function a4($,J={}){return i$(J).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function S5($,J={}){return a4($,J)}function n$($={}){let{executorOptions:J={},executors:Q,...Z}=$,W={...s2(J),...Q??{}};return X$({...Z,executors:W})}import{mkdirSync as Uz,writeFileSync as Rz}from"node:fs";import{dirname as zz}from"node:path";import{normalizeUserInput as Lz}from"@cline/shared";import{nanoid as _z}from"nanoid";var SY={};w(SY,{sanitizeSessionToken:()=>a$,parseTeamTaskSubSessionId:()=>W8,parseSubSessionId:()=>o4,makeTeamTaskSubSessionId:()=>s4,makeSubSessionId:()=>Z8,deriveSubsessionStatus:()=>t4});import{nanoid as Gz}from"nanoid";function a$($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Z8($,J){let Q=a$($),Z=a$(J),W=`${Q}__${Z}`;return W.length>180?W.slice(0,180):W}function s4($,J){let Q=a$($),Z=a$(J);return`${Q}__teamtask__${Z}__${Gz(6)}`}function W8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+12),j=W.lastIndexOf("__");if(j<=0)return null;let f=W.slice(0,j),X=W.slice(j+2);if(!Z||!f||!X)return null;return{rootSessionId:Z,agentId:f,teamTaskId:X}}function o4($){if(W8($))return null;let J="__",Q=$.indexOf(J);if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+J.length);if(!Z||!W)return null;return{rootSessionId:Z,agentId:W}}function t4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let J=String($.reason??"").toLowerCase();if(J.includes("cancel")||J.includes("abort")||J.includes("interrupt"))return"cancelled";if(J.includes("fail")||J.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var EY={};w(EY,{isTerminalSessionStatus:()=>yY,isNonTerminalSessionStatus:()=>j0,SessionSource:()=>U0,SESSION_STATUSES:()=>e4,NON_TERMINAL_SESSION_STATUSES:()=>CY});import{SESSION_STATUS_VALUES as Fz}from"@cline/shared";var e4=Fz,CY=["idle","running","pending"];function yY($){return!CY.includes($)}function j0($){return!yY($)}var U0={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 Dz=a.enum(e4),S0=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:Dz,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 bY($){if(!$)return!1;return Object.values($).some((J)=>typeof J==="function")}function J7($,J){let Q=[...$??[],...J??[]];if(Q.length===0)return;let Z=[],W=new Set;for(let j of Q){if(W.has(j.name))continue;W.add(j.name),Z.push(j)}return Z}function hY($){return JSON.stringify($,(J,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function x1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function $7($,J){let Q={...$};Q.id=x1(Q.id)??_z();let Z=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,W={id:x1(Z?.id)??x1(Q.modelId)??x1(J?.id),provider:x1(Z?.provider)??x1(Q.providerId)??x1(J?.provider),family:x1(Z?.family)??x1(J?.family)};if(delete Q.providerId,delete Q.modelId,W.id&&W.provider)Q.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete Q.modelInfo;return Q}function C5($){return $.map((J)=>$7(J))}function y5($,J,Q=[]){let Z=$.map((Y,V)=>{let H=Q[V],A=H?.role===Y.role&&JSON.stringify(H.content)===JSON.stringify(Y.content)?{...H,...Y}:{...Y};return $7(A)}),W=Q.length,j=[];for(let Y=W;Y<Z.length;Y+=1)if(Z[Y]?.role==="assistant")j.push(Y);if(j.length===0){let Y=[...Z].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Z;j.push(Z.length-1-Y)}let f=j[j.length-1],X=j.some((Y)=>Z[Y]?.metrics);for(let Y of j){let V=Z[Y],H=V.metrics;if(!H&&Y===f&&!X){let B=J.usage;H={inputTokens:B.inputTokens,outputTokens:B.outputTokens,cacheReadTokens:B.cacheReadTokens??0,cacheWriteTokens:B.cacheWriteTokens??0,cost:B.totalCost}}Z[Y]={...$7(V,{id:J.model.id,provider:J.model.provider,family:J.model.info?.family}),...H?{metrics:H}:{},ts:V.ts??J.endedAt.getTime()}}return Z}function $6($){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 Oz=120;function s$($){let J=$?.trim();return J?J.slice(0,Oz):void 0}function Q7($){let J=Lz($??"").trim();if(!J)return;return s$(J.split(`
186
- `)[0]?.trim())}function K$($){if(!$)return;let J={...$},Q=s$(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function J6($){let J=K$($.metadata)??{},Q=$.title!==void 0?s$($.title):Q7($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function Z7($){let J=W8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=o4($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function W7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:C5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function kY($,J,Q){Uz(zz($),{recursive:!0}),Rz($,`${JSON.stringify(W7({updatedAt:J,context:Q,messages:[]}),null,2)}
187
- `,"utf8")}function IY($,J){return S0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function xY($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}O0();var gY={};w(gY,{summarizeUsageFromMessages:()=>f8,sumUsageTotals:()=>Q6,getCurrentContextSize:()=>j7,createInitialAccumulatedUsage:()=>G0,accumulateUsageTotals:()=>V0});function G0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function V0($,J){return{inputTokens:$.inputTokens+Math.max(0,J.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,J.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,J.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,J.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,J.totalCost??0)}}function Q6($){let J=G0();for(let Q of $)J=V0(J,Q);return J}function j8($){return typeof $==="number"&&Number.isFinite($)?$:0}function f8($){let J=G0();for(let Q of $){let Z=Q.metrics;if(!Z)continue;J=V0(J,{inputTokens:j8(Z.inputTokens),outputTokens:j8(Z.outputTokens),cacheReadTokens:j8(Z.cacheReadTokens),cacheWriteTokens:j8(Z.cacheWriteTokens),totalCost:j8(Z.cost)})}return J}function j7($){for(let J=$.length-1;J>=0;J-=1){let Q=$[J];if(Q?.role!=="assistant")continue;let Z=j8(Q.metrics?.inputTokens);return Z>0?Z:void 0}return}function Tz($){if(!$||typeof $!=="object")return;let J=$,Q=J.skill??J.skill_name??J.skillName;if(typeof Q!=="string")return;let Z=Q.trim();return Z.length>0?Z:void 0}function f7($){if(!$||typeof $!=="object")return{};let J=$;return{agentId:typeof J.agentId==="string"?J.agentId:void 0,conversationId:typeof J.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J.parentAgentId==="string"?J.parentAgentId:void 0}}function g1($){let J=$.agentId?.trim();if(!J)return;let Q=$.parentAgentId?.trim()||void 0,Z=$.teamRole,W="root";if(Z==="teammate")W="team_teammate";else if(Z==="lead")W="team_lead";else if(Q)W="subagent";return{agentId:J,agentKind:W,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Z,teamAgentId:$.teamAgentId?.trim()||void 0}}function Mz($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function qz($){let J=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of J){let Z=Q?.trim();if(Z)return Z}return $.isPrimaryAgentEvent?"root":"unknown"}function X7($,J,Q){let{sessionId:Z,config:W,liveSession:j,emit:f}=$,X=W.telemetry,Y=j?.runtime.teamRuntime,V=Q?.isPrimaryAgentEvent??!0,H=f7(J),B=g1({agentId:Q?.agentId??H.agentId,conversationId:Q?.conversationId??H.conversationId,parentAgentId:Q?.parentAgentId??H.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??Y?.getTeamId(),teamName:Q?.teamName??Y?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(J.type==="content_start"&&J.contentType==="tool"&&J.toolName==="skills"){let A=Tz(J.input);if(A)vJ(X,{ulid:Z,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...B})}if(J.type==="content_end"&&J.contentType==="tool"){let A=J.toolName??"unknown",K=!J.error;if(mJ(X,{ulid:Z,tool:A,autoApproved:void 0,success:K,modelId:W.modelId,provider:W.providerId,...B}),!K&&(A==="editor"||A==="apply_patch"))cJ(X,{ulid:Z,modelId:W.modelId,provider:W.providerId,errorType:J.error,...B})}if(J.type==="notice"&&J.reason==="api_error")H4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.message,...B});if(J.type==="error")H4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.error?.message??"unknown error",...B});if(J.type==="usage"&&j?.turnUsageBaseline){let A=Mz(J);if(V){j.turnPrimaryUsage=V0(j.turnPrimaryUsage??G0(),A);let G=V0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Z,G),g2(X,{ulid:Z,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...B}),xJ(X,{ulid:Z,tokensIn:J.inputTokens,tokensOut:J.outputTokens,cacheWriteTokens:J.cacheWriteTokens,cacheReadTokens:J.cacheReadTokens,totalCost:J.cost,model:W.modelId,...B})}else{let G=qz({isPrimaryAgentEvent:V,overrides:Q,eventMetadata:H}),R=j.turnUsageByAgent??new Map;j.turnUsageByAgent=R,R.set(G,V0(R.get(G)??G0(),A))}let K=V0(j.turnPrimaryUsage??G0(),Q6(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Z,V0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,K))}if(J.type==="iteration_end"&&V)$.persistMessages(Z,j?.agent.getMessages()??[],j?.config.systemPrompt);f({type:"agent_event",payload:{sessionId:Z,event:J,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(V?"lead":void 0):void 0}}),f({type:"chunk",payload:{sessionId:Z,stream:"agent",chunk:hY(J),ts:Date.now()}})}function G$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as h_}from"@cline/shared";W1();import{existsSync as x5,readFileSync as AL,statSync as KL}from"node:fs";import{basename as GL,dirname as k5,join as g5,resolve as I5}from"node:path";import{discoverPluginModulePaths as FL,resolveConfiguredPluginModulePaths as jV,resolvePluginConfigSearchPaths as DL,SKILLS_CONFIG_DIRECTORY_NAME as UL}from"@cline/shared/storage";import{resolve as pz}from"node:path";import{normalizePluginManifest as rz}from"@cline/shared";import{existsSync as R0,readFileSync as Y8}from"node:fs";import{builtinModules as Pz,createRequire as B7}from"node:module";import{dirname as F$,extname as W6,isAbsolute as Nz,resolve as p}from"node:path";import{fileURLToPath as vY}from"node:url";import{PLUGIN_FILE_EXTENSIONS as wz}from"@cline/shared";var cY=F$(vY(import.meta.url)),Sz=B7(import.meta.url),Cz=p(cY,"..","..","..","..",".."),Y7=bz(Cz),yz=["@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"],A7=new Set(Pz.flatMap(($)=>[$,$.replace(/^node:/,"")])),Z6=new Set(wz),Ez=["development","node","import","require","default"];function bz($){let J={},Q={"@cline/sdk":p($,"packages/sdk/src/index.ts"),"@cline/agents":p($,"packages/agents/src/index.ts"),"@cline/core":p($,"packages/core/src/index.ts"),"@cline/llms":p($,"packages/llms/src/index.ts"),"@cline/shared":p($,"packages/shared/src/index.ts"),"@cline/shared/storage":p($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":p($,"packages/shared/src/db/index.ts")};for(let[Z,W]of Object.entries(Q))if(R0(W))J[Z]=W;for(let Z of["agents","core","llms","shared"]){let W=p($,"packages",Z),j=p(W,"package.json");if(!R0(j))continue;try{let f=JSON.parse(Y8(j,"utf8"));if(typeof f.name!=="string"||!f.exports)continue;if(typeof f.exports==="string"){let X=p(W,f.exports);if(R0(X))J[f.name]=X;continue}if(typeof f.exports!=="object")continue;for(let[X,Y]of Object.entries(f.exports)){let V=hz(W,Y);if(!V)continue;let H=X==="."?f.name:`${f.name}/${X.replace(/^\.\//,"")}`;J[H]=V}}catch{}}return J}function hz($,J){let Q=K7(J);if(!Q)return null;let Z=uY($,Q);for(let W of Z)if(R0(W))return W;return null}function K7($,J=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(J.has($))return null;J.add($);let Q=$;for(let Z of Ez){let W=K7(Q[Z],J);if(W)return W}return null}function uY($,J){let Q=J.replace(/^\.\//,""),Z=[p($,J)];if(Q.startsWith("dist/")){let W=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[p($,`${W}.ts`),p($,`${W}.tsx`),p($,`${W}.mts`),p($,`${W}.cts`),...Z]}return Z}function kz($){return Object.fromEntries(Object.entries($).sort(([J],[Q])=>Q.length-J.length))}function E5($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function X8($){if($.startsWith("@")){let[J,Q]=$.split("/",3);return Q?`${J}/${Q}`:$}return $.split("/",1)[0]??$}function Iz($){let J=X8($);if($===J)return".";return`.${$.slice(J.length)}`}function dY($){return X8($).startsWith("@cline/")}function V7($,J){let Q=X8(J),Z=F$($);while(!0){let W=p(Z,"node_modules",Q);if(R0(W)||R0(p(W,"package.json")))return!0;let j=p(Z,"..");if(j===Z)return!1;Z=j}}function mY($){return H7($)!==null}function H7($){try{return Sz.resolve($)}catch{}return xz($)}function xz($){let J=X8($),Q=lY(J);if(!Q)return null;let Z=p(Q,"package.json");try{let W=JSON.parse(Y8(Z,"utf8")),j=Iz($),f=j==="."&&typeof W.exports==="string"?W.exports:W.exports&&typeof W.exports==="object"&&Object.hasOwn(W.exports,j)?W.exports[j]:void 0,X=K7(f)??(j==="."&&typeof W.main==="string"?W.main:null);if(!X)return null;let Y=p(Q,X),V=[Y,...uY(Q,X).filter((H)=>H!==Y)];for(let H of V)if(R0(H))return H;return null}catch{return null}}function gz(){let $=[cY],J=process.env.CLINE_WRAPPER_PATH?.trim();if(J)$.push(F$(F$(J)));let Q=process.execPath?.trim();if(Q)$.push(F$(Q));return[...new Set($.map((Z)=>p(Z)))]}function mz($,J){let Q=$;while(!0){let Z=p(Q,"package.json");if(R0(Z))try{if(JSON.parse(Y8(Z,"utf8")).name===J)return Q}catch{}let W=p(Q,"node_modules",J,"package.json");if(R0(W))return F$(W);let j=p(Q,"..");if(j===Q)return null;Q=j}}function lY($){for(let J of gz()){let Q=mz(J,$);if(Q)return Q}return null}function vz($){let Q=F$($);for(let Z=0;Z<4;Z++){let W=p(Q,"package.json");if(R0(W))try{let f=JSON.parse(Y8(W,"utf8"));return f!=null&&typeof f==="object"&&"cline"in f}catch{return!1}let j=p(Q,"..");if(j===Q)return!1;Q=j}return!1}function pY($,J){let Q=J.startsWith("file:")?vY(J):Nz(J)?J:p(F$($),J);if(R0(Q)&&Z6.has(W6(Q)))return Q;for(let Z of Z6){let W=`${Q}${Z}`;if(R0(W))return W}for(let Z of Z6){let W=p(Q,`index${Z}`);if(R0(W))return W}return null}function rY($){let J=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Z of Q)for(let W of $.matchAll(Z)){let j=W[1];if(j)J.add(j)}return[...J]}function cz($){return W6($)!==".ts"}function iY($,J,Q=new Set){if(Q.has($)||!R0($))return;if(Q.add($),!Z6.has(W6($)))return;let Z=Y8($,"utf8"),W=cz($);for(let j of rY(Z)){if(j.startsWith("node:")||A7.has(j))continue;if(E5(j)){if(!W)continue;if(Object.hasOwn(Y7,j)||Object.hasOwn(Y7,X8(j))||V7($,j)||dY(j)&&mY(j)||J&&mY(j))continue;throw Error(`Cannot find module '${X8(j)}'`)}let f=pY($,j);if(f)iY(f,J,Q)}}function nY($,J=new Set,Q=new Set){if(J.has($)||!R0($))return Q;if(J.add($),!Z6.has(W6($)))return Q;let Z=Y8($,"utf8");for(let W of rY(Z)){if(Q.add(W),E5(W))continue;let j=pY($,W);if(j)nY(j,J,Q)}return Q}function uz($,J){let Q=B7($),Z={},W=nY($),j=new Set(yz);for(let[f,X]of Object.entries(Y7)){try{Q.resolve(f);continue}catch{}Z[f]=X}for(let f of W)if(E5(f)&&(dY(f)||J))j.add(f);for(let f of j){if(Object.hasOwn(Z,f)||V7($,f))continue;let X=H7(f);if(X)Z[f]=X}if(!J)return Z;for(let f of W){if(!E5(f)||Object.hasOwn(Z,f)||V7($,f)||f.startsWith("node:")||A7.has(f))continue;let X=H7(f);if(X)Z[f]=X}return Z}function dz($){let J=W6($);return J===".ts"||J===".tsx"||J===".mts"||J===".cts"}var o$;function lz(){if(o$!==void 0)return o$;let $=lY("jiti");if(!$)return o$=null,null;let J=p($,"dist","babel.cjs");if(!R0(J))return o$=null,null;try{let Z=B7(J)(J);o$=typeof Z==="function"?Z:null}catch{o$=null}return o$}async function aY($,J={}){let Q=!vz($);iY($,Q);let Z=uz($,Q),W=kz(Z),j=await import("jiti"),f=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!f)throw Error("Unable to load jiti");let X=Object.entries(W).filter(([,B])=>dz(B)).map(([B])=>B),Y=lz(),V=Y?(B)=>Y({...B,interopDefault:!0}):void 0;return await f($,{alias:W,cache:J.useCache,requireCache:J.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...A7],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function sY($,J){if(!$)return!0;if($.providerIds?.length){if(!J?.providerId||!$.providerIds.includes(J.providerId))return!1}if($.modelIds?.length){if(!J?.modelId||!$.modelIds.includes(J.modelId))return!1}return!0}function oY($){return typeof $==="object"&&$!==null}function G7($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function iz($,J){if(!oY($.manifest))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);if(!G7($.manifest.capabilities))throw Error(`Invalid plugin module at ${J}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${J}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!G7($.manifest.providerIds))throw Error(`Invalid plugin module at ${J}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!G7($.manifest.modelIds))throw Error(`Invalid plugin module at ${J}: manifest.modelIds must be a string array when provided`)}function nz($,J){if(!oY($))throw Error(`Invalid plugin module at ${J}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${J}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);iz($,J)}async function j6($,J={}){let Q=pz(J.cwd??process.cwd(),$),Z=await aY(Q,{useCache:J.useCache}),W=J.exportName??"plugin",j=Z.default??Z[W];nz(j,Q);let f=j,X=f.setup,Y=X?(V,H)=>{let B={...J.session,...H.session},A={...H,session:Object.keys(B).length>0?B:void 0,client:J.client??H.client,user:J.user??H.user,workspaceInfo:J.workspaceInfo??H.workspaceInfo,automation:J.automation??H.automation,logger:J.logger??H.logger,telemetry:J.telemetry??H.telemetry};return X(V,A)}:void 0;return{...f,manifest:rz(f.manifest),setup:Y}}async function b5($,J={}){return(await t$($,J)).plugins}async function t$($,J={}){let Q=[],Z=[],W=new Map,j=0;for(let X of $)try{let Y=await j6(X,J);if(!sY(Y.manifest,J))continue;let V=W.get(Y.name);if(V)Z.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});W.set(Y.name,{plugin:Y,pluginPath:X,order:j++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);Q.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let f=[...W.values()].sort((X,Y)=>X.order-Y.order);return{plugins:f.map((X)=>X.plugin),pluginPaths:f.map((X)=>X.pluginPath),failures:Q,warnings:Z}}import{existsSync as R7}from"node:fs";import{createRequire as WV}from"node:module";import{dirname as h5,join as H8}from"node:path";import{fileURLToPath as ez}from"node:url";var QV={};w(QV,{resolveSubprocessRuntimeExecutable:()=>F7,buildSubprocessSandboxCommand:()=>JV,SubprocessSandbox:()=>V8,CLINE_JS_RUNTIME_PATH_ENV:()=>$V});import{spawn as az}from"node:child_process";import{basename as sz}from"node:path";import{augmentNodeCommandForDebug as oz,withResolvedClineBuildEnv as tz}from"@cline/shared";function tY($){if($ instanceof Error)return $;return Error(String($))}var $V="CLINE_JS_RUNTIME_PATH";function eY($){let J=$?.trim();if(!J)return!1;let Q=sz(J).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function F7($={}){let J=$.env??process.env,Q=$.runtimeExecutable?.trim()||J[$V]?.trim();if(Q)return Q;let Z=$.execPath?.trim()||process.execPath;if(eY(Z))return Z;for(let W of[J.BUN_EXEC_PATH,J.npm_node_execpath,J.NODE]){let j=W?.trim();if(j&&eY(j))return j}return"node"}function JV($,J={}){let Q=F7({env:J.env,execPath:J.execPath,runtimeExecutable:J.runtimeExecutable});return oz([Q,...$],{env:J.env,execArgv:J.execArgv,debugRole:J.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class V8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let J=this.pending.get($);if(!J)return;if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);return J}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],J=JV($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=az(J[0]??F7(this.options),J.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:tz(process.env),windowsHide:!0});this.process=Q;let Z="",W=(j)=>{let f=Z+j;Z=f.length>4000?f.slice(-4000):f};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(j)=>{W(j)}),Q.on("message",(j)=>{this.onMessage(j)}),Q.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${tY(j).message}`))}),Q.on("exit",(j,f)=>{this.process=null;let X=Z.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(f)})${X?`: ${X}`:""}`))})}async call($,J,Q={}){this.start();let Z=this.process;if(!Z||Z.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,j={type:"call",id:W,method:$,args:J};return await new Promise((f,X)=>{let Y={resolve:(V)=>f(V),reject:X};if((Q.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(W,Y),Z.send(j,(V)=>{if(!V)return;let H=this.clearPendingRequest(W);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${tY(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((J)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}J()},300);$.once("exit",()=>{clearTimeout(Q),J()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),J()}}),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 J=this.clearPendingRequest($.id);if(!J)return;if($.ok){J.resolve($.result);return}J.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[J,Q]of this.pending.entries()){if(this.pending.delete(J),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function $L($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function f6($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function JL(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function QL(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=WV($).resolve(`${JL()}/package.json`),Z=H8(h5(Q),"extensions","plugin-sandbox-bootstrap.js");return R7(Z)?Z:void 0}catch{return}}function ZL(){let $=process.execPath?.trim();if(!$)return;let J=H8(h5(h5($)),"extensions","plugin-sandbox-bootstrap.js");return R7(J)?J:void 0}function WL(){let $=h5(ez(import.meta.url)),J=WV(import.meta.url),Q=[H8($,"plugin-sandbox-bootstrap.js"),H8($,"extensions","plugin-sandbox-bootstrap.js"),H8($,"agents","plugin-sandbox-bootstrap.js"),QL(),ZL()];for(let j of Q.filter((f)=>typeof f==="string"))if(R7(j))return{file:j};let Z=H8($,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=J.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(Z)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Z)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
188
- `)}}var D7=WL();function U7($,J,Q){if(typeof $==="number"&&$>0)return $;if(Q){let Z=process.env[Q];if(Z){let W=Number(Z);if(Number.isInteger(W)&&W>0)return W}}return J}async function B8($){let J=new V8({name:"plugin-sandbox",..."file"in D7?{bootstrapFile:D7.file}:{bootstrapScript:D7.script},onEvent:$.onEvent}),Q=U7($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Z=U7($.hookTimeoutMs,3000),W=U7($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},f,X=()=>{return f??=J.call("initialize",j,{timeoutMs:Q}).finally(()=>{f=void 0}),f},Y;try{Y=await J.call("initialize",j,{timeoutMs:Q})}catch(B){throw await J.shutdown().catch(()=>{}),B}let V=Y.plugins.map($L);return{extensions:V.map((B)=>{let A={name:B.name,__clinePluginPath:B.pluginPath,manifest:B.manifest,setup:(K)=>{jL(K,J,B,W,X),fL(K,J,B,W,X),XL(K,J,B,W,X),VL(K,J,B,W,X),YL(K,B)}};return A.hooks=BL(J,B,Z,X),A}),failures:Y.failures,pluginPaths:V.map((B)=>B.pluginPath),shutdown:async()=>{await J.shutdown()},warnings:Y.warnings}}function jL($,J,Q,Z,W){for(let j of Q.contributions?.tools??[]){let f={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(X,Y)=>{try{return await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}catch(V){if(!f6(V))throw V;return await W(),await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}}};$.registerTool(f)}}function fL($,J,Q,Z,W){for(let j of Q.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(f)=>{try{return await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}catch(X){if(!f6(X))throw X;return await W(),await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}}})}function XL($,J,Q,Z,W){for(let j of Q.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}catch(f){if(!f6(f))throw f;return await W(),await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}}:j.content??""})}function YL($,J){for(let Q of J.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of J.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of J.contributions?.mcpServers??[])$.registerMcpServer(Q)}function VL($,J,Q,Z,W){for(let j of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(f){try{let X=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return ZV(X)?X:f}catch(X){if(!f6(X))throw X;await W();let Y=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return ZV(Y)?Y:f}}})}function ZV($){return Array.isArray($)&&$.every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&("content"in J))}function HL($,J,Q,Z,W){return async(j)=>{try{return await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}catch(f){if(!f6(f))throw f;return await W(),await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}}}function BL($,J,Q,Z){let W={};for(let j of J.hooks??[])W[j]=HL($,J.pluginId,j,Q,Z);return Object.keys(W).length>0?W:void 0}var L7="package.json",RL="package";function X6($){return DL($)}function Y6($){return FL($)}function zL($){try{return x5($)&&KL($).isDirectory()}catch{return!1}}function _7($){let J=[],Q=new Set;for(let Z of $){let W=I5(Z);if(Q.has(W))continue;Q.add(W),J.push(W)}return J}function fV($){let J=_7($);return L5(J)}function XV($){return X6($).flatMap((J)=>Y6(J)).filter((J)=>x5(J))}function LL($,J){let Q=[];for(let Z of $)try{Q.push(...jV([Z],J))}catch{}return Q}function z7($){return typeof $==="object"&&$!==null}function _L($){try{let J=JSON.parse(AL(g5($,L7),"utf8"));if(!z7(J)||!z7(J.cline))return[];let Q=J.cline.plugins;if(!Array.isArray(Q))return[];let Z=[];for(let W of Q){if(typeof W==="string"){Z.push(W);continue}if(!z7(W)||!Array.isArray(W.paths))continue;for(let j of W.paths)if(typeof j==="string")Z.push(j)}return Z}catch{return[]}}function YV($,J){let Q=I5(J);return _L($).some((Z)=>I5($,Z)===Q)}function OL($,J){return GL($)===RL&&x5(g5(k5($),L7))&&YV(k5($),J)}function TL($){let J=I5($),Q=[],Z=k5(J);while(!0){if(OL(Z,J)){Q.push(Z);break}if(x5(g5(Z,L7))){if(YV(Z,J))Q.push(Z);break}let W=k5(Z);if(W===Z)break;Z=W}return _7(Q)}function e$($={}){let J=$.cwd??process.cwd(),Q=XV($.workspacePath),Z=jV($.pluginPaths??[],J);return fV([...Z,...Q])}function ML($={}){let J=$.cwd??process.cwd(),Q=XV($.workspacePath),Z=LL($.pluginPaths??[],J);return fV([...Z,...Q])}function $2($){let J=[];for(let Q of $)for(let Z of TL(Q)){let W=g5(Z,UL);if(zL(W))J.push(W)}return _7(J)}function VV($={}){return $2(ML($))}async function A8($={}){let J=e$($);if(J.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Z=await t$(J,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Z.plugins,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}let Q=await B8({pluginPaths:J,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}import{execFile as qL}from"node:child_process";import{promisify as PL}from"node:util";var NL=PL(qL);function O7($,J){$?.log(J,{severity:"warn"})}function wL($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J;if(!Q.latest||!Array.isArray(Q.history))return;let Z=Q.latest,W=Q.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")return;return{latest:Z,history:W}}async function J2($,J){let Q=await NL("git",["-C",$,...J],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function T7($,J){if(!$)return;let Q=`refs/cline/checkpoints/${J}/`;try{let{stdout:Z}=await J2($,["for-each-ref","--format=%(refname)",Q]),W=Z.trim().split(`
189
- `).filter(Boolean);await Promise.allSettled(W.map((j)=>J2($,["update-ref","-d",j])))}catch{}}async function HV($,J,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((Z)=>J2($,["update-ref",`refs/cline/checkpoints/${J}/${Z.runCount}`,Z.ref])))}function SL($,J){let Q=$.findIndex((Z)=>Z.runCount===J.runCount);if(Q<0)return[...$,J];return $.map((Z,W)=>W===Q?J:Z)}function BV($){let J=$.initialRunCount??0,Q,Z=async()=>{if(Q!==void 0)return Q;try{Q=(await J2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},W=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:J});if(!await Z())return;let j=async(V)=>{try{let B=(await J2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:J,kind:"commit"}}catch(H){O7($.logger,`${V}: ${H instanceof Error?H.message:String(H)}`);return}},f=`cline checkpoint session=${$.sessionId} run=${J}`,X="";try{X=(await J2($.cwd,["stash","create",f])).stdout.trim()}catch(V){return O7($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),j("Checkpoint HEAD fallback failed")}if(!X)return j("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${J}`;try{await J2($.cwd,["update-ref",Y,X])}catch(V){O7($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:J,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;J+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||J<1)return;let f=await W();if(!f)return;let X=await $.readSessionMetadata(),Y=wL(X);if(Y?.latest.ref===f.ref)return;let V=SL(Y?.history??[],f);await $.writeSessionMetadata({...X??{},checkpoint:{latest:f,history:V}});return}}}import{spawn as gL}from"node:child_process";import{appendFileSync as mL,readFileSync as vL}from"node:fs";import{join as cL}from"node:path";import{augmentNodeCommandForDebug as GV,withResolvedClineBuildEnv as P7}from"@cline/shared";import{ensureHookLogDir as AV}from"@cline/shared/storage";function K8($,J){if(!J)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:J}}import{existsSync as CL,readdirSync as yL}from"node:fs";import{basename as EL,extname as bL,join as hL}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as m5,resolveHooksConfigSearchPaths as kL}from"@cline/shared/storage";function V6($){return kL($)}var G8;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(G8||={});var H6={["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"},IL=new Map(Object.values(G8).map(($)=>[$.toLowerCase(),$])),xL=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function B6($){let J=bL($).toLowerCase();if(!xL.has(J))return;let Q=EL($,J).trim().toLowerCase();return IL.get(Q)}function D$($){let J=[],Q=new Set,Z=V6($).filter((W)=>CL(W));for(let W of Z)try{for(let j of yL(W,{withFileTypes:!0})){if(!j.isFile())continue;let f=B6(j.name);if(!f)continue;let X=hL(W,j.name);if(Q.has(X))continue;Q.add(X),J.push({fileName:f,hookEventName:H6[f],path:X})}}catch{}return J.sort((W,j)=>W.path.localeCompare(j.path))}function c5($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))J[Q]=typeof Z==="string"?Z:JSON.stringify(Z);return J}function v5($,J,Q){let Z=Q instanceof Error?`: ${Q.message}`:"",W=`${J}${Z}`;if($){try{$.log(W,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(W)}function uL($,J){if(!J)return $;if(!$)return{...J};let Q=[$.context,J.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
184
+ ${Z}`;return Q||Z}function IR($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function xR($,J){return $.filter((Q)=>IR(Q.name,J))}function gR($,J){return I1(xR($,J))}function mR($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return{};return{beforeRun:async(Q)=>{for(let Z of J){let W=await Z.beforeRun?.(Q);if(W?.stop)return W}return},afterRun:async(Q)=>{for(let Z of J)await Z.afterRun?.(Q)},beforeModel:async(Q)=>{let Z=Q.request,W;for(let j of J){let f=await j.beforeModel?.({...Q,request:Z});if(!f)continue;if(f.stop)return f;W={...W,...f,options:oX(W?.options,f.options)},Z={...Z,...f.messages?{messages:f.messages}:{},...f.tools?{tools:f.tools}:{},...f.options?{options:oX(Z.options,f.options)}:{}}}return W},afterModel:async(Q)=>{for(let Z of J){let W=await Z.afterModel?.(Q);if(W?.stop)return W}return},beforeTool:async(Q)=>{let Z=Q.input,W;for(let j of J){let f=await j.beforeTool?.({...Q,input:Z});if(!f)continue;if(f.stop||f.skip)return f;if(W={...W,...f},Object.hasOwn(f,"input"))Z=f.input}return W},afterTool:async(Q)=>{let Z=Q.result,W;for(let j of J){let f=await j.afterTool?.({...Q,result:Z});if(!f)continue;if(f.stop)return f;if(W={...W,...f},f.result)Z=f.result}return W},onEvent:async(Q)=>{for(let Z of J)await Z.onEvent?.(Q)}}}class V${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 aZ;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($,J={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=J.logger??$.logger,this.telemetry=J.telemetry??$.telemetry,this.createAgentRuntimeImpl=J.createAgentRuntimeImpl??yR,this.conversation=new pZ($.initialMessages),this.messageBuilder=new uZ,this.contributionRegistry=ER({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let Q=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new nZ({maxConsecutiveMistakes:Q,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(j)=>this.emitLegacyEvent(j),log:(j,f,X)=>vR(this.logger,j,f,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(j,f)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:j}]})}});let Z=$.execution?.loopDetection;this.loopDetectionDisabled=Z===!1;let W=Z===!1||Z===void 0?void 0:Z;this.loopTracker=new iZ(W)}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 J=new Set(this.config.tools.map((Z)=>Z.name)),Q=[...this.config.tools];for(let Z of $)if(!J.has(Z.name))Q.push(Z),J.add(Z.name);this.config={...this.config,tools:Q}}updateConnection($){let J={...this.config};if($.providerId!==void 0)J.providerId=$.providerId;if($.modelId!==void 0)J.modelId=$.modelId;if($.apiKey!==void 0)J.apiKey=$.apiKey;if($.baseUrl!==void 0)J.baseUrl=$.baseUrl;if($.headers!==void 0)J.headers=$.headers;if($.providerConfig!==void 0)J.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)J.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)J.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)J.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=J}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 J=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=J,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(J)}async shutdown($,J){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($,J,Q){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!1})}continue($,J,Q){return this.executeRun({userMessage:$,userImages:J,userFiles:Q,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let J of this.contributionRegistry.getRegisteredRules()){let Q=await hR(J);if(Q)$.push(Q)}return kR(this.config.systemPrompt,$)}executeRun($){let J;return J=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===J)this.activeRunPromise=null}),this.activeRunPromise=J,J}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 J=new Date,Q=$.userMessage;if(Q!==void 0){let F=await uR(Q,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:F})}let Z=await this.composeSystemPrompt(),W=dX(this.config,this.logger,this.telemetry),j=new Map;for(let F of this.contributionRegistry.getRegisteredTools())j.set(F.name,F);let f=gR([...j.values()],this.config.toolPolicies),X=new Map;for(let F of f)X.set(F.name,F);for(let F of this.config.tools)X.set(F.name,F);let Y=this.conversation.getConversationId(),V=tX(this.config),H=Array.from(X.values()),B=O5(this.conversation.getMessages()),A=nX({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:Y,parentAgentId:this.parentAgentId,model:W,logger:this.logger,telemetry:this.telemetry,tools:H,toolContextMetadata:{modelSupportsImages:V?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata,[of]:this.telemetry},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(V,H),initialMessages:B,systemPrompt:Z}),K=this.createAgentRuntimeImpl(A);if(this.activeRuntime=K,this.abortRequested)K.abort(this.abortReason);let G=K.subscribe((F)=>{this.handleRuntimeEvent(F)}),R,D;try{if($.isContinue)R=await K.continue(void 0);else R=await K.run("")}catch(F){D=F instanceof Error?F:Error(String(F))}finally{G();try{await this.activeTrackerWork}catch(F){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:F})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(R&&R.messages.length>0){let F=$8(R.messages);this.conversation.replaceMessages(F)}let U=new Date;try{return this.buildLegacyResult({runResult:R,thrownError:D,startedAt:J,endedAt:U})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize({tolerateSetupErrors:this.config.hookErrorMode!=="throw"})}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=mR([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((J)=>J.hooks)]);return{...$,beforeModel:async(J)=>{let Q=await $.beforeModel?.(J);if(Q?.stop)return Q;let Z=Q?.messages??J.request.messages,W=await this.prepareMessagesForModelRequest(Z);return{...Q,messages:W}}}}createRuntimePrepareTurn($,J){let Q=this.config.prepareTurn;if(!Q)return;return async(Z)=>{let W=$8(Z.messages),j=await this.prepareProviderMessagesForApi(W),f=await Q({agentId:Z.agentId,conversationId:Z.conversationId??this.conversation.getConversationId(),parentAgentId:Z.parentAgentId??null,iteration:Z.iteration,messages:W,apiMessages:j,abortSignal:Z.signal??new AbortController().signal,systemPrompt:Z.systemPrompt??"",tools:J,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Z.emitStatusNotice});if(!f)return;return{...f.messages?{messages:O5(f.messages)}:{},...f.systemPrompt!==void 0?{systemPrompt:f.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let J=await this.prepareProviderMessagesForApi(T5($));return O5(J)}async prepareProviderMessagesForApi($){let J=$,Q=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Z of Q)J=await Z.build(J);return this.messageBuilder.buildForApi(J)}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 J=this.toolStartedAt.get($.toolCall.toolCallId),Q=new Date,Z=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let W=$.message.content.find((Y)=>Y.type==="tool-result"),j=W?.type==="tool-result"&&W.isError===!0,f=j?bR(W?.type==="tool-result"?W.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Z,output:W?.type==="tool-result"?W.output:void 0,error:f,durationMs:J===void 0?0:Q.getTime()-J.getTime(),startedAt:J??Q,endedAt:Q};if(this.currentRunToolCalls.push(X),j){if(this.currentTurnFailedTools+=1,f)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${f}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let J=this.currentTurnFailedTools,Q=this.currentTurnSuccessfulTools;if(J>0&&Q===0){let Z=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${J} tool call(s) failed${Z?`: ${Z}`:""}`})}else if(Q>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let J of this.eventAdapter.translate($))this.emitLegacyEvent(J)}syncConversationFromRuntimeMessage($,J){if($.length>0){this.conversation.replaceMessages($8($));return}if(J.length===0)return;let Q=new Set(this.conversation.getMessages().map((W)=>W.id).filter((W)=>typeof W==="string")),Z=$8(J).filter((W)=>!W.id||!Q.has(W.id));if(Z.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Z])}emitLegacyEvent($){for(let J of this.listeners)try{J($)}catch(Q){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:Q})}}inspectLoopForToolCall($,J,Q){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Z=this.loopTracker.inspect({name:$,input:J});if(Z.kind==="ok")return;if(Z.kind==="soft"){if(Z.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Z.message}]});return}this.enqueueMistakeRecord({iteration:Q,reason:"tool_execution_failed",forceAtLimit:!0,details:Z.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 J=await this.mistakeTracker.record($);if(J.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:J.message}]}),this.activeRuntime?.abort(J.reason??J.message)})}buildLegacyResult($){let{runResult:J,thrownError:Q,startedAt:Z,endedAt:W}=$,j=W.getTime()-Z.getTime(),f=Q?"error":cR(J),X=J?.outputText||(J?.status==="failed"?J.error?.message:void 0)||"",Y=J?{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens>0?J.usage.cacheReadTokens:void 0,cacheWriteTokens:J.usage.cacheWriteTokens>0?J.usage.cacheWriteTokens:void 0,totalCost:J.usage.totalCost}:this.currentRunUsage,V=J?$8(J.messages):this.conversation.getMessages(),H=tX(this.config);if(Q)throw Q;return{text:X,usage:Y,messages:V,toolCalls:this.currentRunToolCalls,iterations:J?.iterations??0,finishReason:f,model:{id:this.config.modelId,provider:this.config.providerId,info:H},startedAt:Z,endedAt:W,durationMs:j}}}function vR($,J,Q,Z){if(!$)return;if(J==="debug"){$.debug(Q,Z);return}if(J==="error"&&$.error){$.error(Q,Z);return}let W=J==="warn"?"warn":J==="error"?"error":"info";$.log(Q,{...Z,severity:W})}function cR($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function uR($,J,Q,Z){let{buildInitialUserContent:W}=await Promise.resolve().then(() => sX);return W($,J,Q,Z)}function tX($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let J=xZ($);if(J?.[$.modelId])return J[$.modelId];return}import{buildClineSystemPrompt as eX}from"@cline/shared";function $Y($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return eX({ide:J.clineIdeName?.trim()||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,rules:`# Team Teammate Role
185
+ ${Q}`,platform:J.clinePlatform,metadata:J.workspaceMetadata})}function JY($,J){let Q=$.trim();if(J.providerId.toLowerCase()!=="cline")return Q;return eX({ide:J.clineIdeName||"Terminal",workspaceRoot:J.cwd?.trim()||"/",providerId:J.providerId,overridePrompt:Q,metadata:J.workspaceMetadata,platform:J.clinePlatform})}function H$($){let J={...$};return{getRuntimeConfig:()=>J,getConnectionConfig:()=>({providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking}),updateConnectionDefaults:(Q)=>{J={...J,...Q}}}}function l$($){let J=$.configProvider.getRuntimeConfig(),Q=$.kind==="teammate"?$Y($.prompt,J):JY($.prompt,J);return{...$.configProvider.getConnectionConfig(),systemPrompt:Q,tools:$.tools,maxIterations:$.maxIterations??J.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:J.hooks,extensions:J.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:J.logger,role:$.role}}function B$($){let J=l$($),Q=new V$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);return Q}var pR=sZ.object({systemPrompt:sZ.string().describe("System prompt defining the sub-agent's behavior"),task:sZ.string().describe("Task for the sub-agent to complete")});function A$($){return dR({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:lR(pR),execute:async(J,Q)=>{let Z=$.createSubAgentTools?await $.createSubAgentTools(J,Q):$.subAgentTools??[],W=B$({kind:"subagent",prompt:J.systemPrompt,configProvider:$.configProvider,tools:Z,maxIterations:$.defaultMaxIterations,parentAgentId:Q.agentId,abortSignal:Q.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),j=W.getAgentId(),f=W.getConversationId(),X=Q.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:j,conversationId:f,parentAgentId:X,input:J})}catch{}try{let Y=await W.run(J.task),V={text:Y.text,iterations:Y.iterations,finishReason:Y.finishReason,usage:{inputTokens:Y.usage.inputTokens,outputTokens:Y.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,result:V,agentResult:Y})}catch{}return V}catch(Y){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:j,conversationId:f,parentAgentId:X,input:J,error:Y instanceof Error?Y:Error(String(Y))})}catch{}throw Y}},timeoutMs:300000,retryable:!1})}import{createTool as X0,TEAM_AWAIT_TIMEOUT_MS as rR,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as iR,TEAM_RUN_TEXT_PREVIEW_LIMIT as nR,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as aR,TeamAttachOutcomeFragmentInputSchema as QY,TeamAwaitRunsInputSchema as ZY,TeamBroadcastInputSchema as WY,TeamBroadcastToolResultSchema as sR,TeamCancelRunInputSchema as jY,TeamCancelRunToolResultSchema as oR,TeamCleanupInputSchema as fY,TeamCleanupToolResultSchema as tR,TeamCreateOutcomeInputSchema as XY,TeamCreateOutcomeToolResultSchema as eR,TeamFinalizeOutcomeInputSchema as YY,TeamFinalizeOutcomeToolResultSchema as $z,TeamListOutcomesInputSchema as VY,TeamListRunsInputSchema as HY,TeamMailboxMessageToolResultSchema as Jz,TeamMissionLogInputSchema as BY,TeamMissionLogToolResultSchema as Qz,TeamOutcomeFragmentToolResultSchema as AY,TeamOutcomeToolResultSchema as Zz,TeamReadMailboxInputSchema as KY,TeamReviewOutcomeFragmentInputSchema as GY,TeamRunTaskInputSchema as FY,TeamRunTaskToolResultSchema as oZ,TeamRunToolSummarySchema as tZ,TeamSendMessageInputSchema as DY,TeamSendMessageToolResultSchema as Wz,TeamShutdownTeammateInputSchema as UY,TeamSimpleAgentStatusToolResultSchema as RY,TeamSpawnTeammateInputSchema as zY,TeamStatusInputSchema as LY,TeamStatusToolResultSchema as jz,TeamTaskInputSchema as _Y,TeamTaskToolResultSchema as n4,validateWithZod as k,zodToJsonSchema as Y0}from"@cline/shared";function OY($,J){let Q=$.replace(/\s+/g," ").trim();if(Q.length<=J)return Q;return`${Q.slice(0,Math.max(0,J-3)).trimEnd()}...`}function p$($,J){if($===void 0)throw Error(`Missing required field: ${J}`);return $}function fz($){let J=$.result;if(!J)return;return{textPreview:OY(J.text,nR),iterations:J.iterations,finishReason:J.finishReason,durationMs:J.durationMs,usage:{inputTokens:J.usage.inputTokens,outputTokens:J.usage.outputTokens,cacheReadTokens:J.usage.cacheReadTokens,cacheWriteTokens:J.usage.cacheWriteTokens,totalCost:J.usage.totalCost}}}function q5($){return $?.toISOString()}function eZ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:OY($.message,iR),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:q5($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:q5($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:q5($.heartbeatAt),lastProgressAt:q5($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:fz($)}}function Xz($){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 J8=["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 TY($){let J=[];if($.createBaseTools)J.push(...$.createBaseTools());J.push(...r$({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:l$({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:J,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function Q8($){let J=$.leadAgentId??"lead",Q=$.restoredFromPersistence===!0,Z=r$({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),W=[];for(let j of $.restoredTeammates??[]){if($.runtime.isTeammateActive(j.agentId))continue;TY({runtime:$.runtime,requesterId:J,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:j}),W.push(j.agentId)}return{tools:Z,restoredFromPersistence:Q,restoredTeammates:W}}function r$($){let J=$.allowSpawn??!0,Q=$.includeSpawnTool??!0,Z=$.includeManagementTools??!0,W=[];if(Q)W.push(X0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Y0(zY),execute:async(f)=>{let X=k(zY,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!J)throw Error("Spawning teammates is disabled in this context.");let Y={agentId:X.agentId,rolePrompt:X.rolePrompt};if(TY({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:Y}),!Z)$.onLeadToolsUnlocked?.(r$({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return k(RY,{agentId:X.agentId,status:"spawned"})}}));if(!Z)return W;W.push(X0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Y0(UY),execute:async(f)=>{let X=k(UY,f);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),k(RY,{agentId:X.agentId,status:"stopped"})}})),W.push(X0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Y0(LY),execute:async(f)=>{return k(LY,f),k(jz,$.runtime.getSnapshot())}})),W.push(X0({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:Y0(_Y),execute:async(f)=>{let X=k(_Y,f);switch(X.action){case"create":{let Y=new Set(aR.create??[]),V=Object.entries(f).filter(([B,A])=>Y.has(B)&&A!=null).map(([B])=>B),H=$.runtime.createTask({title:p$(X.title,"title"),description:p$(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return k(n4,{action:"create",taskId:H.id,status:H.status,...V.length>0?{ignoredFields:V,note:`Ignored fields for action=create: ${V.join(", ")}`}:{}})}case"list":return k(n4,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let Y=$.runtime.claimTask(p$(X.taskId,"taskId"),$.requesterId);return k(n4,{action:"claim",taskId:Y.id,status:Y.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 Y=$.runtime.completeTask(p$(X.taskId,"taskId"),$.requesterId,p$(X.summary,"summary"));return k(n4,{action:"complete",taskId:Y.id,status:Y.status})}case"block":{let Y=$.runtime.blockTask(p$(X.taskId,"taskId"),$.requesterId,p$(X.reason,"reason"));return k(n4,{action:"block",taskId:Y.id,status:Y.status})}}}}));let j=new Map;return W.push(X0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Y0(FY),execute:async(f)=>{let X=k(FY,f);if(X.runMode==="async"){let H=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return k(oZ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${H.id}.`,runId:H.id})}let Y=j.get(X.agentId);if(Y){let H=await Y;return k(oZ,{...H,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let V=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((H)=>k(oZ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:H.text,iterations:H.iterations})).finally(()=>{j.delete(X.agentId)});return j.set(X.agentId,V),await V}})),W.push(X0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Y0(jY),execute:async(f)=>{let X=k(jY,f),Y=$.runtime.cancelRun(X.runId,X.reason);return k(oR,{runId:Y.id,status:Y.status})}})),W.push(X0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Y0(HY),execute:async(f)=>k(tZ.array(),$.runtime.listRuns(k(HY,f)).map(eZ))})),W.push(X0({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:Y0(ZY),timeoutMs:rR,execute:async(f)=>{let X=k(ZY,f);if(X.runId){let H=await $.runtime.awaitRun(X.runId);return Xz(H),k(tZ,eZ(H))}let Y=await $.runtime.awaitAllRuns(),V=Y.filter((H)=>["failed","cancelled","interrupted"].includes(H.status));if(V.length>0){let H=V.map((B)=>`${B.id}:${B.status}${B.error?`(${B.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${H}`)}return k(tZ.array(),Y.map(eZ))}})),W.push(X0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Y0(DY),execute:async(f)=>{let X=k(DY,f),Y=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return k(Wz,{id:Y.id,toAgentId:Y.toAgentId})}})),W.push(X0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Y0(WY),execute:async(f)=>{let X=k(WY,f),Y=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return k(sR,{delivered:Y.length})}})),W.push(X0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Y0(KY),execute:async(f)=>{let X=k(KY,f);return k(Jz.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),W.push(X0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Y0(BY),execute:async(f)=>{let X=k(BY,f),Y=$.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 k(Qz,{id:Y.id})}})),W.push(X0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Y0(fY),execute:async(f)=>{if(k(fY,f),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),k(tR,{status:"cleaned"})}})),W.push(X0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Y0(XY),execute:async(f)=>{let X=k(XY,f),Y=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return k(eR,{outcomeId:Y.id,status:Y.status,requiredSections:Y.requiredSections})}})),W.push(X0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Y0(QY),execute:async(f)=>{let X=k(QY,f),Y=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return k(AY,{fragmentId:Y.id,status:Y.status})}})),W.push(X0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Y0(GY),execute:async(f)=>{let X=k(GY,f),Y=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return k(AY,{fragmentId:Y.id,status:Y.status})}})),W.push(X0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Y0(YY),execute:async(f)=>{let X=k(YY,f),Y=$.runtime.finalizeOutcome(X.outcomeId);return k($z,{outcomeId:Y.id,status:Y.status})}})),W.push(X0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Y0(VY),execute:async(f)=>{return k(VY,f),k(Zz.array(),$.runtime.listOutcomes())}})),W}function P5($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}function MY($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}var Yz=[{id:"read_files",description:"Read the content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Long files are windowed; page with start_line/end_line.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:A$({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...J8]}],Vz={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function Hz($){return $==="plan"||$==="yolo"?$:"act"}function PY($){let J=Hz($.mode),Q=c0[h1({mode:J})],Z=t2($.providerId??"",$.modelId??"",J,o2);return{mode:J,flags:{...Q,...Z,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function qY($,J){if(J.disabledToolIds?.has($))return!1;let{flags:Q}=PY(J);if($==="spawn_agent")return Q.enableSpawnAgent===!0;if($==="teams")return Q.enableAgentTeams===!0;if($==="editor")return Q.enableEditor===!0||Q.enableApplyPatch===!0;let Z=Vz[$];return Z?Q[Z]===!0:!1}function Bz($,J){if($.id==="editor"){let{flags:Q}=PY(J),Z=Q.enableApplyPatch===!0&&Q.enableEditor!==!0;return{...$,defaultEnabled:qY($.id,J),headlessToolNames:[Z?"apply_patch":"editor"]}}return{...$,defaultEnabled:qY($.id,J)}}function i$($={}){return Yz.map((J)=>Bz(J,$))}function N5($={}){return i$($).filter((J)=>J.defaultEnabled).map((J)=>J.id)}function w5($){if(!$.enabled)return new Set;let J=i$($.availabilityContext),Q=new Set(J.map((Z)=>Z.id));if(!$.allowlist||$.allowlist.length===0)return new Set(J.filter((Z)=>Z.defaultEnabled).map((Z)=>Z.id));for(let Z of $.allowlist)if(!Q.has(Z))throw Error(`Unknown tool "${Z}". Available tools: ${J.map((W)=>W.id).join(", ")}`);return new Set($.allowlist)}function a4($,J={}){return i$(J).filter((Q)=>$.has(Q.id)).flatMap((Q)=>Q.headlessToolNames)}function S5($,J={}){return a4($,J)}function n$($={}){let{executorOptions:J={},executors:Q,...Z}=$,W={...s2(J),...Q??{}};return X$({...Z,executors:W})}import{mkdirSync as Uz,writeFileSync as Rz}from"node:fs";import{dirname as zz}from"node:path";import{normalizeUserInput as Lz}from"@cline/shared";import{nanoid as _z}from"nanoid";var wY={};w(wY,{sanitizeSessionToken:()=>a$,parseTeamTaskSubSessionId:()=>W8,parseSubSessionId:()=>o4,makeTeamTaskSubSessionId:()=>s4,makeSubSessionId:()=>Z8,deriveSubsessionStatus:()=>t4});import{nanoid as Gz}from"nanoid";function a$($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function Z8($,J){let Q=a$($),Z=a$(J),W=`${Q}__${Z}`;return W.length>180?W.slice(0,180):W}function s4($,J){let Q=a$($),Z=a$(J);return`${Q}__teamtask__${Z}__${Gz(6)}`}function W8($){let Q=$.indexOf("__teamtask__");if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+12),j=W.lastIndexOf("__");if(j<=0)return null;let f=W.slice(0,j),X=W.slice(j+2);if(!Z||!f||!X)return null;return{rootSessionId:Z,agentId:f,teamTaskId:X}}function o4($){if(W8($))return null;let J="__",Q=$.indexOf(J);if(Q<=0)return null;let Z=$.slice(0,Q),W=$.slice(Q+J.length);if(!Z||!W)return null;return{rootSessionId:Z,agentId:W}}function t4($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let J=String($.reason??"").toLowerCase();if(J.includes("cancel")||J.includes("abort")||J.includes("interrupt"))return"cancelled";if(J.includes("fail")||J.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as a}from"zod";var yY={};w(yY,{isTerminalSessionStatus:()=>CY,isNonTerminalSessionStatus:()=>j0,SessionSource:()=>U0,SESSION_STATUSES:()=>e4,NON_TERMINAL_SESSION_STATUSES:()=>SY});import{SESSION_STATUS_VALUES as Fz}from"@cline/shared";var e4=Fz,SY=["idle","running","pending"];function CY($){return!SY.includes($)}function j0($){return!CY($)}var U0={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 Dz=a.enum(e4),S0=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:Dz,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 EY($){if(!$)return!1;return Object.values($).some((J)=>typeof J==="function")}function J7($,J){let Q=[...$??[],...J??[]];if(Q.length===0)return;let Z=[],W=new Set;for(let j of Q){if(W.has(j.name))continue;W.add(j.name),Z.push(j)}return Z}function bY($){return JSON.stringify($,(J,Q)=>{if(Q instanceof Error)return{name:Q.name,message:Q.message,stack:Q.stack};return Q})}function x1($){return typeof $==="string"&&$.trim()?$.trim():void 0}function $7($,J){let Q={...$};Q.id=x1(Q.id)??_z();let Z=Q.modelInfo&&typeof Q.modelInfo==="object"?{...Q.modelInfo}:void 0,W={id:x1(Z?.id)??x1(Q.modelId)??x1(J?.id),provider:x1(Z?.provider)??x1(Q.providerId)??x1(J?.provider),family:x1(Z?.family)??x1(J?.family)};if(delete Q.providerId,delete Q.modelId,W.id&&W.provider)Q.modelInfo={id:W.id,provider:W.provider,...W.family?{family:W.family}:{}};else delete Q.modelInfo;return Q}function C5($){return $.map((J)=>$7(J))}function y5($,J,Q=[]){let Z=$.map((Y,V)=>{let H=Q[V],A=H?.role===Y.role&&JSON.stringify(H.content)===JSON.stringify(Y.content)?{...H,...Y}:{...Y};return $7(A)}),W=Q.length,j=[];for(let Y=W;Y<Z.length;Y+=1)if(Z[Y]?.role==="assistant")j.push(Y);if(j.length===0){let Y=[...Z].reverse().findIndex((V)=>V.role==="assistant");if(Y===-1)return Z;j.push(Z.length-1-Y)}let f=j[j.length-1],X=j.some((Y)=>Z[Y]?.metrics);for(let Y of j){let V=Z[Y],H=V.metrics;if(!H&&Y===f&&!X){let B=J.usage;H={inputTokens:B.inputTokens,outputTokens:B.outputTokens,cacheReadTokens:B.cacheReadTokens??0,cacheWriteTokens:B.cacheWriteTokens??0,cost:B.totalCost}}Z[Y]={...$7(V,{id:J.model.id,provider:J.model.provider,family:J.model.info?.family}),...H?{metrics:H}:{},ts:V.ts??J.endedAt.getTime()}}return Z}function $6($){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 Oz=120;function s$($){let J=$?.trim();return J?J.slice(0,Oz):void 0}function Q7($){let J=Lz($??"").trim();if(!J)return;return s$(J.split(`
186
+ `)[0]?.trim())}function K$($){if(!$)return;let J={...$},Q=s$(typeof J.title==="string"?J.title:void 0);if(Q)J.title=Q;else delete J.title;return Object.keys(J).length>0?J:void 0}function J6($){let J=K$($.metadata)??{},Q=$.title!==void 0?s$($.title):Q7($.prompt);if(Q)J.title=Q;return Object.keys(J).length>0?J:void 0}function Z7($){let J=W8($);if(J)return{agent:"teammate",sessionId:J.rootSessionId,taskType:"team"};let Q=o4($);if(Q)return{agent:"subagent",sessionId:Q.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function W7($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:C5($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function hY($,J,Q){Uz(zz($),{recursive:!0}),Rz($,`${JSON.stringify(W7({updatedAt:J,context:Q,messages:[]}),null,2)}
187
+ `,"utf8")}function kY($,J){return S0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:J?.endedAt??$.endedAt??void 0,exit_code:J?.exitCode??$.exitCode??void 0,status:J?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:J?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function IY($,J,Q){let Z=0;while(!0){let W=await $();if(W===void 0)return{updated:!1};let j=await J(W);if(typeof j==="object"&&j!==null&&"updated"in j&&j.updated===!1){if(Z+=1,Z>=Q)return j;continue}return j}}O0();var xY={};w(xY,{summarizeUsageFromMessages:()=>f8,sumUsageTotals:()=>Q6,getCurrentContextSize:()=>j7,createInitialAccumulatedUsage:()=>G0,accumulateUsageTotals:()=>V0});function G0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function V0($,J){return{inputTokens:$.inputTokens+Math.max(0,J.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,J.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,J.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,J.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,J.totalCost??0)}}function Q6($){let J=G0();for(let Q of $)J=V0(J,Q);return J}function j8($){return typeof $==="number"&&Number.isFinite($)?$:0}function f8($){let J=G0();for(let Q of $){let Z=Q.metrics;if(!Z)continue;J=V0(J,{inputTokens:j8(Z.inputTokens),outputTokens:j8(Z.outputTokens),cacheReadTokens:j8(Z.cacheReadTokens),cacheWriteTokens:j8(Z.cacheWriteTokens),totalCost:j8(Z.cost)})}return J}function j7($){for(let J=$.length-1;J>=0;J-=1){let Q=$[J];if(Q?.role!=="assistant")continue;let Z=j8(Q.metrics?.inputTokens);return Z>0?Z:void 0}return}function Tz($){if(!$||typeof $!=="object")return;let J=$,Q=J.skill??J.skill_name??J.skillName;if(typeof Q!=="string")return;let Z=Q.trim();return Z.length>0?Z:void 0}function f7($){if(!$||typeof $!=="object")return{};let J=$;return{agentId:typeof J.agentId==="string"?J.agentId:void 0,conversationId:typeof J.conversationId==="string"?J.conversationId:void 0,parentAgentId:typeof J.parentAgentId==="string"?J.parentAgentId:void 0}}function g1($){let J=$.agentId?.trim();if(!J)return;let Q=$.parentAgentId?.trim()||void 0,Z=$.teamRole,W="root";if(Z==="teammate")W="team_teammate";else if(Z==="lead")W="team_lead";else if(Q)W="subagent";return{agentId:J,agentKind:W,conversationId:$.conversationId?.trim()||void 0,parentAgentId:Q,createdByAgentId:$.createdByAgentId?.trim()||Q||void 0,isSubagent:Boolean(Q),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Z,teamAgentId:$.teamAgentId?.trim()||void 0}}function Mz($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function qz($){let J=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let Q of J){let Z=Q?.trim();if(Z)return Z}return $.isPrimaryAgentEvent?"root":"unknown"}function X7($,J,Q){let{sessionId:Z,config:W,liveSession:j,emit:f}=$,X=W.telemetry,Y=j?.runtime.teamRuntime,V=Q?.isPrimaryAgentEvent??!0,H=f7(J),B=g1({agentId:Q?.agentId??H.agentId,conversationId:Q?.conversationId??H.conversationId,parentAgentId:Q?.parentAgentId??H.parentAgentId,createdByAgentId:Q?.createdByAgentId,teamId:Q?.teamId??Y?.getTeamId(),teamName:Q?.teamName??Y?.getTeamName(),teamRole:Q?.teamRole,teamAgentId:Q?.teamAgentId});if(J.type==="content_start"&&J.contentType==="tool"&&J.toolName==="skills"){let A=Tz(J.input);if(A)vJ(X,{ulid:Z,skillName:A,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:W.providerId,modelId:W.modelId,...B})}if(J.type==="content_end"&&J.contentType==="tool"){let A=J.toolName??"unknown",K=!J.error;if(mJ(X,{ulid:Z,tool:A,autoApproved:void 0,success:K,modelId:W.modelId,provider:W.providerId,...B}),!K&&(A==="editor"||A==="apply_patch"))cJ(X,{ulid:Z,modelId:W.modelId,provider:W.providerId,errorType:J.error,...B})}if(J.type==="notice"&&J.reason==="api_error")H4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.message,...B});if(J.type==="error")H4(X,{ulid:Z,model:W.modelId,provider:W.providerId,errorMessage:J.error?.message??"unknown error",...B});if(J.type==="usage"&&j?.turnUsageBaseline){let A=Mz(J);if(V){j.turnPrimaryUsage=V0(j.turnPrimaryUsage??G0(),A);let G=V0(j.turnUsageBaseline,j.turnPrimaryUsage);$.usageBySession.set(Z,G),g2(X,{ulid:Z,provider:W.providerId,model:W.modelId,source:"assistant",mode:W.mode,...B}),xJ(X,{ulid:Z,tokensIn:J.inputTokens,tokensOut:J.outputTokens,cacheWriteTokens:J.cacheWriteTokens,cacheReadTokens:J.cacheReadTokens,totalCost:J.cost,model:W.modelId,...B})}else{let G=qz({isPrimaryAgentEvent:V,overrides:Q,eventMetadata:H}),R=j.turnUsageByAgent??new Map;j.turnUsageByAgent=R,R.set(G,V0(R.get(G)??G0(),A))}let K=V0(j.turnPrimaryUsage??G0(),Q6(j.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Z,V0(j.turnAggregateUsageBaseline??j.turnUsageBaseline,K))}if(J.type==="iteration_end"&&V)$.persistMessages(Z,j?.agent.getMessages()??[],j?.config.systemPrompt);f({type:"agent_event",payload:{sessionId:Z,event:J,teamAgentId:Q?.teamAgentId,teamRole:Q!==void 0?Q.teamRole??(V?"lead":void 0):void 0}}),f({type:"chunk",payload:{sessionId:Z,stream:"agent",chunk:bY(J),ts:Date.now()}})}function G$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as h_}from"@cline/shared";W1();import{existsSync as x5,readFileSync as AL,statSync as KL}from"node:fs";import{basename as GL,dirname as k5,join as g5,resolve as I5}from"node:path";import{discoverPluginModulePaths as FL,resolveConfiguredPluginModulePaths as WV,resolvePluginConfigSearchPaths as DL,SKILLS_CONFIG_DIRECTORY_NAME as UL}from"@cline/shared/storage";import{resolve as pz}from"node:path";import{normalizePluginManifest as rz}from"@cline/shared";import{existsSync as R0,readFileSync as Y8}from"node:fs";import{builtinModules as Pz,createRequire as B7}from"node:module";import{dirname as F$,extname as W6,isAbsolute as Nz,resolve as p}from"node:path";import{fileURLToPath as mY}from"node:url";import{PLUGIN_FILE_EXTENSIONS as wz}from"@cline/shared";var vY=F$(mY(import.meta.url)),Sz=B7(import.meta.url),Cz=p(vY,"..","..","..","..",".."),Y7=bz(Cz),yz=["@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"],A7=new Set(Pz.flatMap(($)=>[$,$.replace(/^node:/,"")])),Z6=new Set(wz),Ez=["development","node","import","require","default"];function bz($){let J={},Q={"@cline/sdk":p($,"packages/sdk/src/index.ts"),"@cline/agents":p($,"packages/agents/src/index.ts"),"@cline/core":p($,"packages/core/src/index.ts"),"@cline/llms":p($,"packages/llms/src/index.ts"),"@cline/shared":p($,"packages/shared/src/index.ts"),"@cline/shared/storage":p($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":p($,"packages/shared/src/db/index.ts")};for(let[Z,W]of Object.entries(Q))if(R0(W))J[Z]=W;for(let Z of["agents","core","llms","shared"]){let W=p($,"packages",Z),j=p(W,"package.json");if(!R0(j))continue;try{let f=JSON.parse(Y8(j,"utf8"));if(typeof f.name!=="string"||!f.exports)continue;if(typeof f.exports==="string"){let X=p(W,f.exports);if(R0(X))J[f.name]=X;continue}if(typeof f.exports!=="object")continue;for(let[X,Y]of Object.entries(f.exports)){let V=hz(W,Y);if(!V)continue;let H=X==="."?f.name:`${f.name}/${X.replace(/^\.\//,"")}`;J[H]=V}}catch{}}return J}function hz($,J){let Q=K7(J);if(!Q)return null;let Z=cY($,Q);for(let W of Z)if(R0(W))return W;return null}function K7($,J=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(J.has($))return null;J.add($);let Q=$;for(let Z of Ez){let W=K7(Q[Z],J);if(W)return W}return null}function cY($,J){let Q=J.replace(/^\.\//,""),Z=[p($,J)];if(Q.startsWith("dist/")){let W=Q.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[p($,`${W}.ts`),p($,`${W}.tsx`),p($,`${W}.mts`),p($,`${W}.cts`),...Z]}return Z}function kz($){return Object.fromEntries(Object.entries($).sort(([J],[Q])=>Q.length-J.length))}function E5($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function X8($){if($.startsWith("@")){let[J,Q]=$.split("/",3);return Q?`${J}/${Q}`:$}return $.split("/",1)[0]??$}function Iz($){let J=X8($);if($===J)return".";return`.${$.slice(J.length)}`}function uY($){return X8($).startsWith("@cline/")}function V7($,J){let Q=X8(J),Z=F$($);while(!0){let W=p(Z,"node_modules",Q);if(R0(W)||R0(p(W,"package.json")))return!0;let j=p(Z,"..");if(j===Z)return!1;Z=j}}function gY($){return H7($)!==null}function H7($){try{return Sz.resolve($)}catch{}return xz($)}function xz($){let J=X8($),Q=dY(J);if(!Q)return null;let Z=p(Q,"package.json");try{let W=JSON.parse(Y8(Z,"utf8")),j=Iz($),f=j==="."&&typeof W.exports==="string"?W.exports:W.exports&&typeof W.exports==="object"&&Object.hasOwn(W.exports,j)?W.exports[j]:void 0,X=K7(f)??(j==="."&&typeof W.main==="string"?W.main:null);if(!X)return null;let Y=p(Q,X),V=[Y,...cY(Q,X).filter((H)=>H!==Y)];for(let H of V)if(R0(H))return H;return null}catch{return null}}function gz(){let $=[vY],J=process.env.CLINE_WRAPPER_PATH?.trim();if(J)$.push(F$(F$(J)));let Q=process.execPath?.trim();if(Q)$.push(F$(Q));return[...new Set($.map((Z)=>p(Z)))]}function mz($,J){let Q=$;while(!0){let Z=p(Q,"package.json");if(R0(Z))try{if(JSON.parse(Y8(Z,"utf8")).name===J)return Q}catch{}let W=p(Q,"node_modules",J,"package.json");if(R0(W))return F$(W);let j=p(Q,"..");if(j===Q)return null;Q=j}}function dY($){for(let J of gz()){let Q=mz(J,$);if(Q)return Q}return null}function vz($){let Q=F$($);for(let Z=0;Z<4;Z++){let W=p(Q,"package.json");if(R0(W))try{let f=JSON.parse(Y8(W,"utf8"));return f!=null&&typeof f==="object"&&"cline"in f}catch{return!1}let j=p(Q,"..");if(j===Q)return!1;Q=j}return!1}function lY($,J){let Q=J.startsWith("file:")?mY(J):Nz(J)?J:p(F$($),J);if(R0(Q)&&Z6.has(W6(Q)))return Q;for(let Z of Z6){let W=`${Q}${Z}`;if(R0(W))return W}for(let Z of Z6){let W=p(Q,`index${Z}`);if(R0(W))return W}return null}function pY($){let J=new Set,Q=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Z of Q)for(let W of $.matchAll(Z)){let j=W[1];if(j)J.add(j)}return[...J]}function cz($){return W6($)!==".ts"}function rY($,J,Q=new Set){if(Q.has($)||!R0($))return;if(Q.add($),!Z6.has(W6($)))return;let Z=Y8($,"utf8"),W=cz($);for(let j of pY(Z)){if(j.startsWith("node:")||A7.has(j))continue;if(E5(j)){if(!W)continue;if(Object.hasOwn(Y7,j)||Object.hasOwn(Y7,X8(j))||V7($,j)||uY(j)&&gY(j)||J&&gY(j))continue;throw Error(`Cannot find module '${X8(j)}'`)}let f=lY($,j);if(f)rY(f,J,Q)}}function iY($,J=new Set,Q=new Set){if(J.has($)||!R0($))return Q;if(J.add($),!Z6.has(W6($)))return Q;let Z=Y8($,"utf8");for(let W of pY(Z)){if(Q.add(W),E5(W))continue;let j=lY($,W);if(j)iY(j,J,Q)}return Q}function uz($,J){let Q=B7($),Z={},W=iY($),j=new Set(yz);for(let[f,X]of Object.entries(Y7)){try{Q.resolve(f);continue}catch{}Z[f]=X}for(let f of W)if(E5(f)&&(uY(f)||J))j.add(f);for(let f of j){if(Object.hasOwn(Z,f)||V7($,f))continue;let X=H7(f);if(X)Z[f]=X}if(!J)return Z;for(let f of W){if(!E5(f)||Object.hasOwn(Z,f)||V7($,f)||f.startsWith("node:")||A7.has(f))continue;let X=H7(f);if(X)Z[f]=X}return Z}function dz($){let J=W6($);return J===".ts"||J===".tsx"||J===".mts"||J===".cts"}var o$;function lz(){if(o$!==void 0)return o$;let $=dY("jiti");if(!$)return o$=null,null;let J=p($,"dist","babel.cjs");if(!R0(J))return o$=null,null;try{let Z=B7(J)(J);o$=typeof Z==="function"?Z:null}catch{o$=null}return o$}async function nY($,J={}){let Q=!vz($);rY($,Q);let Z=uz($,Q),W=kz(Z),j=await import("jiti"),f=typeof j==="function"?j:typeof j.default==="function"?j.default:void 0;if(!f)throw Error("Unable to load jiti");let X=Object.entries(W).filter(([,B])=>dz(B)).map(([B])=>B),Y=lz(),V=Y?(B)=>Y({...B,interopDefault:!0}):void 0;return await f($,{alias:W,cache:J.useCache,requireCache:J.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...A7],transformModules:X,tryNative:!1,...V?{transform:V}:{}}).import($,{})}function aY($,J){if(!$)return!0;if($.providerIds?.length){if(!J?.providerId||!$.providerIds.includes(J.providerId))return!1}if($.modelIds?.length){if(!J?.modelId||!$.modelIds.includes(J.modelId))return!1}return!0}function sY($){return typeof $==="object"&&$!==null}function G7($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function iz($,J){if(!sY($.manifest))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);if(!G7($.manifest.capabilities))throw Error(`Invalid plugin module at ${J}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${J}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!G7($.manifest.providerIds))throw Error(`Invalid plugin module at ${J}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!G7($.manifest.modelIds))throw Error(`Invalid plugin module at ${J}: manifest.modelIds must be a string array when provided`)}function nz($,J){if(!sY($))throw Error(`Invalid plugin module at ${J}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${J}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${J}: missing required "manifest"`);iz($,J)}async function j6($,J={}){let Q=pz(J.cwd??process.cwd(),$),Z=await nY(Q,{useCache:J.useCache}),W=J.exportName??"plugin",j=Z.default??Z[W];nz(j,Q);let f=j,X=f.setup,Y=X?(V,H)=>{let B={...J.session,...H.session},A={...H,session:Object.keys(B).length>0?B:void 0,client:J.client??H.client,user:J.user??H.user,workspaceInfo:J.workspaceInfo??H.workspaceInfo,automation:J.automation??H.automation,logger:J.logger??H.logger,telemetry:J.telemetry??H.telemetry};return X(V,A)}:void 0;return{...f,manifest:rz(f.manifest),setup:Y}}async function b5($,J={}){return(await t$($,J)).plugins}async function t$($,J={}){let Q=[],Z=[],W=new Map,j=0;for(let X of $)try{let Y=await j6(X,J);if(!aY(Y.manifest,J))continue;let V=W.get(Y.name);if(V)Z.push({type:"duplicate_plugin_override",pluginName:Y.name,pluginPath:X,overriddenPluginPath:V.pluginPath,message:`Plugin "${Y.name}" from ${X} overrides ${V.pluginPath}`});W.set(Y.name,{plugin:Y,pluginPath:X,order:j++})}catch(Y){let V=Y instanceof Error?Y.message:String(Y);Q.push({pluginPath:X,phase:"load",message:V,stack:Y instanceof Error?Y.stack:void 0})}let f=[...W.values()].sort((X,Y)=>X.order-Y.order);return{plugins:f.map((X)=>X.plugin),pluginPaths:f.map((X)=>X.pluginPath),failures:Q,warnings:Z}}import{existsSync as R7}from"node:fs";import{createRequire as ZV}from"node:module";import{dirname as h5,join as H8}from"node:path";import{fileURLToPath as ez}from"node:url";var JV={};w(JV,{resolveSubprocessRuntimeExecutable:()=>F7,buildSubprocessSandboxCommand:()=>$V,SubprocessSandbox:()=>V8,CLINE_JS_RUNTIME_PATH_ENV:()=>eY});import{spawn as az}from"node:child_process";import{basename as sz}from"node:path";import{augmentNodeCommandForDebug as oz,withResolvedClineBuildEnv as tz}from"@cline/shared";function oY($){if($ instanceof Error)return $;return Error(String($))}var eY="CLINE_JS_RUNTIME_PATH";function tY($){let J=$?.trim();if(!J)return!1;let Q=sz(J).toLowerCase();return Q==="node"||Q==="node.exe"||Q==="bun"||Q==="bun.exe"}function F7($={}){let J=$.env??process.env,Q=$.runtimeExecutable?.trim()||J[eY]?.trim();if(Q)return Q;let Z=$.execPath?.trim()||process.execPath;if(tY(Z))return Z;for(let W of[J.BUN_EXEC_PATH,J.npm_node_execpath,J.NODE]){let j=W?.trim();if(j&&tY(j))return j}return"node"}function $V($,J={}){let Q=F7({env:J.env,execPath:J.execPath,runtimeExecutable:J.runtimeExecutable});return oz([Q,...$],{env:J.env,execArgv:J.execArgv,debugRole:J.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class V8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let J=this.pending.get($);if(!J)return;if(this.pending.delete($),J.timeout)clearTimeout(J.timeout);return J}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],J=$V($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),Q=az(J[0]??F7(this.options),J.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:tz(process.env),windowsHide:!0});this.process=Q;let Z="",W=(j)=>{let f=Z+j;Z=f.length>4000?f.slice(-4000):f};Q.stderr?.setEncoding("utf8"),Q.stderr?.on("data",(j)=>{W(j)}),Q.on("message",(j)=>{this.onMessage(j)}),Q.on("error",(j)=>{this.failPending(Error(`${this.processLabel} process error: ${oY(j).message}`))}),Q.on("exit",(j,f)=>{this.process=null;let X=Z.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(j)}, signal=${String(f)})${X?`: ${X}`:""}`))})}async call($,J,Q={}){this.start();let Z=this.process;if(!Z||Z.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let W=`req_${++this.requestCounter}`,j={type:"call",id:W,method:$,args:J};return await new Promise((f,X)=>{let Y={resolve:(V)=>f(V),reject:X};if((Q.timeoutMs??0)>0)Y.timeout=setTimeout(()=>{this.clearPendingRequest(W),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${Q.timeoutMs}ms: ${$}`))},Q.timeoutMs);this.pending.set(W,Y),Z.send(j,(V)=>{if(!V)return;let H=this.clearPendingRequest(W);if(!H)return;H.reject(Error(`${this.processLabel} failed to send call "${$}": ${oY(V).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((J)=>{let Q=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}J()},300);$.once("exit",()=>{clearTimeout(Q),J()});try{$.kill("SIGTERM")}catch{clearTimeout(Q),J()}}),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 J=this.clearPendingRequest($.id);if(!J)return;if($.ok){J.resolve($.result);return}J.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[J,Q]of this.pending.entries()){if(this.pending.delete(J),Q.timeout)clearTimeout(Q.timeout);Q.reject($)}}}function $L($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],rules:$.contributions?.rules??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],mcpServers:$.contributions?.mcpServers??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function f6($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function JL(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function QL(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let Q=ZV($).resolve(`${JL()}/package.json`),Z=H8(h5(Q),"extensions","plugin-sandbox-bootstrap.js");return R7(Z)?Z:void 0}catch{return}}function ZL(){let $=process.execPath?.trim();if(!$)return;let J=H8(h5(h5($)),"extensions","plugin-sandbox-bootstrap.js");return R7(J)?J:void 0}function WL(){let $=h5(ez(import.meta.url)),J=ZV(import.meta.url),Q=[H8($,"plugin-sandbox-bootstrap.js"),H8($,"extensions","plugin-sandbox-bootstrap.js"),H8($,"agents","plugin-sandbox-bootstrap.js"),QL(),ZL()];for(let j of Q.filter((f)=>typeof f==="string"))if(R7(j))return{file:j};let Z=H8($,"plugin-sandbox-bootstrap.ts"),W="jiti";try{W=J.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(W)});`,`const jiti = createJiti(${JSON.stringify(Z)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Z)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
188
+ `)}}var D7=WL();function U7($,J,Q){if(typeof $==="number"&&$>0)return $;if(Q){let Z=process.env[Q];if(Z){let W=Number(Z);if(Number.isInteger(W)&&W>0)return W}}return J}async function B8($){let J=new V8({name:"plugin-sandbox",..."file"in D7?{bootstrapFile:D7.file}:{bootstrapScript:D7.script},onEvent:$.onEvent}),Q=U7($.importTimeoutMs,4000,"CLINE_PLUGIN_IMPORT_TIMEOUT_MS"),Z=U7($.hookTimeoutMs,3000),W=U7($.contributionTimeoutMs,60000),j={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},f,X=()=>{return f??=J.call("initialize",j,{timeoutMs:Q}).finally(()=>{f=void 0}),f},Y;try{Y=await J.call("initialize",j,{timeoutMs:Q})}catch(B){throw await J.shutdown().catch(()=>{}),B}let V=Y.plugins.map($L);return{extensions:V.map((B)=>{let A={name:B.name,__clinePluginPath:B.pluginPath,manifest:B.manifest,setup:(K)=>{jL(K,J,B,W,X),fL(K,J,B,W,X),XL(K,J,B,W,X),VL(K,J,B,W,X),YL(K,B)}};return A.hooks=BL(J,B,Z,X),A}),failures:Y.failures,pluginPaths:V.map((B)=>B.pluginPath),shutdown:async()=>{await J.shutdown()},warnings:Y.warnings}}function jL($,J,Q,Z,W){for(let j of Q.contributions?.tools??[]){let f={name:j.name,description:j.description??"",inputSchema:j.inputSchema??{type:"object",properties:{}},timeoutMs:j.timeoutMs,retryable:j.retryable,execute:async(X,Y)=>{try{return await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}catch(V){if(!f6(V))throw V;return await W(),await J.call("executeTool",{pluginId:Q.pluginId,contributionId:j.id,input:X,context:Y},{timeoutMs:Z})}}};$.registerTool(f)}}function fL($,J,Q,Z,W){for(let j of Q.contributions?.commands??[])$.registerCommand({name:j.name,description:j.description,handler:async(f)=>{try{return await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}catch(X){if(!f6(X))throw X;return await W(),await J.call("executeCommand",{pluginId:Q.pluginId,contributionId:j.id,input:f},{timeoutMs:Z})}}})}function XL($,J,Q,Z,W){for(let j of Q.contributions?.rules??[])$.registerRule({id:j.ruleId,source:j.source,content:j.hasContentHandler===!0?async()=>{try{return await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}catch(f){if(!f6(f))throw f;return await W(),await J.call("resolveRuleContent",{pluginId:Q.pluginId,contributionId:j.id},{timeoutMs:Z})}}:j.content??""})}function YL($,J){for(let Q of J.contributions?.providers??[])$.registerProvider({name:Q.name,description:Q.description,metadata:Q.metadata});for(let Q of J.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:Q.eventType,source:Q.source,description:Q.description,attributesSchema:Q.attributesSchema,payloadSchema:Q.payloadSchema,examples:Q.examples,metadata:Q.metadata});for(let Q of J.contributions?.mcpServers??[])$.registerMcpServer(Q)}function VL($,J,Q,Z,W){for(let j of Q.contributions?.messageBuilders??[])$.registerMessageBuilder({name:j.name,async build(f){try{let X=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return QV(X)?X:f}catch(X){if(!f6(X))throw X;await W();let Y=await J.call("buildMessages",{pluginId:Q.pluginId,contributionId:j.id,messages:f},{timeoutMs:Z});return QV(Y)?Y:f}}})}function QV($){return Array.isArray($)&&$.every((J)=>typeof J==="object"&&J!==null&&("role"in J)&&("content"in J))}function HL($,J,Q,Z,W){return async(j)=>{try{return await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}catch(f){if(!f6(f))throw f;return await W(),await $.call("invokeHook",{pluginId:J,hookName:Q,payload:j},{timeoutMs:Z})}}}function BL($,J,Q,Z){let W={};for(let j of J.hooks??[])W[j]=HL($,J.pluginId,j,Q,Z);return Object.keys(W).length>0?W:void 0}var L7="package.json",RL="package";function X6($){return DL($)}function Y6($){return FL($)}function zL($){try{return x5($)&&KL($).isDirectory()}catch{return!1}}function _7($){let J=[],Q=new Set;for(let Z of $){let W=I5(Z);if(Q.has(W))continue;Q.add(W),J.push(W)}return J}function jV($){let J=_7($);return L5(J)}function fV($){return X6($).flatMap((J)=>Y6(J)).filter((J)=>x5(J))}function LL($,J){let Q=[];for(let Z of $)try{Q.push(...WV([Z],J))}catch{}return Q}function z7($){return typeof $==="object"&&$!==null}function _L($){try{let J=JSON.parse(AL(g5($,L7),"utf8"));if(!z7(J)||!z7(J.cline))return[];let Q=J.cline.plugins;if(!Array.isArray(Q))return[];let Z=[];for(let W of Q){if(typeof W==="string"){Z.push(W);continue}if(!z7(W)||!Array.isArray(W.paths))continue;for(let j of W.paths)if(typeof j==="string")Z.push(j)}return Z}catch{return[]}}function XV($,J){let Q=I5(J);return _L($).some((Z)=>I5($,Z)===Q)}function OL($,J){return GL($)===RL&&x5(g5(k5($),L7))&&XV(k5($),J)}function TL($){let J=I5($),Q=[],Z=k5(J);while(!0){if(OL(Z,J)){Q.push(Z);break}if(x5(g5(Z,L7))){if(XV(Z,J))Q.push(Z);break}let W=k5(Z);if(W===Z)break;Z=W}return _7(Q)}function e$($={}){let J=$.cwd??process.cwd(),Q=fV($.workspacePath),Z=WV($.pluginPaths??[],J);return jV([...Z,...Q])}function ML($={}){let J=$.cwd??process.cwd(),Q=fV($.workspacePath),Z=LL($.pluginPaths??[],J);return jV([...Z,...Q])}function $2($){let J=[];for(let Q of $)for(let Z of TL(Q)){let W=g5(Z,UL);if(zL(W))J.push(W)}return _7(J)}function YV($={}){return $2(ML($))}async function A8($={}){let J=e$($);if(J.length===0)return{extensions:[],failures:[],warnings:[],pluginPaths:[]};if($.mode==="in_process"){let Z=await t$(J,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Z.plugins,failures:Z.failures,pluginPaths:Z.pluginPaths,warnings:Z.warnings}}let Q=await B8({pluginPaths:J,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:Q.extensions??[],shutdown:Q.shutdown,failures:Q.failures,pluginPaths:Q.pluginPaths,warnings:Q.warnings}}import{execFile as qL}from"node:child_process";import{promisify as PL}from"node:util";var NL=PL(qL);function O7($,J){$?.log(J,{severity:"warn"})}function wL($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))return;let Q=J;if(!Q.latest||!Array.isArray(Q.history))return;let Z=Q.latest,W=Q.history.filter((j)=>!!j&&typeof j==="object"&&typeof j.ref==="string"&&typeof j.createdAt==="number"&&typeof j.runCount==="number");if(typeof Z.ref!=="string"||typeof Z.createdAt!=="number"||typeof Z.runCount!=="number")return;return{latest:Z,history:W}}async function J2($,J){let Q=await NL("git",["-C",$,...J],{windowsHide:!0});return{stdout:Q.stdout.trim(),stderr:Q.stderr.trim()}}async function T7($,J){if(!$)return;let Q=`refs/cline/checkpoints/${J}/`;try{let{stdout:Z}=await J2($,["for-each-ref","--format=%(refname)",Q]),W=Z.trim().split(`
189
+ `).filter(Boolean);await Promise.allSettled(W.map((j)=>J2($,["update-ref","-d",j])))}catch{}}async function VV($,J,Q){if(!$||Q.length===0)return;await Promise.allSettled(Q.map((Z)=>J2($,["update-ref",`refs/cline/checkpoints/${J}/${Z.runCount}`,Z.ref])))}function SL($,J){let Q=$.findIndex((Z)=>Z.runCount===J.runCount);if(Q<0)return[...$,J];return $.map((Z,W)=>W===Q?J:Z)}function HV($){let J=$.initialRunCount??0,Q,Z=async()=>{if(Q!==void 0)return Q;try{Q=(await J2($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{Q=!1}return Q},W=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:J});if(!await Z())return;let j=async(V)=>{try{let B=(await J2($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!B)return;return{ref:B,createdAt:Date.now(),runCount:J,kind:"commit"}}catch(H){O7($.logger,`${V}: ${H instanceof Error?H.message:String(H)}`);return}},f=`cline checkpoint session=${$.sessionId} run=${J}`,X="";try{X=(await J2($.cwd,["stash","create",f])).stdout.trim()}catch(V){return O7($.logger,`Checkpoint snapshot failed: ${V instanceof Error?V.message:String(V)}`),j("Checkpoint HEAD fallback failed")}if(!X)return j("Checkpoint HEAD fallback failed");let Y=`refs/cline/checkpoints/${$.sessionId}/${J}`;try{await J2($.cwd,["update-ref",Y,X])}catch(V){O7($.logger,`Checkpoint store failed: ${V instanceof Error?V.message:String(V)}`);return}return{ref:X,createdAt:Date.now(),runCount:J,kind:"stash"}};return{beforeRun:async({snapshot:j})=>{if(j.parentAgentId!=null)return;J+=1;return},beforeModel:async({snapshot:j})=>{if(j.parentAgentId!=null||j.iteration!==1||J<1)return;let f=await W();if(!f)return;let X=await $.readSessionMetadata(),Y=wL(X);if(Y?.latest.ref===f.ref)return;let V=SL(Y?.history??[],f);await $.writeSessionMetadata({...X??{},checkpoint:{latest:f,history:V}});return}}}import{spawn as gL}from"node:child_process";import{appendFileSync as mL,readFileSync as vL}from"node:fs";import{join as cL}from"node:path";import{augmentNodeCommandForDebug as KV,withResolvedClineBuildEnv as P7}from"@cline/shared";import{ensureHookLogDir as BV}from"@cline/shared/storage";function K8($,J){if(!J)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:J}}import{existsSync as CL,readdirSync as yL}from"node:fs";import{basename as EL,extname as bL,join as hL}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as m5,resolveHooksConfigSearchPaths as kL}from"@cline/shared/storage";function V6($){return kL($)}var G8;((H)=>{H.TaskStart="TaskStart";H.TaskResume="TaskResume";H.TaskCancel="TaskCancel";H.TaskComplete="TaskComplete";H.TaskError="TaskError";H.PreToolUse="PreToolUse";H.PostToolUse="PostToolUse";H.UserPromptSubmit="UserPromptSubmit";H.PreCompact="PreCompact";H.SessionShutdown="SessionShutdown"})(G8||={});var H6={["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"},IL=new Map(Object.values(G8).map(($)=>[$.toLowerCase(),$])),xL=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function B6($){let J=bL($).toLowerCase();if(!xL.has(J))return;let Q=EL($,J).trim().toLowerCase();return IL.get(Q)}function D$($){let J=[],Q=new Set,Z=V6($).filter((W)=>CL(W));for(let W of Z)try{for(let j of yL(W,{withFileTypes:!0})){if(!j.isFile())continue;let f=B6(j.name);if(!f)continue;let X=hL(W,j.name);if(Q.has(X))continue;Q.add(X),J.push({fileName:f,hookEventName:H6[f],path:X})}}catch{}return J.sort((W,j)=>W.path.localeCompare(j.path))}function c5($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))J[Q]=typeof Z==="string"?Z:JSON.stringify(Z);return J}function v5($,J,Q){let Z=Q instanceof Error?`: ${Q.message}`:"",W=`${J}${Z}`;if($){try{$.log(W,{severity:"warn",...Q!==void 0?{error:Q}:{}})}catch{}return}console.warn(W)}function uL($,J){if(!J)return $;if(!$)return{...J};let Q=[$.context,J.context].filter((W)=>typeof W==="string"&&W.length>0).join(`
190
190
  `),Z=[...$.appendMessages??[],...J.appendMessages??[]];return{cancel:$.cancel===!0||J.cancel===!0?!0:void 0,review:$.review===!0||J.review===!0?!0:void 0,context:Q||void 0,overrideInput:J.overrideInput!==void 0?J.overrideInput:$.overrideInput,systemPrompt:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,appendMessages:Z.length>0?Z:void 0}}function dL($){if(!$||typeof $!=="object")return;let J=$,Q=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Q,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function M7($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function z0($,J){let Q=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Z={rootSessionId:J.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Z,workspaceRoots:J.workspacePath?[J.workspacePath]:[],workspaceInfo:J.workspaceInfo,userId:Q,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function lL($){let J=$.trim();if(!J)return{};let Z=J.split(`
191
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function pL($,J){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((Z,W)=>{let j=!1,f=()=>{Q.off("error",Y),Q.off("finish",V),$.off("close",H)},X=(B)=>{if(j)return;if(j=!0,f(),B){let A=B.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Z();return}W(B);return}Z()},Y=(B)=>X(B),V=()=>X(),H=()=>X();Q.on("error",Y),Q.once("finish",V),$.once("close",H);try{Q.end(J)}catch(B){X(B)}})}async function FV($,J){if(J.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await KV($,J)}catch(Q){let Z=nL(J.command,process.platform,Q);if(!Z)throw Q;return await KV($,{...J,command:Z})}}async function KV($,J){let Q=GV(J.command,{env:J.env,debugRole:"hook"}),Z=gL(Q[0],Q.slice(1),{cwd:J.cwd,env:P7(J.env),stdio:J.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:J.detached,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>A())}),j=new Promise((A,K)=>{Z.once("error",(G)=>K(G))}),f=JSON.stringify($);if(await Promise.race([W,j]),await pL(Z,f),J.detached){Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,H;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},J.timeoutMs);Z.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=lL(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,j])}function rL($){try{let Q=vL($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let Z=Q.slice(2).trim();if(!Z)return;let W=Z.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function iL($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function nL($,J=process.platform,Q){if(J!=="win32"||!iL(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function DV($){if($.length===0)return;let[J,...Q]=$,Z=J.replace(/\\/g,"/").toLowerCase(),W=Z.split("/").at(-1)??Z;if(W==="env")return DV(Q);if(W==="bash"||W==="sh"||W==="zsh")return[W,...Q];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...Q]:[W,...Q];return $}function aL($){let J=rL($);if(J&&J.length>0)return[...DV(J)??J,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return GV(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function sL($){let J={};for(let Q of D$($)){if(!Q.hookEventName)continue;let Z=Q.hookEventName,W=J[Z]??[];W.push(aL(Q.path)),J[Z]=W}return J}async function oL($){let J;for(let Q of $.commands){let Z=Q.join(" ");try{let W=await FV($.payload,{command:Q,cwd:$.cwd,env:P7(process.env),detached:!1,timeoutMs:$.timeoutMs});if(W?.timedOut){v5($.logger,`hook command timed out: ${Z}`);continue}if(W?.parseError){v5($.logger,`hook command returned invalid JSON control output: ${Z} (${W.parseError})`);continue}J=uL(J,dL(W?.parsedJson))}catch(W){v5($.logger,`hook command failed: ${Z}`,W)}}return J}function Q2($){for(let J of $.commands){let Q=J.join(" ");FV($.payload,{command:J,cwd:$.cwd,env:P7(process.env),detached:!0}).catch((Z)=>{v5($.logger,`hook command failed: ${Q}`,Z)})}}function U$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function q7($,J){return{...U$($.snapshot),userMessage:J}}function UV($){return{...U$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function RV($){return{...U$($.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 zV($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function tL($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}function F8($){let J={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(Z)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...Z})}
192
- `,f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cL(AV(),"hooks.jsonl");AV(f),mL(f,W,"utf8")};return{beforeRun:async(Z)=>{let W=q7(Z,"");Q({...z0(W,J),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Z)=>{let W=UV(Z);Q({...z0(W,J),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:c5(W.call.input)}});return},afterTool:async(Z)=>{let W=RV(Z);Q({...z0(W,J),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:c5(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:Z,result:W})=>{let j=U$(Z);if(W.status==="completed"){Q({...z0(j,J),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||M7(W.error?.message)){Q({...z0(j,J),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)Q({...z0(j,J),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(Z)=>{if(Z.type!=="message-added"||Z.message.role!=="user")return;let W=q7({snapshot:Z.snapshot},zV(Z.message.content));Q({...z0(W,J),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function A6($){let J=sL($.workspacePath);if(!Object.values(J).some((B)=>B.length>0))return;let Z=async(B,A)=>{let K=J[A]??[];if(K.length===0)return;Q2({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...z0(B,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...z0(B,$),hookName:A,taskStart:{taskMetadata:{}}}})},W=async(B)=>{let A=J.prompt_submit??[];if(A.length>0)Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},j=async(B)=>{let A=J.tool_call??[];if(A.length===0)return;return oL({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...z0(B,$),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:c5(B.call.input)}}})},f=async(B)=>{let A=J.tool_result??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:c5(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},X=async(B)=>{let A=J.agent_end??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},Y=async(B)=>{let A=J.agent_error??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},V=async(B)=>{if(M7(B.reason)){let K=J.agent_abort??[];if(K.length>0)Q2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let A=J.session_shutdown??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"session_shutdown",reason:B.reason}})},H={};if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0||(J.prompt_submit?.length??0)>0){if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0)H.beforeRun=async(B)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Z(U$(B.snapshot),A);return};if((J.prompt_submit?.length??0)>0)H.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await W(q7({snapshot:B.snapshot},zV(B.message.content)))}}if((J.tool_call?.length??0)>0)H.beforeTool=async(B)=>{let A=await j(UV(B));return tL(A)};if((J.tool_result?.length??0)>0)H.afterTool=async(B)=>{await f(RV(B));return};if((J.agent_end?.length??0)>0)H.afterRun=async({snapshot:B,result:A})=>{if(A.status!=="completed")return;await X({...U$(B),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((J.agent_error?.length??0)>0||(J.agent_abort?.length??0)>0||(J.session_shutdown?.length??0)>0){let B=H.afterRun;H.afterRun=async(A)=>{await B?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||M7(G.error?.message)){await V({...U$(K),reason:G.error?.message});return}if(G.error)await Y({...U$(K),iteration:G.iterations,error:G.error})}}return H}function D8($){return K8("core.hook_config_files",A6($))}function Z2($,J){let Q=$.map((Z)=>Z[J]).filter((Z)=>typeof Z==="function");if(Q.length===0)return;return async(Z)=>{let W;for(let j of Q){let f=await j(Z);if(!f||typeof f!=="object")continue;let X=f;W={...W??{},...X,stop:W?.stop===!0||X.stop===!0?!0:X.stop,options:W?.options||X.options?{...W?.options??{},...X.options??{}}:void 0}}return W}}function W2($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return;return{beforeRun:Z2(J,"beforeRun"),afterRun:Z2(J,"afterRun"),beforeModel:Z2(J,"beforeModel"),afterModel:Z2(J,"afterModel"),beforeTool:Z2(J,"beforeTool"),afterTool:Z2(J,"afterTool"),onEvent:Z2(J,"onEvent")}}var LV={};w(LV,{normalizeRuntimeCapabilities:()=>L0});function L0(...$){let J,Q;for(let W of $){if(!W)continue;if(W.toolExecutors)J={...J??{},...W.toolExecutors};if(W.requestToolApproval)Q=W.requestToolApproval}let Z=J&&Object.keys(J).length>0;if(!Z&&!Q)return;return{...Z?{toolExecutors:J}:{},...Q?{requestToolApproval:Q}:{}}}var SV={};w(SV,{toProviderConfig:()=>d0,emptyStoredProviderSettings:()=>L$,StoredProviderSettingsSchema:()=>L8,StoredProviderSettingsEntrySchema:()=>HQ,ProviderSettingsSchemaTyped:()=>z8});import{z as z$}from"zod";var wV={};w(wV,{toProviderConfig:()=>d0,safeParseSettings:()=>VQ,safeCreateProviderConfig:()=>I7,parseSettings:()=>YQ,normalizeProviderId:()=>R8,isBuiltInProviderId:()=>h7,createProviderConfig:()=>k7,SapSettingsSchema:()=>jQ,ReasoningSettingsSchema:()=>JQ,ProviderSettingsSchema:()=>R$,ProviderProtocolSchema:()=>t5,ProviderIdSchema:()=>U6,ProviderClientSchema:()=>e5,OcaSettingsSchema:()=>fQ,ModelCatalogSettingsSchema:()=>XQ,GcpSettingsSchema:()=>ZQ,BUILT_IN_PROVIDER_IDS:()=>b7,BUILT_IN_PROVIDER:()=>D6,AzureSettingsSchema:()=>WQ,AwsSettingsSchema:()=>QQ,AuthSettingsSchema:()=>$Q});import*as u0 from"@cline/llms";import{z as N}from"zod";var NV={};w(NV,{resolveProviderConfig:()=>F6,getProviderConfig:()=>o5,getLiveModelsCatalog:()=>U8,clearPublicModelsCatalogCache:()=>z_,clearPrivateModelsCatalogCache:()=>E7,clearLiveModelsCatalogCache:()=>y7,OPENAI_COMPATIBLE_PROVIDERS:()=>G6,DEFAULT_MODELS_CATALOG_URL:()=>i5});import*as H0 from"@cline/llms";function N7($){if(!Array.isArray($))return[];return $.map((J)=>{if(typeof J==="string")return J.trim();if(J&&typeof J==="object"){let Q=J;for(let Z of[Q.id,Q.name,Q.model])if(typeof Z==="string"&&Z.trim())return Z.trim()}return""}).filter((J)=>J.length>0)}function eL($,J){let Q=N7($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let Z=$,W=N7(Z.data??Z.models);if(W.length>0)return W;if(Z.models&&typeof Z.models==="object"&&!Array.isArray(Z.models)){let f=Object.keys(Z.models).filter((X)=>X.trim().length>0);if(f.length>0)return f}let j=Z.providers?.[J];if(j&&typeof j==="object"){let X=N7(j.models??j);if(X.length>0)return X}return[]}async function u5($,J){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return eL(await Q.json(),J)}function _V($){return $.replace(/\/+$/,"")}function d5($,J,Q){let Z=Q?.trim();if(!Z)return;let W=$?.trim();if(!W||!J?.trim())return Z;try{let j=new URL(Z),f=new URL(J),X=new URL(W);if(j.origin!==f.origin)return Z;let Y=_V(f.pathname),V=_V(X.pathname);if(Y&&j.pathname.startsWith(`${Y}/`)){let H=j.pathname.slice(Y.length);X.pathname=`${V}${H}`}else X.pathname=j.pathname;return X.search=j.search,X.hash=j.hash,X.toString()}catch{return Z}}function $_($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{...Q}]))}function J_($){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 Q_=Object.values(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:$_($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),TV=Object.fromEntries(Q_.map(($)=>[$.id,$]));function Z_($){return TV[$]}function W_(){return Object.fromEntries(Object.entries(TV).filter(([,$])=>J_($)))}function MV($=[]){let J=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return J.length>0?J:void 0}var i5="https://models.dev/api.json",j_=600000,qV=300000,f_=5000,r5=new Map,K6=new Map,w7=new Map,l5=new Map;async function X_(){return H0.getGeneratedProviderModels()}async function Y_($,J={},Q={},Z={},W={},j={}){let f=await X_(),X=H0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((B)=>f[B]??{})),V=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(W).length>0;if(V&&H)return H0.sortModelsByReleaseDate({...W,...j});if($==="openai-codex")return H0.sortModelsByReleaseDate({...J,...H0.filterOpenAICodexModels(Q),...W,...j});return H0.sortModelsByReleaseDate({...Y,...J,...Q,...Z,...W,...j})}function V_($,J){let Q=H0.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((Z)=>J[Z]??{}))}function n5($){let J=$?.trim();return J&&J.length>0?J:""}function C7($){let J=$.apiKey?.trim()||$.accessToken?.trim();return J&&J.length>0?J:void 0}function H_($){let J=2166136261;for(let Q=0;Q<$.length;Q+=1)J^=$.charCodeAt(Q),J+=(J<<1)+(J<<4)+(J<<7)+(J<<8)+(J<<24);return(J>>>0).toString(16)}function B_($,J){return`${$}:${n5(J.baseUrl)}:${H_(C7(J)??"")}`}async function a5($,J,Q=f_){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await fetch($,{...J,signal:Z.signal})}finally{clearTimeout(W)}}function j2($,J,Q){if(Q&&!$.includes(J))$.push(J)}function s5($,J){let Q=["streaming","tools"];return j2(Q,"images",Boolean(J.supportsImages)),j2(Q,"prompt-cache",Boolean(J.supportsPromptCache)),j2(Q,"reasoning",Boolean(J.supportsReasoning)),{id:$,name:J.name??$,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxTokens:J.maxTokens,capabilities:Q,releaseDate:J.releaseDate,status:"active"}}async function A_($,J){let Q=await a5("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=f.supported_features??[];j[X]=s5(X,{name:X,contextWindow:f.context_length,maxInputTokens:f.context_length,maxTokens:f.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return j}function OV($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let J=Number($);return Number.isFinite(J)?J:void 0}return}async function K_($,J){let Q=await a5("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":J}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;j[X]=s5(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function G_($,J){let Z=`${(n5($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,W=await a5(Z,{method:"GET",headers:{Authorization:`Bearer ${J}`,accept:"application/json"}});if(!W.ok)throw Error(`Poolside model refresh failed: HTTP ${W.status}`);let f=(await W.json())?.data??[],X={};for(let Y of f){let V=Y.id?.trim();if(!V)continue;let H=Y.supported_features??[],B=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];j2(K,"tools",H.includes("tools")),j2(K,"reasoning",H.includes("reasoning")),j2(K,"temperature",B.includes("temperature")),j2(K,"images",A.includes("image"));let G={input:OV(Y.pricing?.prompt),output:OV(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function F_($){let J=n5($);if(!J)return"http://localhost:4000";return J.endsWith("/v1")?J.slice(0,-3):J}async function D_($,J){let Z=`${F_($.baseUrl)}/v1/model/info`,W=async(V)=>a5(Z,{method:"GET",headers:{accept:"application/json",...V}}),j=await W({"x-litellm-api-key":J});if(!j.ok)j=await W({Authorization:`Bearer ${J}`});if(!j.ok)throw Error(`LiteLLM model refresh failed: HTTP ${j.status}`);let X=(await j.json())?.data??[],Y={};for(let V of X){let H=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||H;if(!A)continue;let K=V.model_info,G=s5(A,{name:H??A,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(Y[A]=G,H)Y[H]={...G,id:H,name:H}}return Y}var PV={baseten:A_,hicap:K_,litellm:D_,poolside:G_},S7=new Map,p5=new Map;function U_($,J){return`${$}:${n5(J.baseUrl)}`}async function R_($,J,Q){let Z=H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=d5(Q.baseUrl,Z?.provider.baseUrl,Z?.provider.modelsSourceUrl);if(!W)return{};let j=J?.cacheTtlMs??qV,f=U_($,Q),X=Date.now(),Y=S7.get(f);if(Y&&Y.expiresAt>X)return Y.data;let V=p5.get(f);if(V)return V;let H=u5(W,$).then((B)=>{let A=Object.fromEntries(B.map((K)=>[K,s5(K,{name:K})]));return S7.set(f,{data:A,expiresAt:X+j}),A}).finally(()=>{p5.delete(f)});return p5.set(f,H),H}function z_(){S7.clear(),p5.clear()}async function L_($,J){let Q=C7(J);if(!Q)return{};let Z=PV[$];if(!Z)return{};return Z(J,Q)}function __($,J,Q){if(!Q)return!1;if(!PV[$])return!1;if(J?.loadPrivateOnAuth===!1)return!1;return Boolean(C7(Q))}async function O_($,J,Q){let Z=J?.cacheTtlMs??qV,W=B_($,Q),j=Date.now(),f=w7.get(W);if(f&&f.expiresAt>j)return f.data;let X=l5.get(W);if(X)return X;let Y=L_($,Q).then((V)=>{return w7.set(W,{data:V,expiresAt:j+Z}),V}).finally(()=>{l5.delete(W)});return l5.set(W,Y),Y}async function T_($){return H0.fetchModelsDevProviderModels($,globalThis.fetch)}async function U8($={}){let J=$.url??i5,Q=$.cacheTtlMs??j_,Z=Date.now(),W=r5.get(J);if(W&&W.expiresAt>Z)return W.data;let j=K6.get(J);if(j)return j;let f=T_(J).then((X)=>{return r5.set(J,{data:X,expiresAt:Z+Q}),X}).finally(()=>{K6.delete(J)});return K6.set(J,f),f}function y7($){if($){r5.delete($),K6.delete($);return}r5.clear(),K6.clear()}function E7(){w7.clear(),l5.clear()}function M_($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:MV(Q.capabilities)}]))}var G6=M_(W_());function o5($){let J=Z_($);if(!J)return;return{baseUrl:J.baseUrl||void 0,modelId:J.modelId,knownModels:J.knownModels,capabilities:MV(J.capabilities)}}async function F6($,J,Q){let Z=o5($);if(!Z)return;try{let W=J?.loadLatestOnInit?await U8(J):void 0,j=W?V_($,W):{},f=Q&&__($,J,Q)?await O_($,J,Q):{},Y=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:Z.modelId,baseUrl:Z.baseUrl}:Q,V=Y?await R_($,J,Y).catch(()=>({})):{},H=await Y_($,Z.knownModels,j,f,V,Q?.knownModels);return{...Z,knownModels:H}}catch(W){if(J?.failOnError)throw W;return Z}}var D6=u0.BUILT_IN_PROVIDER,b7=u0.BUILT_IN_PROVIDER_IDS,h7=u0.isBuiltInProviderId,R8=u0.normalizeProviderId,U6=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),t5=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),e5=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),$Q=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),q_=N.enum(["none","low","medium","high","xhigh"]),JQ=N.object({enabled:N.boolean().optional(),effort:q_.optional(),budgetTokens:N.number().int().positive().optional()}),QQ=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),ZQ=N.object({projectId:N.string().optional(),region:N.string().optional()}),WQ=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),jQ=N.object({clientId:N.string().optional(),clientSecret:N.string().optional(),tokenUrl:N.string().url().optional(),resourceGroup:N.string().optional(),deploymentId:N.string().optional(),useOrchestrationMode:N.boolean().optional(),api:N.enum(["orchestration","foundation-models"]).optional(),defaultSettings:N.record(N.string(),N.unknown()).optional()}),fQ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),XQ=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),R$=N.object({provider:U6,apiKey:N.string().optional(),auth:$Q.optional(),model:N.string().optional(),protocol:t5.optional(),client:e5.optional(),routingProviderId:U6.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:JQ.optional(),aws:QQ.optional(),gcp:ZQ.optional(),azure:WQ.optional(),sap:jQ.optional(),oca:fQ.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:XQ.optional()});function YQ($){return R$.parse($)}function VQ($){return R$.safeParse($)}function P_($){return $.protocol==="openai-responses"||$.client==="openai"}function d0($,J={}){let Q=$.provider,Z=R8(Q),W=J.includeKnownModels!==!1,j=$.reasoning?.effort||"none",f=j==="none"?void 0:j,X=G6[Z],Y=Object.assign({},...u0.resolveProviderModelCatalogKeys(Z).map((R)=>u0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],H=l2(Z,$),B=$.baseUrl??(Z==="oca"?$.oca?.mode==="internal"?J5:Q5:X?.baseUrl),A=$.routingProviderId??(P_($)&&Z!==D6.OPENAI_NATIVE?D6.OPENAI_NATIVE:void 0),K=W?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:Q,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...W?{knownModels:K}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:B,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:f,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,D])=>D!==void 0))}function k7($){let J=YQ($);return d0(J)}function I7($){let J=VQ($);if(J.success)return{success:!0,config:d0(J.data)};return{success:!1,error:J.error}}var z8=R$;var HQ=z$.object({settings:R$,updatedAt:z$.string().datetime(),tokenSource:z$.enum(["manual","oauth","migration"]).default("manual")}),L8=z$.object({version:z$.literal(1),lastUsedProvider:z$.string().min(1).optional(),providers:z$.record(z$.string(),HQ)});function L$(){return{version:1,providers:{}}}W1();var bV={};w(bV,{InMemoryWorkspaceManager:()=>O8});import{upsertWorkspaceInfo as C_,WorkspaceManifestSchema as g7}from"@cline/shared";var EV={};w(EV,{normalizeWorkspacePath:()=>m1,generateWorkspaceInfoWithDiagnostics:()=>R6,generateWorkspaceInfo:()=>_8,buildWorkspaceMetadataWithInfo:()=>x7,buildWorkspaceMetadata:()=>z6});import{basename as N_,resolve as w_}from"node:path";import{performance as CV}from"node:perf_hooks";import{processWorkspaceInfo as yV}from"@cline/shared";import S_ from"simple-git";function m1($){return w_($)}async function _8($){return(await R6($)).info}function BQ($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function R6($){let J=m1($),Q={rootPath:J,hint:N_(J)},Z;try{let W=S_({baseDir:J});if(!await W.checkIsRepo())return{info:Q,vcsType:"none"};try{let f=await W.getRemotes(!0);if(f.length>0){let X=f.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});Q.associatedRemoteUrls=X}}catch(f){Z??=BQ(f)}try{let f=(await W.revparse(["HEAD"])).trim();if(f.length>0)Q.latestGitCommitHash=f}catch(f){Z??=BQ(f)}try{let f=(await W.branch()).current.trim();if(f.length>0)Q.latestGitBranchName=f}catch(f){Z??=BQ(f)}return{info:Q,vcsType:"git",error:Z}}catch(W){return{info:Q,vcsType:"none",error:BQ(W)}}}async function z6($){let J=await _8($);return yV(J)}async function x7($){let J=CV.now(),Q=await R6($),Z=CV.now()-J,W=Q.info;return{workspaceInfo:W,workspaceMetadata:yV(W),durationMs:Z,vcsType:Q.vcsType,initError:Q.error}}class O8{manifest;listeners=new Set;constructor($){this.manifest=g7.parse($??{workspaces:{}})}async addWorkspacePath($){let J=await _8($);return this.manifest=C_(this.manifest,J),this.emit({type:"workspace_added",workspace:J}),J}async switchWorkspace($){let J=m1($),Q=this.manifest.workspaces[J];if(Q)return this.manifest=g7.parse({...this.manifest,currentWorkspacePath:J}),this.emit({type:"workspace_switched",workspace:Q}),Q;let Z=await this.addWorkspacePath(J);return this.manifest=g7.parse({...this.manifest,currentWorkspacePath:Z.rootPath}),this.emit({type:"workspace_switched",workspace:Z}),Z}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let J=m1($);return this.manifest.workspaces[J]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let J of this.listeners)J($)}}O0();import{createHash as y_}from"node:crypto";var hV=new Set,kV=new Set;function E_($){return y_("sha256").update($).digest("hex")}function b_($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function IV($){if(!$.telemetry)return;let J=E_($.rootPath),Q=$.rootCount??1;if(!hV.has(J))hV.add(J),bJ($.telemetry,{root_count:Q,vcs_types:b_($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!kV.has(J)){kV.add(J);let Z=Error($.initError.message);Z.name=$.initError.errorType||"Error",hJ($.telemetry,Z,{fallback_to_single_root:!0,workspace_count:Q})}}function k_($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function I_($,J,Q){if(J.length>0)for(let j of J)Q?.log(j.message,{severity:"warn"});if($.length===0)return;let Z=$.slice(0,3).map(k_).join("; "),W=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${Z}${W}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Q?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function x_($,J){let Q=typeof $.thinking==="boolean",Z=typeof $.reasoningEffort==="string";if(!Q&&!Z)return J;return{...J??{},...Q?{enabled:$.thinking}:{},...Z?{effort:$.reasoningEffort}:{}}}function xV($,J){return h_($,J)}function g_($){let J=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;J+=1}return J}function m_($){let J={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||v_($.accessToken);if(J.originator="cline",J.session_id=$.sessionId,J["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)J["ChatGPT-Account-Id"]=Q;return J}function v_($){let J=$?.trim();if(!J)return;let Q=T0(J),Z=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let W=Q?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return}function c_($,J,Q,Z,W){let j=Q.getProviderSettings($.providerId),f=Z||j?.modelCatalog?{...Z??{},...j?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...j??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??j?.apiKey,baseUrl:$.baseUrl??j?.baseUrl,headers:$.providerId==="openai-codex"?m_({sessionId:J,configHeaders:$.headers,storedHeaders:j?.headers,accountId:j?.auth?.accountId,accessToken:$.apiKey??j?.auth?.accessToken??j?.apiKey}):$.headers??j?.headers,reasoning:x_($,j?.reasoning),modelCatalog:f},V={...d0(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let B=$.fetch??V.fetch??W;if(B)V.fetch=B;return V}async function gV($){let{input:J,sessionId:Q,providerSettingsManager:Z,defaultTelemetry:W,defaultCapabilities:j,defaultToolPolicies:f,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:H,createSpawnTool:B,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=G$(J.config),{modelCatalogDefaults:D,userInstructionService:U,configExtensions:F,onTeamRestored:O,...T}=A??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:z,workspaceMetadata:P,durationMs:S,vcsType:b,initError:u}=await x7(R),o=L?.extensionContext,J0={...o??{},workspace:{...z,...o?.workspace??{}},session:{...o?.session??{},sessionId:Q},logger:o?.logger??L?.logger,telemetry:o?.telemetry??L?.telemetry??W};IV({telemetry:J0.telemetry,rootPath:z.rootPath,workspaceInfo:z,rootCount:1,vcsType:b,durationMs:S,initError:u,featureFlagEnabled:!0});let t=D8({cwd:J.config.cwd,workspacePath:R,rootSessionId:Q,logger:L?.logger,workspaceInfo:z}),$1=bY(L?.hooks)?void 0:F8({rootSessionId:Q,workspacePath:R,workspaceInfo:z}),b$=W2([L?.hooks,$1]),n;if(xV(F,"plugins"))try{n=await A8({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:J.config.cwd,onEvent:Y,providerId:J.config.providerId,modelId:J.config.modelId,workspaceInfo:z,session:J0.session,client:J0.client,user:J0.user,logger:J0.logger,telemetry:J0.telemetry,automation:J0.automation}),I_(n.failures,n.warnings,L?.logger)}catch(x2){let s9=x2 instanceof Error?x2.message:String(x2);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${s9})`)}let C=J7(t?[t]:void 0,J7(L?.extensions,_5(n?.extensions))),F0=xV(F,"plugins")?$2(n?.pluginPaths??[]):void 0,f0={...J.config,...L??{},sessionId:Q,hooks:b$,extensions:C,extensionContext:J0,telemetry:J0.telemetry},w0=c_(f0,Q,Z,D,X),k2=W2([f0.hooks,f0.checkpoint?.enabled===!0?BV({cwd:f0.cwd,sessionId:Q,logger:f0.logger,createCheckpoint:f0.checkpoint?.createCheckpoint,initialRunCount:g_(J.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),T1={...f0,providerConfig:w0,workspaceMetadata:P,hooks:k2},Y1=J.toolPolicies??f0.toolPolicies??f,Y4=L0(j,J.capabilities),I2=Y4?.requestToolApproval,SJ=Y4?.toolExecutors,M1=H?.(T1),CJ=new O8({currentWorkspacePath:z.rootPath,workspaces:{[z.rootPath]:z}});return{effectiveInput:J,config:T1,providerConfig:w0,workspaceMetadata:P,workspaceInfo:z,extensions:C,hooks:k2,toolPolicies:Y1,requestToolApproval:I2,pluginSandboxShutdown:n?.shutdown,runtimeBuilderInput:{config:T1,hooks:k2,extensions:C,onTeamEvent:V,createSpawnTool:B,onTeamRestored:O,onSubAgentEvent:M1?.onSubAgentEvent,onSubAgentStart:M1?.onSubAgentStart,onSubAgentEnd:M1?.onSubAgentEnd,userInstructionService:U,pluginSkillDirectories:F0,configExtensions:F,toolExecutors:SJ,toolPolicies:Y1,workspaceManager:CJ,logger:T1.logger,telemetry:T1.telemetry,requestToolApproval:I2}}}import{existsSync as KQ,mkdirSync as u_,readdirSync as d_,rmdirSync as l_,rmSync as p_,unlinkSync as r_}from"node:fs";import{dirname as mV,join as AQ}from"node:path";function e(){return new Date().toISOString()}function L6($){if(!$||!KQ($))return;try{r_($)}catch{}}function i_($){let J=W8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:`${J.agentId}__${J.teamTaskId}`};let Q=o4($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class m7{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return AQ(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let J=this.sessionArtifactsDir($);if(!KQ(J))u_(J,{recursive:!0});return J}sessionMessagesPath($){return AQ(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,J=!1){let Q=J?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return AQ(Q,`${$}.json`)}removeSessionDirIfEmpty($){let J=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(J.startsWith(Q)&&J!==Q){if(!KQ(J)){J=mV(J);continue}try{if(d_(J).length>0)break;l_(J)}catch{break}J=mV(J)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!KQ($))return;try{p_($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,J,Q){let{rootSessionId:Z,fileStem:W}=i_($),j=this.sessionArtifactsDir(Z);return{messagesPath:AQ(j,`${W}.messages.json`)}}}import{resolveDocumentsExtensionPath as n_}from"@cline/shared/storage";O0();function vV($,J,Q,Z,W){if(Q)IJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});else kJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});a_($.telemetry,{workspacePath:Z})}function a_($,J){let Q=n_("Hooks"),Z=D$(J.workspacePath),W=new Map;for(let j of Z){let f=j.hookEventName??"unknown",X=W.get(f)??{global:0,workspace:0};if(j.path===Q||j.path.startsWith(`${Q}/`))X.global+=1;else X.workspace+=1;W.set(f,X)}for(let[j,f]of W.entries())rJ($,j,f.global,f.workspace)}function cV($,J){for(let Q of J.mentions)lJ($,Q,J.matchedFiles.includes(Q)?1:0,"file",!J.matchedFiles.includes(Q));for(let Q of J.matchedFiles)uJ($,"file",Q.length);for(let Q of J.ignoredMentions)dJ($,"file","not_found",Q)}var iG={};w(iG,{ProviderSettingsManager:()=>_1});import{chmodSync as aG,existsSync as Nj,mkdirSync as Xb,readFileSync as Yb,writeFileSync as Vb}from"node:fs";import{basename as sG,dirname as wj}from"node:path";import{resolveProviderSettingsPath as Hb}from"@cline/shared/storage";var M={};w(M,{writeHubDiscovery:()=>dQ,writeGlobalSettings:()=>k1,withHubStartupLock:()=>lQ,verifyHubConnection:()=>G1,updateMcpServerOAuthState:()=>H2,updateLocalProvider:()=>I9,uninstallPlugin:()=>t3,truncateNotificationBody:()=>UJ,toggleDisabledTool:()=>z5,toTeamProgressLifecycleEvent:()=>u8,toProviderConfig:()=>d0,toHubStatusUrl:()=>PW,toHubHealthUrl:()=>pQ,toHookConfigFileName:()=>B6,syncPluginMcpServersToSettings:()=>d3,summarizeUsageFromMessages:()=>f8,stopLocalHubServerGracefully:()=>gW,startLocalOAuthServer:()=>J1,startHubWebSocketServer:()=>C2,startHubServer:()=>dK,startClineDeviceAuth:()=>WZ,splitCoreSessionConfig:()=>u6,spawnDetachedHubServerWithRetry:()=>h8,spawnDetachedHubServer:()=>EW,setTelemetryOptOutGlobally:()=>EX,setMcpServerDisabled:()=>Y2,setDisabledTools:()=>IZ,setDisabledPlugin:()=>gX,setAutoUpdateEnabledGlobally:()=>hX,sendHubCommand:()=>uA,saveProviderOAuthCredentials:()=>x$,saveLocalProviderSettings:()=>fj,saveLocalProviderOAuthCredentials:()=>Hj,sanitizeSessionToken:()=>a$,safeParseSettings:()=>VQ,safeCreateProviderConfig:()=>I7,runSubprocessEvent:()=>r8,runHook:()=>n8,reviveTeamStateDates:()=>P5,restartLocalHubIfIdleAfterStartupTimeout:()=>sQ,resolveWorkspaceHubOwnerContext:()=>NB,resolveWorkflowsConfigSearchPaths:()=>y6,resolveSkillsConfigSearchPaths:()=>S6,resolveSharedHubOwnerContext:()=>E0,resolveSessionBackend:()=>W3,resolveRulesConfigSearchPaths:()=>C6,resolveProviderConfig:()=>F6,resolveProviderApiKeyFromSettings:()=>HZ,resolveProductionHubOwnerContext:()=>n0,resolvePluginSkillDirectoriesFromPaths:()=>$2,resolvePluginConfigSearchPaths:()=>X6,resolveMcpServerRegistrations:()=>A1,resolveLocalClineAuthToken:()=>Aj,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>l1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>uQ,resolveHooksConfigSearchPaths:()=>V6,resolveDisabledToolNames:()=>B1,resolveDisabledPluginPaths:()=>p4,resolveDefaultMcpSettingsPath:()=>B0,resolveDefaultHubPort:()=>b8,resolveDefaultHubPathname:()=>yW,resolveDefaultHubHost:()=>CW,resolveCoreSelectedToolIds:()=>w5,resolveCoreDistinctId:()=>b0,resolveCompatibleLocalHubUrl:()=>QJ,resolveClineDir:()=>TB,resolveClineDataDir:()=>R2,resolveAndLoadAgentPlugins:()=>A8,resolveAgentPluginPaths:()=>e$,requestHubShutdown:()=>JJ,requestDesktopToolApproval:()=>m3,removePluginMcpServersFromSettings:()=>MJ,rememberRecoverableLocalHubUrl:()=>P$,registerRemoteConfigSessionBlobUpload:()=>_9,registerMcpServersFromSettingsFile:()=>B2,registerDisposable:()=>Zb,refreshProviderModelsFromSource:()=>Xj,refreshOpenAICodexToken:()=>$5,refreshOcaToken:()=>W5,refreshClineToken:()=>tJ,readSessionCheckpointHistory:()=>RJ,readRemoteConfigSessionBlobUploadMetadata:()=>C3,readHubDiscovery:()=>A0,readGlobalSettings:()=>M0,readBearerToken:()=>F9,probeHubServer:()=>p1,probeHubConnection:()=>cA,prewarmFileIndex:()=>A5,prewarmDetachedHubServer:()=>iQ,prepareRemoteConfigCoreIntegration:()=>E3,parseWorkflowConfigFromMarkdown:()=>w6,parseUserCommandEnvelope:()=>Qb,parseSkillConfigFromMarkdown:()=>P6,parseSettings:()=>YQ,parseRuleConfigFromMarkdown:()=>N6,parseHookEventPayload:()=>i8,parseConfiguredAgentConfig:()=>fJ,normalizeWorkspacePath:()=>m1,normalizeUserInput:()=>Jb,normalizeSdkError:()=>$b,normalizeRuntimeCapabilities:()=>L0,normalizeProviderId:()=>R8,normalizeOAuthProvider:()=>Yj,normalizeHubWebSocketUrl:()=>N$,noopBasicLogger:()=>eE,migrateLegacyProviderSettings:()=>PJ,mergeRulesForSystemPrompt:()=>N8,mergeAgentHooks:()=>W2,makeTeamTaskSubSessionId:()=>s4,makeSubSessionId:()=>Z8,loginOpenAICodex:()=>G4,loginOcaOAuth:()=>U4,loginLocalProvider:()=>Vj,loginClineOAuth:()=>A4,loginAndSaveProviderOAuthCredentials:()=>z4,loginAndSaveLocalProviderOAuthCredentials:()=>Bj,loadOpenTelemetryAdapter:()=>mE,loadMcpSettingsFile:()=>X2,loadLlmsConfigFromFile:()=>Mj,loadConfiguredAgentConfigs:()=>m8,loadAgentPluginsFromPathsWithDiagnostics:()=>t$,loadAgentPluginsFromPaths:()=>b5,loadAgentPluginFromPath:()=>j6,listSessionHistoryFromBackend:()=>OW,listPluginToolsWithDiagnostics:()=>bQ,listPluginTools:()=>v6,listMcpServerOAuthStatuses:()=>g6,listLocalProviders:()=>Wj,listHookConfigFiles:()=>D$,isToolDisabledGlobally:()=>kX,isTelemetryOptedOutGlobally:()=>R5,isSessionNotFoundError:()=>d1,isRuleEnabled:()=>TQ,isPluginDisabledGlobally:()=>xX,isOAuthProvider:()=>I$,isHubReconnectableTransportError:()=>IW,isHubCommandTimeoutError:()=>aQ,isDiscoveryFilePresent:()=>qB,isClineAccountActionRequest:()=>GQ,isBuiltInProviderId:()=>h7,isAutoUpdateEnabledGlobally:()=>bX,identifyAccount:()=>S1,hasMcpSettingsFile:()=>c1,getValidOpenAICodexCredentials:()=>F4,getValidOcaCredentials:()=>R4,getValidClineCredentials:()=>K4,getProviderOAuthCredentialsFromSettings:()=>L4,getProviderConfigFields:()=>Kj,getProviderConfig:()=>o5,getProviderAuthStorageId:()=>VZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>l2,getMcpServerOAuthState:()=>V2,getLocalProviderModels:()=>jj,getLiveModelsCatalog:()=>U8,getFileIndex:()=>b1,getCurrentContextSize:()=>j7,getCoreHeadlessToolNames:()=>a4,getCoreDefaultEnabledToolIds:()=>N5,getCoreBuiltinToolCatalog:()=>i$,getCoreAcpToolNames:()=>S5,getClineDefaultSystemPrompt:()=>cE,generateWorkspaceInfoWithDiagnostics:()=>R6,generateWorkspaceInfo:()=>_8,formatRulesForSystemPrompt:()=>P8,formatProviderOAuthApiKey:()=>BZ,formatDisplayUserInput:()=>tE,filterExtensionToolRegistrations:()=>_5,filterDisabledTools:()=>I1,filterDisabledPluginPaths:()=>L5,fetchClineRecommendedModels:()=>Oj,executeClineAccountAction:()=>FQ,ensureHubWebSocketServer:()=>D9,ensureHubServer:()=>lK,ensureDetachedHubServer:()=>bB,ensureCustomProvidersLoaded:()=>b9,ensureCompatibleLocalHubUrl:()=>_2,enrichPromptWithMentions:()=>a2,emptyWorkspaceManifest:()=>aE,emptyStoredProviderSettings:()=>L$,discoverPluginModulePaths:()=>Y6,disablePluginMcpServersInSettings:()=>l3,deriveSubsessionStatus:()=>t4,deleteLocalProvider:()=>x9,defineLlmsConfig:()=>Tj,createWorkflowsConfigDefinition:()=>h6,createUserInstructionConfigService:()=>_$,createToolPoliciesWithPreset:()=>G5,createTool:()=>nE,createTeamName:()=>M9,createSubprocessHooks:()=>j9,createSpawnAgentTool:()=>A$,createSkillsConfigDefinition:()=>E6,createSessionHost:()=>p8,createRuntimeHost:()=>p8,createRulesConfigDefinition:()=>b6,createRemoteConfigSessionMessagesArtifactUploader:()=>y3,createProviderConfig:()=>k7,createOpenTelemetryTelemetryService:()=>DJ,createOAuthClientCallbacks:()=>T8,createMcpTools:()=>y8,createLocalHubScheduleRuntimeHandlers:()=>U9,createLlmsSdk:()=>Pj,createInitialAccumulatedUsage:()=>G0,createInMemoryHubOwnerContext:()=>MB,createHubServerUrl:()=>j1,createHubAuthToken:()=>cQ,createHookConfigFileHooks:()=>A6,createHookConfigFileExtension:()=>D8,createHookAuditHooks:()=>F8,createDisabledMcpToolPolicy:()=>m6,createDisabledMcpToolPolicies:()=>EQ,createDelegatedAgentConfigProvider:()=>H$,createDelegatedAgent:()=>B$,createDefaultToolsWithPreset:()=>F5,createDefaultTools:()=>X$,createDefaultMcpServerClientFactory:()=>S8,createDefaultExecutors:()=>s2,createCoreSettingsService:()=>K2,createCoreSessionSnapshot:()=>F1,createContributionRegistry:()=>iE,createContextCompactionPrepareTurn:()=>P4,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,createConfiguredAgentTools:()=>v8,createClineTelemetryServiceMetadata:()=>rE,createClineTelemetryServiceConfig:()=>pE,createBuiltinTools:()=>n$,createAgentTeamsTools:()=>r$,createAgentRuntime:()=>fb,createAgentHooksExtension:()=>K8,connectToHub:()=>V9,completeClineDeviceAuth:()=>jZ,clearPrivateModelsCatalogCache:()=>E7,clearLiveModelsCatalogCache:()=>y7,clearHubDiscovery:()=>y0,captureWorkspacePathResolved:()=>rj,captureWorkspaceInitialized:()=>bJ,captureWorkspaceInitError:()=>hJ,captureToolUsage:()=>mJ,captureTokenUsage:()=>xJ,captureTaskRestarted:()=>IJ,captureTaskCreated:()=>kJ,captureTaskCompleted:()=>V4,captureSubagentExecution:()=>B4,captureSkillUsed:()=>vJ,captureSdkError:()=>lE,captureProviderConfigured:()=>ij,captureProviderApiError:()=>H4,captureModeSwitch:()=>gJ,captureMentionUsed:()=>uJ,captureMentionSearchResults:()=>lJ,captureMentionFailed:()=>dJ,captureHookDiscovery:()=>rJ,captureExtensionActivated:()=>pj,captureDiffEditFailure:()=>cJ,captureConversationTurnEvent:()=>g2,captureCompactionSkipped:()=>nJ,captureCompactionExecuted:()=>iJ,captureAuthSucceeded:()=>N1,captureAuthStarted:()=>P1,captureAuthLoggedOut:()=>e1,captureAuthFailed:()=>w1,captureAgentTeamCreated:()=>pJ,captureAgentCreated:()=>$$,buildWorkspaceMetadata:()=>z6,buildTeamProgressSummary:()=>c8,buildSdkErrorProperties:()=>uE,buildRemoteConfigSessionBlobUploadMetadata:()=>z9,buildDelegatedAgentConfig:()=>l$,buildConfiguredAgentToolName:()=>XJ,buildConfiguredAgentToolDescriptors:()=>YJ,bootstrapAgentTeams:()=>Q8,authorizeMcpServerOAuth:()=>wQ,addLocalProvider:()=>Zj,accumulateUsageTotals:()=>V0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q6,UnifiedConfigFileWatcher:()=>f2,ToolPresets:()=>c0,TelemetryService:()=>o8,TelemetryLoggerSink:()=>FJ,TEAM_TOOL_NAMES:()=>J8,SubprocessSandbox:()=>V8,StoredProviderSettingsSchema:()=>L8,StoredProviderSettingsEntrySchema:()=>HQ,SqliteTeamStore:()=>y2,SqliteSessionStore:()=>U1,SessionVersioningService:()=>y$,SessionVersioningError:()=>k0,SessionSource:()=>U0,SessionNotFoundError:()=>u1,SapSettingsSchema:()=>jQ,SKILLS_CONFIG_DIRECTORY_NAME:()=>M6,SESSION_STATUSES:()=>e4,SESSION_NOT_FOUND_ERROR_CODE:()=>G2,SDK_ERROR_TELEMETRY_EVENT:()=>Wb,RpcClineAccountService:()=>O6,RemoteRuntimeHost:()=>x8,ReasoningSettingsSchema:()=>JQ,RULES_CONFIG_DIRECTORY_NAME:()=>OQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>L9,ProviderSettingsSchema:()=>R$,ProviderSettingsManager:()=>_1,ProviderProtocolSchema:()=>t5,ProviderIdSchema:()=>U6,ProviderClientSchema:()=>e5,OpenTelemetryProvider:()=>t8,OcaSettingsSchema:()=>fQ,OPENAI_COMPATIBLE_PROVIDERS:()=>G6,NodeHubClient:()=>f1,NoOpFeatureFlagsProvider:()=>q2,NativeHubTransportAdapter:()=>OJ,ModelCatalogSettingsSchema:()=>XQ,LocalRuntimeHost:()=>L1,Llms:()=>vE,InMemoryWorkspaceManager:()=>O8,InMemoryMcpManager:()=>A2,HubUIClient:()=>K3,HubTransportError:()=>q0,HubSessionClient:()=>A3,HubServerTransport:()=>J4,HubScheduleService:()=>s8,HubScheduleCommandService:()=>a8,HubRuntimeHost:()=>r1,HubCommandError:()=>k8,HookEventPayloadSchema:()=>W9,HookEventNameSchema:()=>Z9,HookConfigFileName:()=>G8,HOOK_CONFIG_FILE_EVENT_MAP:()=>H6,HOOKS_CONFIG_DIRECTORY_NAME:()=>m5,GlobalSettingsSchema:()=>l4,GcpSettingsSchema:()=>ZQ,FileTeamPersistenceStore:()=>c9,FeatureFlagsService:()=>M2,FeatureFlagDefaultValue:()=>oE,FEATURE_FLAGS:()=>sE,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>i9,DefaultToolNames:()=>K0,DefaultRuntimeBuilder:()=>W4,DefaultLlmsSdk:()=>NJ,DEFAULT_MODELS_CATALOG_URL:()=>i5,DEFAULT_HUB_PORT:()=>wW,DEFAULT_HUB_PATHNAME:()=>SW,DEFAULT_HUB_HOST:()=>NW,CoreSettingsService:()=>O$,CoreSessionService:()=>z1,ContributionRegistry:()=>dE,ClineCore:()=>KJ,ClineAccountService:()=>_6,ChatViewStateSchema:()=>zj,ChatSummarySchema:()=>r9,ChatSessionStatusSchema:()=>d9,ChatSessionConfigSchema:()=>u9,ChatMessageSchema:()=>p9,ChatMessageRoleSchema:()=>l9,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>Lj,BrowserWebSocketHubAdapter:()=>_J,BUILT_IN_PROVIDER_IDS:()=>b7,BUILT_IN_PROVIDER:()=>D6,AzureSettingsSchema:()=>WQ,AwsSettingsSchema:()=>QQ,AuthSettingsSchema:()=>$Q,AgentTeamsRuntime:()=>T2,AgentTeam:()=>l8,Agent:()=>jb,ALL_DEFAULT_TOOL_NAMES:()=>W$});q(M,kn);import*as vE from"@cline/llms";import{buildClineSystemPrompt as cE,buildSdkErrorProperties as uE,ContributionRegistry as dE,captureSdkError as lE,createClineTelemetryServiceConfig as pE,createClineTelemetryServiceMetadata as rE,createContributionRegistry as iE,createTool as nE,emptyWorkspaceManifest as aE,FEATURE_FLAGS as sE,FeatureFlagDefaultValue as oE,formatDisplayUserInput as tE,noopBasicLogger as eE,normalizeSdkError as $b,normalizeUserInput as Jb,parseUserCommandEnvelope as Qb,registerDisposable as Zb,SDK_ERROR_TELEMETRY_EVENT as Wb}from"@cline/shared";import"@cline/shared/storage";var dV={};w(dV,{isClineAccountActionRequest:()=>GQ,executeClineAccountAction:()=>FQ,RpcClineAccountService:()=>O6,ClineAccountService:()=>_6});function s_($){if(typeof $!=="object"||$===null||!("error"in $))return;let J=$.error;return typeof J==="string"&&J.trim()?J:void 0}function uV($,J,Q){let Z=s_(Q);if(Z)return Z;let W=J.trim();if(W){let j=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class _6{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let J=$.apiBaseUrl.trim();if(!J)throw Error("apiBaseUrl is required");this.apiBaseUrl=J,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 J=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(J)}/balance`)}async fetchUsageTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/usages`)).items??[]}async fetchPaymentTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}`)}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}/balance`)}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(J,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(J)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let J=$?.trim();if(J)return J;let Z=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Z)return Z;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId($,J){let Q=J?.trim();if(Q)return Q;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(W)return W;let f=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!f?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return f}async request($,J){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let Z=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,j=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let f=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:J?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...Z??{}},body:J?.body!==void 0?JSON.stringify(J.body):void 0,signal:W.signal});if(f.status===204||J?.expectNoContent){if(!f.ok)throw Error(`Cline account request failed with status ${f.status}`);return}let X=await f.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!f.ok)throw Error(uV(f.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!f.ok)throw Error(uV(f.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(j)}}}function GQ($){return $.action==="clineAccount"}async function FQ($,J){switch($.operation){case"fetchMe":return J.fetchMe();case"fetchBalance":return J.fetchBalance($.userId);case"fetchUsageTransactions":return J.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return J.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return J.fetchUserOrganizations();case"fetchOrganizationBalance":return J.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return J.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await J.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return J.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class O6{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 J=$.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:J})}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:J,...$.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 lV={};w(lV,{createOAuthClientCallbacks:()=>T8});function T8($){return{onAuth:({url:J,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(J)).catch((Z)=>{$.onOpenUrlError?.({url:J,error:Z})})}catch(Z){$.onOpenUrlError?.({url:J,error:Z})}$.onOutput?.(J)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var EA={};w(EA,{ClineCore:()=>KJ});function pV($){if($===!0)return{};if(!$)return;return $}function rV($){if($==="user")return"global";return $}class v7{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let J=this.getService().ingestEvent($);return{event:J.event,duplicate:J.duplicate,matchedSpecIds:J.matchedSpecs.map((Q)=>Q.specId),queuedRuns:J.queuedRuns,suppressions:J.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function iV($){let{host:J}=$;return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||U0.CLI,interactive:!1,config:{providerId:R8(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:e_(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content),delivery:Z.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:t_(W)}},async abortSession(Q){return await J.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}function DQ($){let J=o_($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),Z=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),W=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!J&&!Q&&!Z&&!W&&!j)return $.context;return{...$.context??{},...Q?{client:Q}:{},...Z?{user:Z}:{},...W?{logger:W}:{},...j?{telemetry:j}:{},...J?{automation:J}:{}}}function o_($,J){if(!$)return;return{ingestEvent:(Q)=>{J.ingestEvent(Q)}}}function t_($){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((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function e_($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var xH={};w(xH,{createCoreSettingsService:()=>K2,CoreSettingsService:()=>O$});import{existsSync as hQ}from"node:fs";import{basename as hH,isAbsolute as PT,relative as NT}from"node:path";var YH={};w(YH,{resolveWorkflowsConfigSearchPaths:()=>y6,resolveSkillsConfigSearchPaths:()=>S6,resolveRulesConfigSearchPaths:()=>C6,parseWorkflowConfigFromMarkdown:()=>w6,parseSkillConfigFromMarkdown:()=>P6,parseRuleConfigFromMarkdown:()=>N6,createWorkflowsConfigDefinition:()=>h6,createUserInstructionConfigService:()=>_$,createSkillsConfigDefinition:()=>E6,createRulesConfigDefinition:()=>b6,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q6,UnifiedConfigFileWatcher:()=>f2,SKILLS_CONFIG_DIRECTORY_NAME:()=>M6,RULES_CONFIG_DIRECTORY_NAME:()=>OQ});import{createHash as $O}from"node:crypto";import{watch as JO}from"node:fs";import{readdir as QO,readFile as ZO}from"node:fs/promises";import{join as WO}from"node:path";function jO($){return $O("sha1").update($).digest("hex")}function sV($){return Boolean($&&typeof $==="object"&&"code"in $)}function nV($){return sV($)&&$.code==="ENOENT"}function aV($){return sV($)&&($.code==="EACCES"||$.code==="EPERM")}class f2{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($,J){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=J?.debounceMs??75,this.emitParseErrors=J?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let Z of Q.directories){let W=this.baseTypesByDirectory.get(Z);if(W)W.add(Q.type);else this.baseTypesByDirectory.set(Z,new Set([Q.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let J=this.definitionsByType.get($);if(!J)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(J)})}getSnapshot($){let J=this.recordsByType.get($);return new Map([...J?.entries()??[]].map(([Q,Z])=>[Q,{...Z}]))}getAllSnapshots(){let $=new Map;for(let[J,Q]of this.recordsByType.entries())$.set(J,new Map([...Q.entries()].map(([Z,W])=>[Z,{...W}])));return $}emit($){for(let J of this.listeners)J($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[J,Q]of this.watchersByDirectory.entries()){if($.has(J))continue;Q.close(),this.watchersByDirectory.delete(J)}this.watchedTypesByDirectory=$;for(let J of $.keys()){if(this.watchersByDirectory.has(J))continue;try{let Q=JO(J,()=>{let Z=this.watchedTypesByDirectory.get(J);if(!Z)return;for(let W of Z)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set(J,Q),Q.on("error",(Z)=>{let W=this.watchedTypesByDirectory.get(J);if(!W)return;for(let j of W)this.emit({kind:"error",type:j,error:Z,filePath:J})})}catch(Q){if(!nV(Q)&&!aV(Q)){let Z=$.get(J);if(!Z)continue;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:J})}}}}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 J of $){let Q=this.definitionsByType.get(J);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:J,discoveredDirectories:Q}=await this.loadDefinition($),Z=this.recordsByType.get($.type)??new Map;for(let[W,j]of Z.entries()){if(J.has(W))continue;this.emit({kind:"remove",type:$.type,id:W,filePath:j.filePath})}for(let[W,j]of J.entries()){let f=Z.get(W);if(f&&f.filePath===j.filePath&&f.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:W,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,J),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let J=new Map,Q=new Set;for(let Z of $.directories){Q.add(Z);let W=$.discoverFiles?await $.discoverFiles(Z):await this.readDirectoryFileCandidates(Z);for(let j of W){let{fileName:f,filePath:X}=j;if(Q.add(j.directoryPath),$.includeFile&&!$.includeFile(f,X))continue;try{let Y=await ZO(X,"utf8"),V={type:$.type,directoryPath:j.directoryPath,fileName:f,filePath:X,content:Y},H=$.parseFile(V),B=$.resolveId(H,V).trim();if(!B)continue;J.set(B,{type:$.type,id:B,item:H,filePath:X,fingerprint:jO(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:J,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[J,Q]of this.baseTypesByDirectory.entries())$.set(J,new Set(Q));for(let[J,Q]of this.discoveredDirectoriesByType.entries())for(let Z of Q){let W=$.get(Z);if(W)W.add(J);else $.set(Z,new Set([J]))}return $}async readDirectoryFileCandidates($){try{return(await QO($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:WO($,Q.name)})).sort((Q,Z)=>Q.fileName.localeCompare(Z.fileName))}catch(J){if(nV(J)||aV(J))return[];throw J}}}import{readdir as u7,readFile as fO,stat as c7}from"node:fs/promises";import{basename as v1,dirname as XO,extname as RQ,join as C0,resolve as T6}from"node:path";import{AGENTS_RULES_FILE_NAME as oV,RULES_CONFIG_DIRECTORY_NAME as OQ,resolveGlobalAgentsRulesPath as YO,resolveRulesConfigSearchPaths as VO,resolveSkillsConfigSearchPaths as HO,resolveWorkflowsConfigSearchPaths as BO,SKILLS_CONFIG_DIRECTORY_NAME as M6,WORKFLOWS_CONFIG_DIRECTORY_NAME as q6}from"@cline/shared/storage";import AO from"yaml";var UQ="SKILL.md",KO="managed.json",GO=new Set([".md",".markdown",".txt"]);function d7($){return $.trim().toLowerCase()}function M8($){let J=$;return J?.code==="ENOENT"||J?.code==="EACCES"||J?.code==="EPERM"||J?.code==="ELOOP"}function zQ($){return GO.has(RQ($).toLowerCase())}function tV($){let J=[],Q=new Set;for(let Z of $){let W=T6(Z);if(Q.has(W))continue;Q.add(W),J.push(Z)}return J}function FO($){let J=[...$?.directories??S6($?.workspacePath)];if($?.pluginSkillDirectories)J.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)J.push(...VV({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return tV(J)}async function l7($){try{let J=await u7($,{withFileTypes:!0}),Q=[];for(let Z of J){if(!Z.isDirectory())continue;let W=C0($,Z.name),j=C0(W,KO);try{let f=await fO(j,"utf8"),X=JSON.parse(f);if(X&&typeof X==="object")Q.push(W)}catch(f){if(M8(f))continue;if(f?.name==="SyntaxError")continue;throw f}}return Q.sort((Z,W)=>Z.localeCompare(W))}catch(J){if(M8(J))return[];throw J}}function p7($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q;try{let j=AO.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}catch(j){let f=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:f}}}function LQ($,J,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${J}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${J}' must be a string.`);let Z=$.trim();if(!Z&&Q)throw Error(`Frontmatter field '${J}' cannot be empty.`);return Z||void 0}function q8($,J){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${J}' must be a boolean.`);return $}function DO($,J){if(v1($.filePath).toLowerCase()!==oV.toLowerCase())return v1($.filePath,RQ($.filePath));if(J&&T6($.filePath)===T6(J,oV))return"Workspace AGENTS.md";if(T6($.filePath)===T6(YO()))return"Global AGENTS.md";return v1($.filePath,RQ($.filePath))}function P6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in skill file.");let X=LQ(Q.name,"name",!1)??J.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:LQ(Q.description,"description",!1),disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function N6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in rule file.");let f=LQ(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing rule name.");return{name:f,disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function w6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in workflow file.");let f=LQ(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing workflow name.");return{name:f,disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function S6($){return HO($)}function C6($){return VO($)}function y6($){return BO($)}async function eV($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>eV(C0(Z,M6))))).flat()}try{let J=await u7($,{withFileTypes:!0}),Q=[];for(let Z of J){if(Z.isFile()&&Z.name===UQ){Q.push({directoryPath:$,fileName:Z.name,filePath:C0($,Z.name)});continue}let W=C0($,Z.name);if(Z.isDirectory()||Z.isSymbolicLink()&&await c7(W).then((f)=>f.isDirectory()).catch((f)=>{if(M8(f))return!1;throw f}))Q.push({directoryPath:W,fileName:UQ,filePath:C0(W,UQ)})}return Q}catch(J){if(M8(J))return[];throw J}}async function _Q($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>_Q(C0(Z,"rules.md"))))).flat()}try{if((await c7($)).isFile())return[{directoryPath:XO($),fileName:v1($),filePath:$}]}catch(J){if(!M8(J))throw J}try{let Q=(await u7($,{withFileTypes:!0})).filter((W)=>W.isFile()&&zQ(W.name)).map((W)=>({directoryPath:$,fileName:W.name,filePath:C0($,W.name)})),Z=C0($,"AGENTS.md");try{if((await c7(Z)).isFile()){if(!Q.some((f)=>f.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:Z})}}catch{}return Q}catch(J){if(M8(J))return[];throw J}}async function UO($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>_Q(C0(Z,q6))))).flat()}return _Q($)}function E6($){let J=FO($),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?tV([...J,Q]):J,discoverFiles:eV,includeFile:(Z)=>Z===UQ,parseFile:(Z)=>P6(Z.content,v1(Z.directoryPath)),resolveId:(Z)=>d7(Z.name)}}function b6($){let J=$?.directories??C6($?.workspacePath),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...J,Q]:J,discoverFiles:_Q,includeFile:(Z,W)=>Z===".clinerules"||zQ(Z)||zQ(W),parseFile:(Z)=>N6(Z.content,DO(Z,$?.workspacePath)),resolveId:(Z)=>d7(Z.name)}}function h6($){let J=$?.directories??y6($?.workspacePath),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...J,Q]:J,discoverFiles:UO,includeFile:(Z)=>zQ(Z),parseFile:(Z)=>w6(Z.content,v1(Z.filePath,RQ(Z.filePath))),resolveId:(Z)=>d7(Z.name)}}function $H($){let J=[E6($?.skills),b6($?.rules),h6($?.workflows)];return new f2(J,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as JH}from"@cline/shared";function RO($,J){if($.description?.trim())return JH($.description,".");if(J==="workflow")return;return JH($.instructions,".")}function zO($){return $.disabled!==!0}function QH($,J){return[...$.getSnapshot(J).entries()].map(([Q,Z])=>({id:Q,record:Z})).filter(({record:Q})=>zO(Q.item)).map(({id:Q,record:Z})=>({id:Q,name:Z.item.name,instructions:Z.item.instructions,description:RO(Z.item,J),kind:J})).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function k6($){let J=new Map;for(let Q of[...QH($,"workflow"),...QH($,"skill")])if(!J.has(Q.name))J.set(Q.name,Q);return[...J.values()].sort((Q,Z)=>Q.name.localeCompare(Z.name))}function ZH($,J){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let Z=Q[1];if(!Z)return $;let W=Z.length+1,j=$.slice(W),f=k6(J).find((X)=>X.name===Z);return f?`${f.instructions}${j}`:$}var jH={};w(jH,{mergeRulesForSystemPrompt:()=>N8,loadRulesForSystemPromptFromWatcher:()=>r7,listEnabledRulesFromWatcher:()=>WH,isRuleEnabled:()=>TQ,formatRulesForSystemPrompt:()=>P8});function TQ($){return $.disabled!==!0}function P8($){if($.length===0)return"";return`
191
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse hook stdout JSON"}}}async function pL($,J){let Q=$.stdin;if(!Q)throw Error("hook command failed to create stdin");await new Promise((Z,W)=>{let j=!1,f=()=>{Q.off("error",Y),Q.off("finish",V),$.off("close",H)},X=(B)=>{if(j)return;if(j=!0,f(),B){let A=B.code;if(A==="EPIPE"||A==="ERR_STREAM_DESTROYED"){Z();return}W(B);return}Z()},Y=(B)=>X(B),V=()=>X(),H=()=>X();Q.on("error",Y),Q.once("finish",V),$.once("close",H);try{Q.end(J)}catch(B){X(B)}})}async function GV($,J){if(J.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await AV($,J)}catch(Q){let Z=nL(J.command,process.platform,Q);if(!Z)throw Q;return await AV($,{...J,command:Z})}}async function AV($,J){let Q=KV(J.command,{env:J.env,debugRole:"hook"}),Z=gL(Q[0],Q.slice(1),{cwd:J.cwd,env:P7(J.env),stdio:J.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:J.detached,windowsHide:!0}),W=new Promise((A)=>{Z.once("spawn",()=>A())}),j=new Promise((A,K)=>{Z.once("error",(G)=>K(G))}),f=JSON.stringify($);if(await Promise.race([W,j]),await pL(Z,f),J.detached){Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("hook command failed to create stdout/stderr");let X="",Y="",V=!1,H;Z.stdout.on("data",(A)=>{X+=A.toString()}),Z.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,Z.kill("SIGKILL")},J.timeoutMs);Z.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=lL(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,j])}function rL($){try{let Q=vL($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!Q?.startsWith("#!"))return;let Z=Q.slice(2).trim();if(!Z)return;let W=Z.split(/\s+/).filter(Boolean);return W.length>0?W:void 0}catch{return}}function iL($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function nL($,J=process.platform,Q){if(J!=="win32"||!iL(Q))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function FV($){if($.length===0)return;let[J,...Q]=$,Z=J.replace(/\\/g,"/").toLowerCase(),W=Z.split("/").at(-1)??Z;if(W==="env")return FV(Q);if(W==="bash"||W==="sh"||W==="zsh")return[W,...Q];if(W==="python3"||W==="python")return process.platform==="win32"?["py","-3",...Q]:[W,...Q];return $}function aL($){let J=rL($);if(J&&J.length>0)return[...FV(J)??J,$];let Q=$.toLowerCase();if(Q.endsWith(".sh")||Q.endsWith(".bash")||Q.endsWith(".zsh"))return["bash",$];if(Q.endsWith(".js")||Q.endsWith(".mjs")||Q.endsWith(".cjs"))return KV(["node",$],{debugRole:"hook"});if(Q.endsWith(".ts")||Q.endsWith(".mts")||Q.endsWith(".cts"))return["bun","run",$];if(Q.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(Q.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function sL($){let J={};for(let Q of D$($)){if(!Q.hookEventName)continue;let Z=Q.hookEventName,W=J[Z]??[];W.push(aL(Q.path)),J[Z]=W}return J}async function oL($){let J;for(let Q of $.commands){let Z=Q.join(" ");try{let W=await GV($.payload,{command:Q,cwd:$.cwd,env:P7(process.env),detached:!1,timeoutMs:$.timeoutMs});if(W?.timedOut){v5($.logger,`hook command timed out: ${Z}`);continue}if(W?.parseError){v5($.logger,`hook command returned invalid JSON control output: ${Z} (${W.parseError})`);continue}J=uL(J,dL(W?.parsedJson))}catch(W){v5($.logger,`hook command failed: ${Z}`,W)}}return J}function Q2($){for(let J of $.commands){let Q=J.join(" ");GV($.payload,{command:J,cwd:$.cwd,env:P7(process.env),detached:!0}).catch((Z)=>{v5($.logger,`hook command failed: ${Q}`,Z)})}}function U$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function q7($,J){return{...U$($.snapshot),userMessage:J}}function DV($){return{...U$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function UV($){return{...U$($.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 RV($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function tL($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}function F8($){let J={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},Q=(Z)=>{let W=`${JSON.stringify({ts:new Date().toISOString(),...Z})}
192
+ `,f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??cL(BV(),"hooks.jsonl");BV(f),mL(f,W,"utf8")};return{beforeRun:async(Z)=>{let W=q7(Z,"");Q({...z0(W,J),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Z)=>{let W=DV(Z);Q({...z0(W,J),hookName:"tool_call",iteration:W.iteration,tool_call:{id:W.call.id,name:W.call.name,input:W.call.input},preToolUse:{toolName:W.call.name,parameters:c5(W.call.input)}});return},afterTool:async(Z)=>{let W=UV(Z);Q({...z0(W,J),hookName:"tool_result",iteration:W.iteration,tool_result:W.record,postToolUse:{toolName:W.record.name,parameters:c5(W.record.input),result:typeof W.record.output==="string"?W.record.output:JSON.stringify(W.record.output),success:!W.record.error,executionTimeMs:W.record.durationMs}});return},afterRun:async({snapshot:Z,result:W})=>{let j=U$(Z);if(W.status==="completed"){Q({...z0(j,J),hookName:"agent_end",iteration:W.iterations,turn:{outputText:W.outputText,status:W.status},taskComplete:{taskMetadata:{}}});return}if(W.status==="aborted"||M7(W.error?.message)){Q({...z0(j,J),hookName:"agent_abort",reason:W.error?.message,taskCancel:{taskMetadata:{}}});return}if(W.error)Q({...z0(j,J),hookName:"agent_error",iteration:W.iterations,error:{name:W.error.name,message:W.error.message,stack:W.error.stack}})},onEvent:async(Z)=>{if(Z.type!=="message-added"||Z.message.role!=="user")return;let W=q7({snapshot:Z.snapshot},RV(Z.message.content));Q({...z0(W,J),hookName:"prompt_submit",userPromptSubmit:{prompt:W.userMessage,attachments:[]}})}}}function A6($){let J=sL($.workspacePath);if(!Object.values(J).some((B)=>B.length>0))return;let Z=async(B,A)=>{let K=J[A]??[];if(K.length===0)return;Q2({commands:K,cwd:$.cwd,logger:$.logger,payload:A==="agent_resume"?{...z0(B,$),hookName:A,taskResume:{taskMetadata:{},previousState:{}}}:{...z0(B,$),hookName:A,taskStart:{taskMetadata:{}}}})},W=async(B)=>{let A=J.prompt_submit??[];if(A.length>0)Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"prompt_submit",userPromptSubmit:{prompt:B.userMessage,attachments:[]}}})},j=async(B)=>{let A=J.tool_call??[];if(A.length===0)return;return oL({commands:A,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...z0(B,$),hookName:"tool_call",iteration:B.iteration,tool_call:{id:B.call.id,name:B.call.name,input:B.call.input},preToolUse:{toolName:B.call.name,parameters:c5(B.call.input)}}})},f=async(B)=>{let A=J.tool_result??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"tool_result",iteration:B.iteration,tool_result:B.record,postToolUse:{toolName:B.record.name,parameters:c5(B.record.input),result:typeof B.record.output==="string"?B.record.output:JSON.stringify(B.record.output),success:!B.record.error,executionTimeMs:B.record.durationMs}}})},X=async(B)=>{let A=J.agent_end??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_end",iteration:B.iteration,turn:B.turn,taskComplete:{taskMetadata:{}}}})},Y=async(B)=>{let A=J.agent_error??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_error",iteration:B.iteration,error:{name:B.error.name,message:B.error.message,stack:B.error.stack}}})},V=async(B)=>{if(M7(B.reason)){let K=J.agent_abort??[];if(K.length>0)Q2({commands:K,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"agent_abort",reason:B.reason,taskCancel:{taskMetadata:{}}}})}let A=J.session_shutdown??[];if(A.length===0)return;Q2({commands:A,cwd:$.cwd,logger:$.logger,payload:{...z0(B,$),hookName:"session_shutdown",reason:B.reason}})},H={};if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0||(J.prompt_submit?.length??0)>0){if((J.agent_start?.length??0)>0||(J.agent_resume?.length??0)>0)H.beforeRun=async(B)=>{let A=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Z(U$(B.snapshot),A);return};if((J.prompt_submit?.length??0)>0)H.onEvent=async(B)=>{if(B.type!=="message-added"||B.message.role!=="user")return;await W(q7({snapshot:B.snapshot},RV(B.message.content)))}}if((J.tool_call?.length??0)>0)H.beforeTool=async(B)=>{let A=await j(DV(B));return tL(A)};if((J.tool_result?.length??0)>0)H.afterTool=async(B)=>{await f(UV(B));return};if((J.agent_end?.length??0)>0)H.afterRun=async({snapshot:B,result:A})=>{if(A.status!=="completed")return;await X({...U$(B),iteration:A.iterations,turn:{outputText:A.outputText,status:A.status}})};if((J.agent_error?.length??0)>0||(J.agent_abort?.length??0)>0||(J.session_shutdown?.length??0)>0){let B=H.afterRun;H.afterRun=async(A)=>{await B?.(A);let{snapshot:K,result:G}=A;if(G.status==="aborted"||M7(G.error?.message)){await V({...U$(K),reason:G.error?.message});return}if(G.error)await Y({...U$(K),iteration:G.iterations,error:G.error})}}return H}function D8($){return K8("core.hook_config_files",A6($))}function Z2($,J){let Q=$.map((Z)=>Z[J]).filter((Z)=>typeof Z==="function");if(Q.length===0)return;return async(Z)=>{let W;for(let j of Q){let f=await j(Z);if(!f||typeof f!=="object")continue;let X=f;W={...W??{},...X,stop:W?.stop===!0||X.stop===!0?!0:X.stop,options:W?.options||X.options?{...W?.options??{},...X.options??{}}:void 0}}return W}}function W2($){let J=$.filter((Q)=>Q!==void 0);if(J.length===0)return;return{beforeRun:Z2(J,"beforeRun"),afterRun:Z2(J,"afterRun"),beforeModel:Z2(J,"beforeModel"),afterModel:Z2(J,"afterModel"),beforeTool:Z2(J,"beforeTool"),afterTool:Z2(J,"afterTool"),onEvent:Z2(J,"onEvent")}}var zV={};w(zV,{normalizeRuntimeCapabilities:()=>L0});function L0(...$){let J,Q;for(let W of $){if(!W)continue;if(W.toolExecutors)J={...J??{},...W.toolExecutors};if(W.requestToolApproval)Q=W.requestToolApproval}let Z=J&&Object.keys(J).length>0;if(!Z&&!Q)return;return{...Z?{toolExecutors:J}:{},...Q?{requestToolApproval:Q}:{}}}var wV={};w(wV,{toProviderConfig:()=>d0,emptyStoredProviderSettings:()=>L$,StoredProviderSettingsSchema:()=>L8,StoredProviderSettingsEntrySchema:()=>H9,ProviderSettingsSchemaTyped:()=>z8});import{z as z$}from"zod";var NV={};w(NV,{toProviderConfig:()=>d0,safeParseSettings:()=>V9,safeCreateProviderConfig:()=>I7,parseSettings:()=>Y9,normalizeProviderId:()=>R8,isBuiltInProviderId:()=>h7,createProviderConfig:()=>k7,SapSettingsSchema:()=>j9,ReasoningSettingsSchema:()=>J9,ProviderSettingsSchema:()=>R$,ProviderProtocolSchema:()=>t5,ProviderIdSchema:()=>U6,ProviderClientSchema:()=>e5,OcaSettingsSchema:()=>f9,ModelCatalogSettingsSchema:()=>X9,GcpSettingsSchema:()=>Z9,BUILT_IN_PROVIDER_IDS:()=>b7,BUILT_IN_PROVIDER:()=>D6,AzureSettingsSchema:()=>W9,AwsSettingsSchema:()=>Q9,AuthSettingsSchema:()=>$9});import*as u0 from"@cline/llms";import{z as N}from"zod";var PV={};w(PV,{resolveProviderConfig:()=>F6,getProviderConfig:()=>o5,getLiveModelsCatalog:()=>U8,clearPublicModelsCatalogCache:()=>z_,clearPrivateModelsCatalogCache:()=>E7,clearLiveModelsCatalogCache:()=>y7,OPENAI_COMPATIBLE_PROVIDERS:()=>G6,DEFAULT_MODELS_CATALOG_URL:()=>i5});import*as H0 from"@cline/llms";function N7($){if(!Array.isArray($))return[];return $.map((J)=>{if(typeof J==="string")return J.trim();if(J&&typeof J==="object"){let Q=J;for(let Z of[Q.id,Q.name,Q.model])if(typeof Z==="string"&&Z.trim())return Z.trim()}return""}).filter((J)=>J.length>0)}function eL($,J){let Q=N7($);if(Q.length>0)return Q;if(!$||typeof $!=="object")return[];let Z=$,W=N7(Z.data??Z.models);if(W.length>0)return W;if(Z.models&&typeof Z.models==="object"&&!Array.isArray(Z.models)){let f=Object.keys(Z.models).filter((X)=>X.trim().length>0);if(f.length>0)return f}let j=Z.providers?.[J];if(j&&typeof j==="object"){let X=N7(j.models??j);if(X.length>0)return X}return[]}async function u5($,J){let Q=await fetch($,{method:"GET"});if(!Q.ok)throw Error(`failed to fetch models from ${$}: HTTP ${Q.status}`);return eL(await Q.json(),J)}function LV($){return $.replace(/\/+$/,"")}function d5($,J,Q){let Z=Q?.trim();if(!Z)return;let W=$?.trim();if(!W||!J?.trim())return Z;try{let j=new URL(Z),f=new URL(J),X=new URL(W);if(j.origin!==f.origin)return Z;let Y=LV(f.pathname),V=LV(X.pathname);if(Y&&j.pathname.startsWith(`${Y}/`)){let H=j.pathname.slice(Y.length);X.pathname=`${V}${H}`}else X.pathname=j.pathname;return X.search=j.search,X.hash=j.hash,X.toString()}catch{return Z}}function $_($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{...Q}]))}function J_($){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 Q_=Object.values(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:$_($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),OV=Object.fromEntries(Q_.map(($)=>[$.id,$]));function Z_($){return OV[$]}function W_(){return Object.fromEntries(Object.entries(OV).filter(([,$])=>J_($)))}function TV($=[]){let J=$.flatMap((Q)=>{switch(Q){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[Q];default:return[]}});return J.length>0?J:void 0}var i5="https://models.dev/api.json",j_=600000,MV=300000,f_=5000,r5=new Map,K6=new Map,w7=new Map,l5=new Map;async function X_(){return H0.getGeneratedProviderModels()}async function Y_($,J={},Q={},Z={},W={},j={}){let f=await X_(),X=H0.resolveProviderModelCatalogKeys($),Y=Object.assign({},...X.map((B)=>f[B]??{})),V=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),H=Object.keys(W).length>0;if(V&&H)return H0.sortModelsByReleaseDate({...W,...j});if($==="openai-codex")return H0.sortModelsByReleaseDate({...J,...H0.filterOpenAICodexModels(Q),...W,...j});return H0.sortModelsByReleaseDate({...Y,...J,...Q,...Z,...W,...j})}function V_($,J){let Q=H0.resolveProviderModelCatalogKeys($);return Object.assign({},...Q.map((Z)=>J[Z]??{}))}function n5($){let J=$?.trim();return J&&J.length>0?J:""}function C7($){let J=$.apiKey?.trim()||$.accessToken?.trim();return J&&J.length>0?J:void 0}function H_($){let J=2166136261;for(let Q=0;Q<$.length;Q+=1)J^=$.charCodeAt(Q),J+=(J<<1)+(J<<4)+(J<<7)+(J<<8)+(J<<24);return(J>>>0).toString(16)}function B_($,J){return`${$}:${n5(J.baseUrl)}:${H_(C7(J)??"")}`}async function a5($,J,Q=f_){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await fetch($,{...J,signal:Z.signal})}finally{clearTimeout(W)}}function j2($,J,Q){if(Q&&!$.includes(J))$.push(J)}function s5($,J){let Q=["streaming","tools"];return j2(Q,"images",Boolean(J.supportsImages)),j2(Q,"prompt-cache",Boolean(J.supportsPromptCache)),j2(Q,"reasoning",Boolean(J.supportsReasoning)),{id:$,name:J.name??$,contextWindow:J.contextWindow,maxInputTokens:J.maxInputTokens,maxTokens:J.maxTokens,capabilities:Q,releaseDate:J.releaseDate,status:"active"}}async function A_($,J){let Q=await a5("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json"}});if(!Q.ok)throw Error(`Baseten model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let Y=f.supported_features??[];j[X]=s5(X,{name:X,contextWindow:f.context_length,maxInputTokens:f.context_length,maxTokens:f.max_completion_tokens,supportsReasoning:Y.includes("reasoning")||Y.includes("reasoning_effort"),supportsImages:!1})}return j}function _V($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let J=Number($);return Number.isFinite(J)?J:void 0}return}async function K_($,J){let Q=await a5("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":J}});if(!Q.ok)throw Error(`Hicap model refresh failed: HTTP ${Q.status}`);let W=(await Q.json())?.data??[],j={};for(let f of W){let X=f.id?.trim();if(!X)continue;j[X]=s5(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return j}async function G_($,J){let Z=`${(n5($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,W=await a5(Z,{method:"GET",headers:{Authorization:`Bearer ${J}`,accept:"application/json"}});if(!W.ok)throw Error(`Poolside model refresh failed: HTTP ${W.status}`);let f=(await W.json())?.data??[],X={};for(let Y of f){let V=Y.id?.trim();if(!V)continue;let H=Y.supported_features??[],B=Y.supported_sampling_parameters??[],A=Y.input_modalities??[],K=["streaming"];j2(K,"tools",H.includes("tools")),j2(K,"reasoning",H.includes("reasoning")),j2(K,"temperature",B.includes("temperature")),j2(K,"images",A.includes("image"));let G={input:_V(Y.pricing?.prompt),output:_V(Y.pricing?.completion)};X[V]={id:V,name:Y.name??V,description:Y.description,contextWindow:Y.context_length,maxInputTokens:Y.context_length,maxTokens:Y.max_completion_tokens,capabilities:K,pricing:G.input!==void 0||G.output!==void 0?G:void 0,status:"active"}}return X}function F_($){let J=n5($);if(!J)return"http://localhost:4000";return J.endsWith("/v1")?J.slice(0,-3):J}async function D_($,J){let Z=`${F_($.baseUrl)}/v1/model/info`,W=async(V)=>a5(Z,{method:"GET",headers:{accept:"application/json",...V}}),j=await W({"x-litellm-api-key":J});if(!j.ok)j=await W({Authorization:`Bearer ${J}`});if(!j.ok)throw Error(`LiteLLM model refresh failed: HTTP ${j.status}`);let X=(await j.json())?.data??[],Y={};for(let V of X){let H=V.model_name?.trim(),A=V.litellm_params?.model?.trim()||H;if(!A)continue;let K=V.model_info,G=s5(A,{name:H??A,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(Y[A]=G,H)Y[H]={...G,id:H,name:H}}return Y}var qV={baseten:A_,hicap:K_,litellm:D_,poolside:G_},S7=new Map,p5=new Map;function U_($,J){return`${$}:${n5(J.baseUrl)}`}async function R_($,J,Q){let Z=H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],W=d5(Q.baseUrl,Z?.provider.baseUrl,Z?.provider.modelsSourceUrl);if(!W)return{};let j=J?.cacheTtlMs??MV,f=U_($,Q),X=Date.now(),Y=S7.get(f);if(Y&&Y.expiresAt>X)return Y.data;let V=p5.get(f);if(V)return V;let H=u5(W,$).then((B)=>{let A=Object.fromEntries(B.map((K)=>[K,s5(K,{name:K})]));return S7.set(f,{data:A,expiresAt:X+j}),A}).finally(()=>{p5.delete(f)});return p5.set(f,H),H}function z_(){S7.clear(),p5.clear()}async function L_($,J){let Q=C7(J);if(!Q)return{};let Z=qV[$];if(!Z)return{};return Z(J,Q)}function __($,J,Q){if(!Q)return!1;if(!qV[$])return!1;if(J?.loadPrivateOnAuth===!1)return!1;return Boolean(C7(Q))}async function O_($,J,Q){let Z=J?.cacheTtlMs??MV,W=B_($,Q),j=Date.now(),f=w7.get(W);if(f&&f.expiresAt>j)return f.data;let X=l5.get(W);if(X)return X;let Y=L_($,Q).then((V)=>{return w7.set(W,{data:V,expiresAt:j+Z}),V}).finally(()=>{l5.delete(W)});return l5.set(W,Y),Y}async function T_($){return H0.fetchModelsDevProviderModels($,globalThis.fetch)}async function U8($={}){let J=$.url??i5,Q=$.cacheTtlMs??j_,Z=Date.now(),W=r5.get(J);if(W&&W.expiresAt>Z)return W.data;let j=K6.get(J);if(j)return j;let f=T_(J).then((X)=>{return r5.set(J,{data:X,expiresAt:Z+Q}),X}).finally(()=>{K6.delete(J)});return K6.set(J,f),f}function y7($){if($){r5.delete($),K6.delete($);return}r5.clear(),K6.clear()}function E7(){w7.clear(),l5.clear()}function M_($){return Object.fromEntries(Object.entries($).map(([J,Q])=>[J,{baseUrl:Q.baseUrl,modelId:Q.modelId,capabilities:TV(Q.capabilities)}]))}var G6=M_(W_());function o5($){let J=Z_($);if(!J)return;return{baseUrl:J.baseUrl||void 0,modelId:J.modelId,knownModels:J.knownModels,capabilities:TV(J.capabilities)}}async function F6($,J,Q){let Z=o5($);if(!Z)return;try{let W=J?.loadLatestOnInit?await U8(J):void 0,j=W?V_($,W):{},f=Q&&__($,J,Q)?await O_($,J,Q):{},Y=Boolean(H0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?Q??{providerId:$,modelId:Z.modelId,baseUrl:Z.baseUrl}:Q,V=Y?await R_($,J,Y).catch(()=>({})):{},H=await Y_($,Z.knownModels,j,f,V,Q?.knownModels);return{...Z,knownModels:H}}catch(W){if(J?.failOnError)throw W;return Z}}var D6=u0.BUILT_IN_PROVIDER,b7=u0.BUILT_IN_PROVIDER_IDS,h7=u0.isBuiltInProviderId,R8=u0.normalizeProviderId,U6=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),t5=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),e5=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),$9=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),q_=N.enum(["none","low","medium","high","xhigh"]),J9=N.object({enabled:N.boolean().optional(),effort:q_.optional(),budgetTokens:N.number().int().positive().optional()}),Q9=N.object({accessKey:N.string().optional(),secretKey:N.string().optional(),sessionToken:N.string().optional(),region:N.string().optional(),profile:N.string().optional(),authentication:N.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:N.boolean().optional(),useCrossRegionInference:N.boolean().optional(),useGlobalInference:N.boolean().optional(),endpoint:N.string().url().optional(),customModelBaseId:N.string().optional()}),Z9=N.object({projectId:N.string().optional(),region:N.string().optional()}),W9=N.object({apiVersion:N.string().optional(),useIdentity:N.boolean().optional()}),j9=N.object({clientId:N.string().optional(),clientSecret:N.string().optional(),tokenUrl:N.string().url().optional(),resourceGroup:N.string().optional(),deploymentId:N.string().optional(),useOrchestrationMode:N.boolean().optional(),api:N.enum(["orchestration","foundation-models"]).optional(),defaultSettings:N.record(N.string(),N.unknown()).optional()}),f9=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),X9=N.object({loadLatestOnInit:N.boolean().optional(),loadPrivateOnAuth:N.boolean().optional(),url:N.string().url().optional(),cacheTtlMs:N.number().int().positive().optional(),failOnError:N.boolean().optional()}),R$=N.object({provider:U6,apiKey:N.string().optional(),auth:$9.optional(),model:N.string().optional(),protocol:t5.optional(),client:e5.optional(),routingProviderId:U6.optional(),maxTokens:N.number().int().positive().optional(),contextWindow:N.number().int().positive().optional(),baseUrl:N.string().url().optional(),headers:N.record(N.string(),N.string()).optional(),timeout:N.number().int().positive().optional(),reasoning:J9.optional(),aws:Q9.optional(),gcp:Z9.optional(),azure:W9.optional(),sap:j9.optional(),oca:f9.optional(),region:N.string().optional(),apiLine:N.enum(["china","international"]).optional(),capabilities:N.array(N.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:X9.optional()});function Y9($){return R$.parse($)}function V9($){return R$.safeParse($)}function P_($){return $.protocol==="openai-responses"||$.client==="openai"}function d0($,J={}){let Q=$.provider,Z=R8(Q),W=J.includeKnownModels!==!1,j=$.reasoning?.effort||"none",f=j==="none"?void 0:j,X=G6[Z],Y=Object.assign({},...u0.resolveProviderModelCatalogKeys(Z).map((R)=>u0.getGeneratedModelsForProvider(R))),V=Object.keys(Y)[0],H=l2(Z,$),B=$.baseUrl??(Z==="oca"?$.oca?.mode==="internal"?J5:Q5:X?.baseUrl),A=$.routingProviderId??(P_($)&&Z!==D6.OPENAI_NATIVE?D6.OPENAI_NATIVE:void 0),K=W?X?.knownModels??(Object.keys(Y).length>0?Y:void 0):void 0,G={providerId:Q,clientType:$.client,routingProviderId:A,modelId:$.model??X?.modelId??V??"default",...W?{knownModels:K}:{},apiKey:H,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:B,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:f,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,D])=>D!==void 0))}function k7($){let J=Y9($);return d0(J)}function I7($){let J=V9($);if(J.success)return{success:!0,config:d0(J.data)};return{success:!1,error:J.error}}var z8=R$;var H9=z$.object({settings:R$,updatedAt:z$.string().datetime(),tokenSource:z$.enum(["manual","oauth","migration"]).default("manual")}),L8=z$.object({version:z$.literal(1),lastUsedProvider:z$.string().min(1).optional(),providers:z$.record(z$.string(),H9)});function L$(){return{version:1,providers:{}}}W1();var EV={};w(EV,{InMemoryWorkspaceManager:()=>O8});import{upsertWorkspaceInfo as C_,WorkspaceManifestSchema as g7}from"@cline/shared";var yV={};w(yV,{normalizeWorkspacePath:()=>m1,generateWorkspaceInfoWithDiagnostics:()=>R6,generateWorkspaceInfo:()=>_8,buildWorkspaceMetadataWithInfo:()=>x7,buildWorkspaceMetadata:()=>z6});import{basename as N_,resolve as w_}from"node:path";import{performance as SV}from"node:perf_hooks";import{processWorkspaceInfo as CV}from"@cline/shared";import S_ from"simple-git";function m1($){return w_($)}async function _8($){return(await R6($)).info}function B9($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function R6($){let J=m1($),Q={rootPath:J,hint:N_(J)},Z;try{let W=S_({baseDir:J});if(!await W.checkIsRepo())return{info:Q,vcsType:"none"};try{let f=await W.getRemotes(!0);if(f.length>0){let X=f.map((Y)=>{let V=Y.refs.fetch||Y.refs.push;return`${Y.name}: ${V}`});Q.associatedRemoteUrls=X}}catch(f){Z??=B9(f)}try{let f=(await W.revparse(["HEAD"])).trim();if(f.length>0)Q.latestGitCommitHash=f}catch(f){Z??=B9(f)}try{let f=(await W.branch()).current.trim();if(f.length>0)Q.latestGitBranchName=f}catch(f){Z??=B9(f)}return{info:Q,vcsType:"git",error:Z}}catch(W){return{info:Q,vcsType:"none",error:B9(W)}}}async function z6($){let J=await _8($);return CV(J)}async function x7($){let J=SV.now(),Q=await R6($),Z=SV.now()-J,W=Q.info;return{workspaceInfo:W,workspaceMetadata:CV(W),durationMs:Z,vcsType:Q.vcsType,initError:Q.error}}class O8{manifest;listeners=new Set;constructor($){this.manifest=g7.parse($??{workspaces:{}})}async addWorkspacePath($){let J=await _8($);return this.manifest=C_(this.manifest,J),this.emit({type:"workspace_added",workspace:J}),J}async switchWorkspace($){let J=m1($),Q=this.manifest.workspaces[J];if(Q)return this.manifest=g7.parse({...this.manifest,currentWorkspacePath:J}),this.emit({type:"workspace_switched",workspace:Q}),Q;let Z=await this.addWorkspacePath(J);return this.manifest=g7.parse({...this.manifest,currentWorkspacePath:Z.rootPath}),this.emit({type:"workspace_switched",workspace:Z}),Z}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let J=m1($);return this.manifest.workspaces[J]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let J of this.listeners)J($)}}O0();import{createHash as y_}from"node:crypto";var bV=new Set,hV=new Set;function E_($){return y_("sha256").update($).digest("hex")}function b_($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function kV($){if(!$.telemetry)return;let J=E_($.rootPath),Q=$.rootCount??1;if(!bV.has(J))bV.add(J),bJ($.telemetry,{root_count:Q,vcs_types:b_($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!hV.has(J)){hV.add(J);let Z=Error($.initError.message);Z.name=$.initError.errorType||"Error",hJ($.telemetry,Z,{fallback_to_single_root:!0,workspace_count:Q})}}function k_($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function I_($,J,Q){if(J.length>0)for(let j of J)Q?.log(j.message,{severity:"warn"});if($.length===0)return;let Z=$.slice(0,3).map(k_).join("; "),W=$.length>3?`; and ${$.length-3} more`:"";Q?.log(`Some plugins failed to initialize. ${Z}${W}. Use --verbose for more details.`,{severity:"warn"});for(let j of $)Q?.log(`Plugin initialization failed (${j.phase}) for ${j.pluginPath}`,{severity:"warn",stack:j.stack,pluginPath:j.pluginPath,pluginName:j.pluginName})}function x_($,J){let Q=typeof $.thinking==="boolean",Z=typeof $.reasoningEffort==="string";if(!Q&&!Z)return J;return{...J??{},...Q?{enabled:$.thinking}:{},...Z?{effort:$.reasoningEffort}:{}}}function IV($,J){return h_($,J)}function g_($){let J=0;for(let Q of $??[]){if(Q.role!=="user")continue;if(("metadata"in Q&&Q.metadata&&typeof Q.metadata==="object"&&!Array.isArray(Q.metadata)?Q.metadata:void 0)?.kind==="recovery_notice")continue;J+=1}return J}function m_($){let J={...$.storedHeaders??{},...$.configHeaders??{}},Q=$.accountId?.trim()||v_($.accessToken);if(J.originator="cline",J.session_id=$.sessionId,J["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,Q)J["ChatGPT-Account-Id"]=Q;return J}function v_($){let J=$?.trim();if(!J)return;let Q=T0(J),Z=Q?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Z==="string"&&Z.length>0)return Z;let W=Q?.organizations?.[0]?.id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.chatgpt_account_id;if(typeof j==="string"&&j.length>0)return j;return}function c_($,J,Q,Z,W){let j=Q.getProviderSettings($.providerId),f=Z||j?.modelCatalog?{...Z??{},...j?.modelCatalog??{}}:void 0,X=$.providerConfig?.providerId===$.providerId?$.providerConfig:void 0,Y={...j??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??j?.apiKey,baseUrl:$.baseUrl??j?.baseUrl,headers:$.providerId==="openai-codex"?m_({sessionId:J,configHeaders:$.headers,storedHeaders:j?.headers,accountId:j?.auth?.accountId,accessToken:$.apiKey??j?.auth?.accessToken??j?.apiKey}):$.headers??j?.headers,reasoning:x_($,j?.reasoning),modelCatalog:f},V={...d0(Y),...X??{}};if($.knownModels)V.knownModels=$.knownModels;if($.extensionContext)V.extensionContext=$.extensionContext;let B=$.fetch??V.fetch??W;if(B)V.fetch=B;return V}async function xV($){let{input:J,sessionId:Q,providerSettingsManager:Z,defaultTelemetry:W,defaultCapabilities:j,defaultToolPolicies:f,defaultFetch:X,onPluginEvent:Y,onTeamEvent:V,createSubAgentLifecycleCallbacks:H,createSpawnTool:B,localRuntime:A,readSessionMetadata:K,writeSessionMetadata:G}=$,R=G$(J.config),{modelCatalogDefaults:D,userInstructionService:U,configExtensions:F,onTeamRestored:O,...T}=A??{},L=Object.keys(T).length>0?T:void 0,{workspaceInfo:z,workspaceMetadata:P,durationMs:S,vcsType:b,initError:u}=await x7(R),o=L?.extensionContext,J0={...o??{},workspace:{...z,...o?.workspace??{}},session:{...o?.session??{},sessionId:Q},logger:o?.logger??L?.logger,telemetry:o?.telemetry??L?.telemetry??W};kV({telemetry:J0.telemetry,rootPath:z.rootPath,workspaceInfo:z,rootCount:1,vcsType:b,durationMs:S,initError:u,featureFlagEnabled:!0});let t=D8({cwd:J.config.cwd,workspacePath:R,rootSessionId:Q,logger:L?.logger,workspaceInfo:z}),$1=EY(L?.hooks)?void 0:F8({rootSessionId:Q,workspacePath:R,workspaceInfo:z}),b$=W2([L?.hooks,$1]),n;if(IV(F,"plugins"))try{n=await A8({pluginPaths:L?.pluginPaths,workspacePath:R,cwd:J.config.cwd,onEvent:Y,providerId:J.config.providerId,modelId:J.config.modelId,workspaceInfo:z,session:J0.session,client:J0.client,user:J0.user,logger:J0.logger,telemetry:J0.telemetry,automation:J0.automation}),I_(n.failures,n.warnings,L?.logger)}catch(x2){let sQ=x2 instanceof Error?x2.message:String(x2);L?.logger?.log?.(`plugin loading failed; continuing without plugins (${sQ})`)}let C=J7(t?[t]:void 0,J7(L?.extensions,_5(n?.extensions))),F0=IV(F,"plugins")?$2(n?.pluginPaths??[]):void 0,f0={...J.config,...L??{},sessionId:Q,hooks:b$,extensions:C,extensionContext:J0,telemetry:J0.telemetry},w0=c_(f0,Q,Z,D,X),k2=W2([f0.hooks,f0.checkpoint?.enabled===!0?HV({cwd:f0.cwd,sessionId:Q,logger:f0.logger,createCheckpoint:f0.checkpoint?.createCheckpoint,initialRunCount:g_(J.initialMessages),readSessionMetadata:K,writeSessionMetadata:G}):void 0]),T1={...f0,providerConfig:w0,workspaceMetadata:P,hooks:k2},Y1=J.toolPolicies??f0.toolPolicies??f,Y4=L0(j,J.capabilities),I2=Y4?.requestToolApproval,SJ=Y4?.toolExecutors,M1=H?.(T1),CJ=new O8({currentWorkspacePath:z.rootPath,workspaces:{[z.rootPath]:z}});return{effectiveInput:J,config:T1,providerConfig:w0,workspaceMetadata:P,workspaceInfo:z,extensions:C,hooks:k2,toolPolicies:Y1,requestToolApproval:I2,pluginSandboxShutdown:n?.shutdown,runtimeBuilderInput:{config:T1,hooks:k2,extensions:C,onTeamEvent:V,createSpawnTool:B,onTeamRestored:O,onSubAgentEvent:M1?.onSubAgentEvent,onSubAgentStart:M1?.onSubAgentStart,onSubAgentEnd:M1?.onSubAgentEnd,userInstructionService:U,pluginSkillDirectories:F0,configExtensions:F,toolExecutors:SJ,toolPolicies:Y1,workspaceManager:CJ,logger:T1.logger,telemetry:T1.telemetry,requestToolApproval:I2}}}import{existsSync as K9,mkdirSync as u_,readdirSync as d_,rmdirSync as l_,rmSync as p_,unlinkSync as r_}from"node:fs";import{dirname as gV,join as A9}from"node:path";function e(){return new Date().toISOString()}function L6($){if(!$||!K9($))return;try{r_($)}catch{}}function i_($){let J=W8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:`${J.agentId}__${J.teamTaskId}`};let Q=o4($);if(Q)return{rootSessionId:Q.rootSessionId,fileStem:Q.agentId};return{rootSessionId:$,fileStem:$}}class m7{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return A9(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let J=this.sessionArtifactsDir($);if(!K9(J))u_(J,{recursive:!0});return J}sessionMessagesPath($){return A9(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,J=!1){let Q=J?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return A9(Q,`${$}.json`)}removeSessionDirIfEmpty($){let J=this.sessionArtifactsDir($),Q=this.ensureSessionsDir();while(J.startsWith(Q)&&J!==Q){if(!K9(J)){J=gV(J);continue}try{if(d_(J).length>0)break;l_(J)}catch{break}J=gV(J)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!K9($))return;try{p_($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,J,Q){let{rootSessionId:Z,fileStem:W}=i_($),j=this.sessionArtifactsDir(Z);return{messagesPath:A9(j,`${W}.messages.json`)}}}import{resolveDocumentsExtensionPath as n_}from"@cline/shared/storage";O0();function mV($,J,Q,Z,W){if(Q)IJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});else kJ($.telemetry,{ulid:J,apiProvider:$.providerId,...W});a_($.telemetry,{workspacePath:Z})}function a_($,J){let Q=n_("Hooks"),Z=D$(J.workspacePath),W=new Map;for(let j of Z){let f=j.hookEventName??"unknown",X=W.get(f)??{global:0,workspace:0};if(j.path===Q||j.path.startsWith(`${Q}/`))X.global+=1;else X.workspace+=1;W.set(f,X)}for(let[j,f]of W.entries())rJ($,j,f.global,f.workspace)}function vV($,J){for(let Q of J.mentions)lJ($,Q,J.matchedFiles.includes(Q)?1:0,"file",!J.matchedFiles.includes(Q));for(let Q of J.matchedFiles)uJ($,"file",Q.length);for(let Q of J.ignoredMentions)dJ($,"file","not_found",Q)}var iG={};w(iG,{ProviderSettingsManager:()=>_1});import{chmodSync as aG,existsSync as Pj,mkdirSync as Xb,readFileSync as Yb,writeFileSync as Vb}from"node:fs";import{basename as sG,dirname as Nj}from"node:path";import{resolveProviderSettingsPath as Hb}from"@cline/shared/storage";var M={};w(M,{writeHubDiscovery:()=>d9,writeGlobalSettings:()=>k1,withHubStartupLock:()=>l9,verifyHubConnection:()=>G1,updateMcpServerOAuthState:()=>H2,updateLocalProvider:()=>IQ,uninstallPlugin:()=>t3,truncateNotificationBody:()=>UJ,toggleDisabledTool:()=>z5,toTeamProgressLifecycleEvent:()=>u8,toProviderConfig:()=>d0,toHubStatusUrl:()=>PW,toHubHealthUrl:()=>p9,toHookConfigFileName:()=>B6,syncPluginMcpServersToSettings:()=>d3,summarizeUsageFromMessages:()=>f8,stopLocalHubServerGracefully:()=>gW,startLocalOAuthServer:()=>J1,startHubWebSocketServer:()=>C2,startHubServer:()=>uK,startClineDeviceAuth:()=>WZ,splitCoreSessionConfig:()=>u6,spawnDetachedHubServerWithRetry:()=>h8,spawnDetachedHubServer:()=>EW,setTelemetryOptOutGlobally:()=>yX,setMcpServerDisabled:()=>Y2,setDisabledTools:()=>IZ,setDisabledPlugin:()=>xX,setAutoUpdateEnabledGlobally:()=>bX,sendHubCommand:()=>cA,saveProviderOAuthCredentials:()=>x$,saveLocalProviderSettings:()=>fj,saveLocalProviderOAuthCredentials:()=>Hj,sanitizeSessionToken:()=>a$,safeParseSettings:()=>V9,safeCreateProviderConfig:()=>I7,runSubprocessEvent:()=>r8,runHook:()=>n8,reviveTeamStateDates:()=>P5,restartLocalHubIfIdleAfterStartupTimeout:()=>s9,resolveWorkspaceHubOwnerContext:()=>PB,resolveWorkflowsConfigSearchPaths:()=>y6,resolveSkillsConfigSearchPaths:()=>S6,resolveSharedHubOwnerContext:()=>E0,resolveSessionBackend:()=>W3,resolveRulesConfigSearchPaths:()=>C6,resolveProviderConfig:()=>F6,resolveProviderApiKeyFromSettings:()=>HZ,resolveProductionHubOwnerContext:()=>n0,resolvePluginSkillDirectoriesFromPaths:()=>$2,resolvePluginConfigSearchPaths:()=>X6,resolveMcpServerRegistrations:()=>A1,resolveLocalClineAuthToken:()=>Aj,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>l1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>u9,resolveHooksConfigSearchPaths:()=>V6,resolveDisabledToolNames:()=>B1,resolveDisabledPluginPaths:()=>p4,resolveDefaultMcpSettingsPath:()=>B0,resolveDefaultHubPort:()=>b8,resolveDefaultHubPathname:()=>yW,resolveDefaultHubHost:()=>CW,resolveCoreSelectedToolIds:()=>w5,resolveCoreDistinctId:()=>b0,resolveCompatibleLocalHubUrl:()=>QJ,resolveClineDir:()=>OB,resolveClineDataDir:()=>R2,resolveAndLoadAgentPlugins:()=>A8,resolveAgentPluginPaths:()=>e$,requestHubShutdown:()=>JJ,requestDesktopToolApproval:()=>m3,removePluginMcpServersFromSettings:()=>MJ,rememberRecoverableLocalHubUrl:()=>P$,registerRemoteConfigSessionBlobUpload:()=>_Q,registerMcpServersFromSettingsFile:()=>B2,registerDisposable:()=>Zb,refreshProviderModelsFromSource:()=>Xj,refreshOpenAICodexToken:()=>$5,refreshOcaToken:()=>W5,refreshClineToken:()=>tJ,readSessionCheckpointHistory:()=>RJ,readRemoteConfigSessionBlobUploadMetadata:()=>C3,readHubDiscovery:()=>A0,readGlobalSettings:()=>M0,readBearerToken:()=>FQ,probeHubServer:()=>p1,probeHubConnection:()=>vA,prewarmFileIndex:()=>A5,prewarmDetachedHubServer:()=>i9,prepareRemoteConfigCoreIntegration:()=>E3,parseWorkflowConfigFromMarkdown:()=>w6,parseUserCommandEnvelope:()=>Qb,parseSkillConfigFromMarkdown:()=>P6,parseSettings:()=>Y9,parseRuleConfigFromMarkdown:()=>N6,parseHookEventPayload:()=>i8,parseConfiguredAgentConfig:()=>fJ,normalizeWorkspacePath:()=>m1,normalizeUserInput:()=>Jb,normalizeSdkError:()=>$b,normalizeRuntimeCapabilities:()=>L0,normalizeProviderId:()=>R8,normalizeOAuthProvider:()=>Yj,normalizeHubWebSocketUrl:()=>N$,noopBasicLogger:()=>eE,migrateLegacyProviderSettings:()=>PJ,mergeRulesForSystemPrompt:()=>N8,mergeAgentHooks:()=>W2,makeTeamTaskSubSessionId:()=>s4,makeSubSessionId:()=>Z8,loginOpenAICodex:()=>G4,loginOcaOAuth:()=>U4,loginLocalProvider:()=>Vj,loginClineOAuth:()=>A4,loginAndSaveProviderOAuthCredentials:()=>z4,loginAndSaveLocalProviderOAuthCredentials:()=>Bj,loadOpenTelemetryAdapter:()=>mE,loadMcpSettingsFile:()=>X2,loadLlmsConfigFromFile:()=>Tj,loadConfiguredAgentConfigs:()=>m8,loadAgentPluginsFromPathsWithDiagnostics:()=>t$,loadAgentPluginsFromPaths:()=>b5,loadAgentPluginFromPath:()=>j6,listSessionHistoryFromBackend:()=>OW,listPluginToolsWithDiagnostics:()=>b9,listPluginTools:()=>v6,listMcpServerOAuthStatuses:()=>g6,listLocalProviders:()=>Wj,listHookConfigFiles:()=>D$,isToolDisabledGlobally:()=>hX,isTelemetryOptedOutGlobally:()=>R5,isSessionNotFoundError:()=>d1,isRuleEnabled:()=>T9,isPluginDisabledGlobally:()=>IX,isOAuthProvider:()=>I$,isHubReconnectableTransportError:()=>IW,isHubCommandTimeoutError:()=>a9,isDiscoveryFilePresent:()=>MB,isClineAccountActionRequest:()=>G9,isBuiltInProviderId:()=>h7,isAutoUpdateEnabledGlobally:()=>EX,identifyAccount:()=>S1,hasMcpSettingsFile:()=>c1,getValidOpenAICodexCredentials:()=>F4,getValidOcaCredentials:()=>R4,getValidClineCredentials:()=>K4,getProviderOAuthCredentialsFromSettings:()=>L4,getProviderConfigFields:()=>Kj,getProviderConfig:()=>o5,getProviderAuthStorageId:()=>VZ,getProviderAuthHandler:()=>Z0,getPersistedProviderApiKey:()=>l2,getMcpServerOAuthState:()=>V2,getLocalProviderModels:()=>jj,getLiveModelsCatalog:()=>U8,getFileIndex:()=>b1,getCurrentContextSize:()=>j7,getCoreHeadlessToolNames:()=>a4,getCoreDefaultEnabledToolIds:()=>N5,getCoreBuiltinToolCatalog:()=>i$,getCoreAcpToolNames:()=>S5,getClineDefaultSystemPrompt:()=>cE,generateWorkspaceInfoWithDiagnostics:()=>R6,generateWorkspaceInfo:()=>_8,formatRulesForSystemPrompt:()=>P8,formatProviderOAuthApiKey:()=>BZ,formatDisplayUserInput:()=>tE,filterExtensionToolRegistrations:()=>_5,filterDisabledTools:()=>I1,filterDisabledPluginPaths:()=>L5,fetchClineRecommendedModels:()=>_j,executeClineAccountAction:()=>F9,ensureHubWebSocketServer:()=>DQ,ensureHubServer:()=>dK,ensureDetachedHubServer:()=>EB,ensureCustomProvidersLoaded:()=>bQ,ensureCompatibleLocalHubUrl:()=>_2,enrichPromptWithMentions:()=>a2,emptyWorkspaceManifest:()=>aE,emptyStoredProviderSettings:()=>L$,discoverPluginModulePaths:()=>Y6,disablePluginMcpServersInSettings:()=>l3,deriveSubsessionStatus:()=>t4,deleteLocalProvider:()=>xQ,defineLlmsConfig:()=>Oj,createWorkflowsConfigDefinition:()=>h6,createUserInstructionConfigService:()=>_$,createToolPoliciesWithPreset:()=>G5,createTool:()=>nE,createTeamName:()=>MQ,createSubprocessHooks:()=>jQ,createSpawnAgentTool:()=>A$,createSkillsConfigDefinition:()=>E6,createSessionHost:()=>p8,createRuntimeHost:()=>p8,createRulesConfigDefinition:()=>b6,createRemoteConfigSessionMessagesArtifactUploader:()=>y3,createProviderConfig:()=>k7,createOpenTelemetryTelemetryService:()=>DJ,createOAuthClientCallbacks:()=>T8,createMcpTools:()=>y8,createLocalHubScheduleRuntimeHandlers:()=>UQ,createLlmsSdk:()=>qj,createInitialAccumulatedUsage:()=>G0,createInMemoryHubOwnerContext:()=>TB,createHubServerUrl:()=>j1,createHubAuthToken:()=>c9,createHookConfigFileHooks:()=>A6,createHookConfigFileExtension:()=>D8,createHookAuditHooks:()=>F8,createDisabledMcpToolPolicy:()=>m6,createDisabledMcpToolPolicies:()=>E9,createDelegatedAgentConfigProvider:()=>H$,createDelegatedAgent:()=>B$,createDefaultToolsWithPreset:()=>F5,createDefaultTools:()=>X$,createDefaultMcpServerClientFactory:()=>S8,createDefaultExecutors:()=>s2,createCoreSettingsService:()=>K2,createCoreSessionSnapshot:()=>F1,createContributionRegistry:()=>iE,createContextCompactionPrepareTurn:()=>P4,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,createConfiguredAgentTools:()=>v8,createClineTelemetryServiceMetadata:()=>rE,createClineTelemetryServiceConfig:()=>pE,createBuiltinTools:()=>n$,createAgentTeamsTools:()=>r$,createAgentRuntime:()=>fb,createAgentHooksExtension:()=>K8,connectToHub:()=>VQ,completeClineDeviceAuth:()=>jZ,clearPrivateModelsCatalogCache:()=>E7,clearLiveModelsCatalogCache:()=>y7,clearHubDiscovery:()=>y0,captureWorkspacePathResolved:()=>pj,captureWorkspaceInitialized:()=>bJ,captureWorkspaceInitError:()=>hJ,captureToolUsage:()=>mJ,captureTokenUsage:()=>xJ,captureTaskRestarted:()=>IJ,captureTaskCreated:()=>kJ,captureTaskCompleted:()=>V4,captureSubagentExecution:()=>B4,captureSkillUsed:()=>vJ,captureSdkError:()=>lE,captureProviderConfigured:()=>rj,captureProviderApiError:()=>H4,captureModeSwitch:()=>gJ,captureMentionUsed:()=>uJ,captureMentionSearchResults:()=>lJ,captureMentionFailed:()=>dJ,captureHookDiscovery:()=>rJ,captureExtensionActivated:()=>lj,captureDiffEditFailure:()=>cJ,captureConversationTurnEvent:()=>g2,captureCompactionSkipped:()=>nJ,captureCompactionExecuted:()=>iJ,captureAuthSucceeded:()=>N1,captureAuthStarted:()=>P1,captureAuthLoggedOut:()=>e1,captureAuthFailed:()=>w1,captureAgentTeamCreated:()=>pJ,captureAgentCreated:()=>$$,buildWorkspaceMetadata:()=>z6,buildTeamProgressSummary:()=>c8,buildSdkErrorProperties:()=>uE,buildRemoteConfigSessionBlobUploadMetadata:()=>zQ,buildDelegatedAgentConfig:()=>l$,buildConfiguredAgentToolName:()=>XJ,buildConfiguredAgentToolDescriptors:()=>YJ,bootstrapAgentTeams:()=>Q8,authorizeMcpServerOAuth:()=>w9,addLocalProvider:()=>Zj,accumulateUsageTotals:()=>V0,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q6,UnifiedConfigFileWatcher:()=>f2,ToolPresets:()=>c0,TelemetryService:()=>o8,TelemetryLoggerSink:()=>FJ,TEAM_TOOL_NAMES:()=>J8,SubprocessSandbox:()=>V8,StoredProviderSettingsSchema:()=>L8,StoredProviderSettingsEntrySchema:()=>H9,SqliteTeamStore:()=>y2,SqliteSessionStore:()=>U1,SessionVersioningService:()=>y$,SessionVersioningError:()=>k0,SessionSource:()=>U0,SessionNotFoundError:()=>u1,SapSettingsSchema:()=>j9,SKILLS_CONFIG_DIRECTORY_NAME:()=>M6,SESSION_STATUSES:()=>e4,SESSION_NOT_FOUND_ERROR_CODE:()=>G2,SDK_ERROR_TELEMETRY_EVENT:()=>Wb,RpcClineAccountService:()=>O6,RemoteRuntimeHost:()=>x8,ReasoningSettingsSchema:()=>J9,RULES_CONFIG_DIRECTORY_NAME:()=>O9,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>LQ,ProviderSettingsSchema:()=>R$,ProviderSettingsManager:()=>_1,ProviderProtocolSchema:()=>t5,ProviderIdSchema:()=>U6,ProviderClientSchema:()=>e5,OpenTelemetryProvider:()=>t8,OcaSettingsSchema:()=>f9,OPENAI_COMPATIBLE_PROVIDERS:()=>G6,NodeHubClient:()=>f1,NoOpFeatureFlagsProvider:()=>q2,NativeHubTransportAdapter:()=>OJ,ModelCatalogSettingsSchema:()=>X9,LocalRuntimeHost:()=>L1,Llms:()=>vE,InMemoryWorkspaceManager:()=>O8,InMemoryMcpManager:()=>A2,HubUIClient:()=>K3,HubTransportError:()=>q0,HubSessionClient:()=>A3,HubServerTransport:()=>J4,HubScheduleService:()=>s8,HubScheduleCommandService:()=>a8,HubRuntimeHost:()=>r1,HubCommandError:()=>k8,HookEventPayloadSchema:()=>WQ,HookEventNameSchema:()=>ZQ,HookConfigFileName:()=>G8,HOOK_CONFIG_FILE_EVENT_MAP:()=>H6,HOOKS_CONFIG_DIRECTORY_NAME:()=>m5,GlobalSettingsSchema:()=>l4,GcpSettingsSchema:()=>Z9,FileTeamPersistenceStore:()=>cQ,FeatureFlagsService:()=>M2,FeatureFlagDefaultValue:()=>oE,FEATURE_FLAGS:()=>sE,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>iQ,DefaultToolNames:()=>K0,DefaultRuntimeBuilder:()=>W4,DefaultLlmsSdk:()=>NJ,DEFAULT_MODELS_CATALOG_URL:()=>i5,DEFAULT_HUB_PORT:()=>wW,DEFAULT_HUB_PATHNAME:()=>SW,DEFAULT_HUB_HOST:()=>NW,CoreSettingsService:()=>O$,CoreSessionService:()=>z1,ContributionRegistry:()=>dE,ClineCore:()=>KJ,ClineAccountService:()=>_6,ChatViewStateSchema:()=>zj,ChatSummarySchema:()=>rQ,ChatSessionStatusSchema:()=>dQ,ChatSessionConfigSchema:()=>uQ,ChatMessageSchema:()=>pQ,ChatMessageRoleSchema:()=>lQ,CORE_TELEMETRY_EVENTS:()=>x,CORE_BUILD_VERSION:()=>Lj,BrowserWebSocketHubAdapter:()=>_J,BUILT_IN_PROVIDER_IDS:()=>b7,BUILT_IN_PROVIDER:()=>D6,AzureSettingsSchema:()=>W9,AwsSettingsSchema:()=>Q9,AuthSettingsSchema:()=>$9,AgentTeamsRuntime:()=>T2,AgentTeam:()=>l8,Agent:()=>jb,ALL_DEFAULT_TOOL_NAMES:()=>W$});q(M,kn);import*as vE from"@cline/llms";import{buildClineSystemPrompt as cE,buildSdkErrorProperties as uE,ContributionRegistry as dE,captureSdkError as lE,createClineTelemetryServiceConfig as pE,createClineTelemetryServiceMetadata as rE,createContributionRegistry as iE,createTool as nE,emptyWorkspaceManifest as aE,FEATURE_FLAGS as sE,FeatureFlagDefaultValue as oE,formatDisplayUserInput as tE,noopBasicLogger as eE,normalizeSdkError as $b,normalizeUserInput as Jb,parseUserCommandEnvelope as Qb,registerDisposable as Zb,SDK_ERROR_TELEMETRY_EVENT as Wb}from"@cline/shared";import"@cline/shared/storage";var uV={};w(uV,{isClineAccountActionRequest:()=>G9,executeClineAccountAction:()=>F9,RpcClineAccountService:()=>O6,ClineAccountService:()=>_6});function s_($){if(typeof $!=="object"||$===null||!("error"in $))return;let J=$.error;return typeof J==="string"&&J.trim()?J:void 0}function cV($,J,Q){let Z=s_(Q);if(Z)return Z;let W=J.trim();if(W){let j=W.length>200?`${W.slice(0,200)}...`:W;return`Cline account request failed with status ${$}: ${j}`}return`Cline account request failed with status ${$}`}class _6{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let J=$.apiBaseUrl.trim();if(!J)throw Error("apiBaseUrl is required");this.apiBaseUrl=J,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 J=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(J)}/balance`)}async fetchUsageTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/usages`)).items??[]}async fetchPaymentTransactions($){let J=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(J)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}`)}async fetchOrganizationBalance($){let J=$.trim();if(!J)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(J)}/balance`)}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");let Q=await this.resolveOrganizationMemberId(J,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(J)}/members/${encodeURIComponent(Q)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let J=$?.trim();if(J)return J;let Z=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Z)return Z;let W=await this.fetchMe();if(!W.id?.trim())throw Error("Unable to resolve current user id");return W.id}async resolveOrganizationMemberId($,J){let Q=J?.trim();if(Q)return Q;let W=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(W)return W;let f=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!f?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return f}async request($,J){let Q=(await this.getAuthTokenFn())?.trim();if(!Q)throw Error("No Cline account auth token found");let Z=this.getHeadersFn?await this.getHeadersFn():{},W=new AbortController,j=setTimeout(()=>W.abort(),this.requestTimeoutMs);try{let f=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:J?.method??"GET",headers:{Authorization:`Bearer ${Q}`,"Content-Type":"application/json",...Z??{}},body:J?.body!==void 0?JSON.stringify(J.body):void 0,signal:W.signal});if(f.status===204||J?.expectNoContent){if(!f.ok)throw Error(`Cline account request failed with status ${f.status}`);return}let X=await f.text(),Y;if(X.trim())try{Y=JSON.parse(X)}catch{if(!f.ok)throw Error(cV(f.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!f.ok)throw Error(cV(f.status,X,Y));if(typeof Y==="object"&&Y!==null){let V=Y;if(typeof V.success==="boolean"){if(!V.success)throw Error(V.error||"Cline account request failed");if(V.data!==void 0)return V.data}}if(Y===void 0||Y===null)throw Error("Cline account response payload was empty");return Y}finally{clearTimeout(j)}}}function G9($){return $.action==="clineAccount"}async function F9($,J){switch($.operation){case"fetchMe":return J.fetchMe();case"fetchBalance":return J.fetchBalance($.userId);case"fetchUsageTransactions":return J.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return J.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return J.fetchUserOrganizations();case"fetchOrganizationBalance":return J.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return J.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await J.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return J.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class O6{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 J=$.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:J})}async fetchOrganizationUsageTransactions($){let J=$.organizationId.trim();if(!J)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:J,...$.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 dV={};w(dV,{createOAuthClientCallbacks:()=>T8});function T8($){return{onAuth:({url:J,instructions:Q})=>{if($.onOutput?.(Q??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(J)).catch((Z)=>{$.onOpenUrlError?.({url:J,error:Z})})}catch(Z){$.onOpenUrlError?.({url:J,error:Z})}$.onOutput?.(J)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}var yA={};w(yA,{ClineCore:()=>KJ});function lV($){if($===!0)return{};if(!$)return;return $}function pV($){if($==="user")return"global";return $}class v7{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let J=this.getService().ingestEvent($);return{event:J.event,duplicate:J.duplicate,matchedSpecIds:J.matchedSpecs.map((Q)=>Q.specId),queuedRuns:J.queuedRuns,suppressions:J.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function rV($){let{host:J}=$;return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||U0.CLI,interactive:!1,config:{providerId:R8(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:e_(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content),delivery:Z.delivery});if(!W)throw Error("ClineCore automation runtime returned no result");return{result:t_(W)}},async abortSession(Q){return await J.abort(Q,Error("ClineCore automation abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}function D9($){let J=o_($.automationService,$.automation),Q=$.context?.client??($.clientName?{name:$.clientName}:void 0),Z=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),W=$.context?.logger??$.logger,j=$.context?.telemetry??$.telemetry;if(!J&&!Q&&!Z&&!W&&!j)return $.context;return{...$.context??{},...Q?{client:Q}:{},...Z?{user:Z}:{},...W?{logger:W}:{},...j?{telemetry:j}:{},...J?{automation:J}:{}}}function o_($,J){if(!$)return;return{ingestEvent:(Q)=>{J.ingestEvent(Q)}}}function t_($){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((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function e_($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}var IH={};w(IH,{createCoreSettingsService:()=>K2,CoreSettingsService:()=>O$});import{existsSync as h9}from"node:fs";import{basename as bH,isAbsolute as PT,relative as NT}from"node:path";var XH={};w(XH,{resolveWorkflowsConfigSearchPaths:()=>y6,resolveSkillsConfigSearchPaths:()=>S6,resolveRulesConfigSearchPaths:()=>C6,parseWorkflowConfigFromMarkdown:()=>w6,parseSkillConfigFromMarkdown:()=>P6,parseRuleConfigFromMarkdown:()=>N6,createWorkflowsConfigDefinition:()=>h6,createUserInstructionConfigService:()=>_$,createSkillsConfigDefinition:()=>E6,createRulesConfigDefinition:()=>b6,WORKFLOWS_CONFIG_DIRECTORY_NAME:()=>q6,UnifiedConfigFileWatcher:()=>f2,SKILLS_CONFIG_DIRECTORY_NAME:()=>M6,RULES_CONFIG_DIRECTORY_NAME:()=>O9});import{createHash as $O}from"node:crypto";import{watch as JO}from"node:fs";import{readdir as QO,readFile as ZO}from"node:fs/promises";import{join as WO}from"node:path";function jO($){return $O("sha1").update($).digest("hex")}function aV($){return Boolean($&&typeof $==="object"&&"code"in $)}function iV($){return aV($)&&$.code==="ENOENT"}function nV($){return aV($)&&($.code==="EACCES"||$.code==="EPERM")}class f2{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($,J){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=J?.debounceMs??75,this.emitParseErrors=J?.emitParseErrors??!1;for(let Q of $){if(this.definitionsByType.has(Q.type))throw Error(`Duplicate unified config definition type '${Q.type}'.`);this.definitionsByType.set(Q.type,Q),this.recordsByType.set(Q.type,new Map),this.discoveredDirectoriesByType.set(Q.type,new Set);for(let Z of Q.directories){let W=this.baseTypesByDirectory.get(Z);if(W)W.add(Q.type);else this.baseTypesByDirectory.set(Z,new Set([Q.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let J=this.definitionsByType.get($);if(!J)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(J)})}getSnapshot($){let J=this.recordsByType.get($);return new Map([...J?.entries()??[]].map(([Q,Z])=>[Q,{...Z}]))}getAllSnapshots(){let $=new Map;for(let[J,Q]of this.recordsByType.entries())$.set(J,new Map([...Q.entries()].map(([Z,W])=>[Z,{...W}])));return $}emit($){for(let J of this.listeners)J($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[J,Q]of this.watchersByDirectory.entries()){if($.has(J))continue;Q.close(),this.watchersByDirectory.delete(J)}this.watchedTypesByDirectory=$;for(let J of $.keys()){if(this.watchersByDirectory.has(J))continue;try{let Q=JO(J,()=>{let Z=this.watchedTypesByDirectory.get(J);if(!Z)return;for(let W of Z)this.pendingTypes.add(W);this.scheduleFlush()});this.watchersByDirectory.set(J,Q),Q.on("error",(Z)=>{let W=this.watchedTypesByDirectory.get(J);if(!W)return;for(let j of W)this.emit({kind:"error",type:j,error:Z,filePath:J})})}catch(Q){if(!iV(Q)&&!nV(Q)){let Z=$.get(J);if(!Z)continue;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:J})}}}}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 J of $){let Q=this.definitionsByType.get(J);if(!Q)continue;await this.refreshTypeInternal(Q)}})},this.debounceMs)}async refreshTypeInternal($){let{records:J,discoveredDirectories:Q}=await this.loadDefinition($),Z=this.recordsByType.get($.type)??new Map;for(let[W,j]of Z.entries()){if(J.has(W))continue;this.emit({kind:"remove",type:$.type,id:W,filePath:j.filePath})}for(let[W,j]of J.entries()){let f=Z.get(W);if(f&&f.filePath===j.filePath&&f.fingerprint===j.fingerprint)continue;this.emit({kind:"upsert",record:{type:j.type,id:W,item:j.item,filePath:j.filePath}})}if(this.recordsByType.set($.type,J),this.discoveredDirectoriesByType.set($.type,Q),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let J=new Map,Q=new Set;for(let Z of $.directories){Q.add(Z);let W=$.discoverFiles?await $.discoverFiles(Z):await this.readDirectoryFileCandidates(Z);for(let j of W){let{fileName:f,filePath:X}=j;if(Q.add(j.directoryPath),$.includeFile&&!$.includeFile(f,X))continue;try{let Y=await ZO(X,"utf8"),V={type:$.type,directoryPath:j.directoryPath,fileName:f,filePath:X,content:Y},H=$.parseFile(V),B=$.resolveId(H,V).trim();if(!B)continue;J.set(B,{type:$.type,id:B,item:H,filePath:X,fingerprint:jO(Y)})}catch(Y){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:Y,filePath:X})}}}return{records:J,discoveredDirectories:Q}}buildDesiredTypesByDirectory(){let $=new Map;for(let[J,Q]of this.baseTypesByDirectory.entries())$.set(J,new Set(Q));for(let[J,Q]of this.discoveredDirectoriesByType.entries())for(let Z of Q){let W=$.get(Z);if(W)W.add(J);else $.set(Z,new Set([J]))}return $}async readDirectoryFileCandidates($){try{return(await QO($,{withFileTypes:!0})).filter((Q)=>Q.isFile()).map((Q)=>({directoryPath:$,fileName:Q.name,filePath:WO($,Q.name)})).sort((Q,Z)=>Q.fileName.localeCompare(Z.fileName))}catch(J){if(iV(J)||nV(J))return[];throw J}}}import{readdir as u7,readFile as fO,stat as c7}from"node:fs/promises";import{basename as v1,dirname as XO,extname as R9,join as C0,resolve as T6}from"node:path";import{AGENTS_RULES_FILE_NAME as sV,RULES_CONFIG_DIRECTORY_NAME as O9,resolveGlobalAgentsRulesPath as YO,resolveRulesConfigSearchPaths as VO,resolveSkillsConfigSearchPaths as HO,resolveWorkflowsConfigSearchPaths as BO,SKILLS_CONFIG_DIRECTORY_NAME as M6,WORKFLOWS_CONFIG_DIRECTORY_NAME as q6}from"@cline/shared/storage";import AO from"yaml";var U9="SKILL.md",KO="managed.json",GO=new Set([".md",".markdown",".txt"]);function d7($){return $.trim().toLowerCase()}function M8($){let J=$;return J?.code==="ENOENT"||J?.code==="EACCES"||J?.code==="EPERM"||J?.code==="ELOOP"}function z9($){return GO.has(R9($).toLowerCase())}function oV($){let J=[],Q=new Set;for(let Z of $){let W=T6(Z);if(Q.has(W))continue;Q.add(W),J.push(Z)}return J}function FO($){let J=[...$?.directories??S6($?.workspacePath)];if($?.pluginSkillDirectories)J.push(...$.pluginSkillDirectories);else if($?.includePluginSkills)J.push(...YV({pluginPaths:$.pluginPaths,workspacePath:$.workspacePath,cwd:$.cwd??$.workspacePath}));return oV(J)}async function l7($){try{let J=await u7($,{withFileTypes:!0}),Q=[];for(let Z of J){if(!Z.isDirectory())continue;let W=C0($,Z.name),j=C0(W,KO);try{let f=await fO(j,"utf8"),X=JSON.parse(f);if(X&&typeof X==="object")Q.push(W)}catch(f){if(M8(f))continue;if(f?.name==="SyntaxError")continue;throw f}}return Q.sort((Z,W)=>Z.localeCompare(W))}catch(J){if(M8(J))return[];throw J}}function p7($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q;try{let j=AO.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}catch(j){let f=j instanceof Error?j.message:String(j);return{data:{},body:$,hadFrontmatter:!0,parseError:f}}}function L9($,J,Q){if($===void 0||$===null){if(Q)throw Error(`Missing required frontmatter field '${J}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${J}' must be a string.`);let Z=$.trim();if(!Z&&Q)throw Error(`Frontmatter field '${J}' cannot be empty.`);return Z||void 0}function q8($,J){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${J}' must be a boolean.`);return $}function DO($,J){if(v1($.filePath).toLowerCase()!==sV.toLowerCase())return v1($.filePath,R9($.filePath));if(J&&T6($.filePath)===T6(J,sV))return"Workspace AGENTS.md";if(T6($.filePath)===T6(YO()))return"Global AGENTS.md";return v1($.filePath,R9($.filePath))}function P6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in skill file.");let X=L9(Q.name,"name",!1)??J.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:L9(Q.description,"description",!1),disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function N6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in rule file.");let f=L9(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing rule name.");return{name:f,disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function w6($,J){let{data:Q,body:Z,parseError:W}=p7($);if(W)throw Error(`Failed to parse YAML frontmatter: ${W}`);let j=Z.trim();if(!j)throw Error("Missing instructions body in workflow file.");let f=L9(Q.name,"name",!1)??J.trim();if(!f)throw Error("Missing workflow name.");return{name:f,disabled:q8(Q.disabled,"disabled")??(q8(Q.enabled,"enabled")===!1?!0:void 0),instructions:j,frontmatter:Q}}function S6($){return HO($)}function C6($){return VO($)}function y6($){return BO($)}async function tV($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>tV(C0(Z,M6))))).flat()}try{let J=await u7($,{withFileTypes:!0}),Q=[];for(let Z of J){if(Z.isFile()&&Z.name===U9){Q.push({directoryPath:$,fileName:Z.name,filePath:C0($,Z.name)});continue}let W=C0($,Z.name);if(Z.isDirectory()||Z.isSymbolicLink()&&await c7(W).then((f)=>f.isDirectory()).catch((f)=>{if(M8(f))return!1;throw f}))Q.push({directoryPath:W,fileName:U9,filePath:C0(W,U9)})}return Q}catch(J){if(M8(J))return[];throw J}}async function _9($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>_9(C0(Z,"rules.md"))))).flat()}try{if((await c7($)).isFile())return[{directoryPath:XO($),fileName:v1($),filePath:$}]}catch(J){if(!M8(J))throw J}try{let Q=(await u7($,{withFileTypes:!0})).filter((W)=>W.isFile()&&z9(W.name)).map((W)=>({directoryPath:$,fileName:W.name,filePath:C0($,W.name)})),Z=C0($,"AGENTS.md");try{if((await c7(Z)).isFile()){if(!Q.some((f)=>f.fileName==="AGENTS.md"))Q.push({directoryPath:$,fileName:"AGENTS.md",filePath:Z})}}catch{}return Q}catch(J){if(M8(J))return[];throw J}}async function UO($){if(v1($)===".cline"){let J=await l7($);return(await Promise.all(J.map((Z)=>_9(C0(Z,q6))))).flat()}return _9($)}function E6($){let J=FO($),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"skill",directories:Q?oV([...J,Q]):J,discoverFiles:tV,includeFile:(Z)=>Z===U9,parseFile:(Z)=>P6(Z.content,v1(Z.directoryPath)),resolveId:(Z)=>d7(Z.name)}}function b6($){let J=$?.directories??C6($?.workspacePath),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"rule",directories:Q?[...J,Q]:J,discoverFiles:_9,includeFile:(Z,W)=>Z===".clinerules"||z9(Z)||z9(W),parseFile:(Z)=>N6(Z.content,DO(Z,$?.workspacePath)),resolveId:(Z)=>d7(Z.name)}}function h6($){let J=$?.directories??y6($?.workspacePath),Q=$?.workspacePath?C0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:Q?[...J,Q]:J,discoverFiles:UO,includeFile:(Z)=>z9(Z),parseFile:(Z)=>w6(Z.content,v1(Z.filePath,R9(Z.filePath))),resolveId:(Z)=>d7(Z.name)}}function eV($){let J=[E6($?.skills),b6($?.rules),h6($?.workflows)];return new f2(J,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as $H}from"@cline/shared";function RO($,J){if($.description?.trim())return $H($.description,".");if(J==="workflow")return;return $H($.instructions,".")}function zO($){return $.disabled!==!0}function JH($,J){return[...$.getSnapshot(J).entries()].map(([Q,Z])=>({id:Q,record:Z})).filter(({record:Q})=>zO(Q.item)).map(({id:Q,record:Z})=>({id:Q,name:Z.item.name,instructions:Z.item.instructions,description:RO(Z.item,J),kind:J})).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function k6($){let J=new Map;for(let Q of[...JH($,"workflow"),...JH($,"skill")])if(!J.has(Q.name))J.set(Q.name,Q);return[...J.values()].sort((Q,Z)=>Q.name.localeCompare(Z.name))}function QH($,J){if(!$.startsWith("/")||$.length<2)return $;let Q=$.match(/^\/(\S+)/);if(!Q)return $;let Z=Q[1];if(!Z)return $;let W=Z.length+1,j=$.slice(W),f=k6(J).find((X)=>X.name===Z);return f?`${f.instructions}${j}`:$}var WH={};w(WH,{mergeRulesForSystemPrompt:()=>N8,loadRulesForSystemPromptFromWatcher:()=>r7,listEnabledRulesFromWatcher:()=>ZH,isRuleEnabled:()=>T9,formatRulesForSystemPrompt:()=>P8});function T9($){return $.disabled!==!0}function P8($){if($.length===0)return"";return`
193
193
 
194
194
  # Rules
195
195
  ${$.map((Q)=>`## ${Q.name}
@@ -197,24 +197,24 @@ ${Q.instructions}`).join(`
197
197
 
198
198
  `)}`}function N8($,J){let Q=$?.trim(),Z=J?.trim();if(Q&&Z)return`${Q}
199
199
 
200
- ${Z}`;return Q||Z||void 0}function WH($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(TQ).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function r7($){return P8(WH($))}function MQ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function LO($){if(!$||$.length===0)return;let J=$.map(MQ).filter((Q)=>Q.length>0);return J.length>0?new Set(J):void 0}function _O($,J,Q){if(!Q)return!0;let Z=MQ($),W=MQ(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function I6($,J){let Q=LO(J);return[...$.getSnapshot("skill").entries()].map(([W,j])=>{let f=j.item;return{id:W,name:f.name.trim(),description:f.description?.trim(),disabled:f.disabled===!0,skill:f}}).filter((W)=>_O(W.id,W.name,Q))}function OO($,J){return I6($,J).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,Z)=>Q.localeCompare(Z))}function TO($,J,Q){let Z=MQ(J);if(!Z)return{error:"Missing skill name."};let W=I6($,Q),j=W.find((H)=>H.id===Z);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let f=Z.includes(":")?Z.split(":").at(-1)??Z:Z,X=W.filter(({id:H})=>{if(H===f)return!0;return H.endsWith(`:${f}`)}),Y=X.filter(({skill:H})=>H.disabled!==!0);if(Y.length===1){let{id:H,skill:B}=Y[0];return{id:H,skill:B}}if(Y.length>1)return{error:`Skill "${J}" is ambiguous. Use one of: ${Y.map(({id:H})=>H).join(", ")}`};if(X.length===1){let{skill:H}=X[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${J}" is ambiguous, and all matches are disabled: ${X.map(({id:H})=>H).join(", ")}`};let V=OO($,Q);return{error:V.length>0?`Skill "${J}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function i7($,J=Promise.resolve(),Q){let Z=new Set,W=async(j,f)=>{await J;let X=TO($,j,Q);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Z.has(Y))return`Skill "${V.name}" is already running.`;Z.add(Y);try{let H=f?.trim(),B=H?`
200
+ ${Z}`;return Q||Z||void 0}function ZH($){return[...$.getSnapshot("rule").values()].map((Q)=>Q.item).filter(T9).sort((Q,Z)=>Q.name.localeCompare(Z.name))}function r7($){return P8(ZH($))}function M9($){return $.trim().replace(/^\/+/,"").toLowerCase()}function LO($){if(!$||$.length===0)return;let J=$.map(M9).filter((Q)=>Q.length>0);return J.length>0?new Set(J):void 0}function _O($,J,Q){if(!Q)return!0;let Z=M9($),W=M9(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function I6($,J){let Q=LO(J);return[...$.getSnapshot("skill").entries()].map(([W,j])=>{let f=j.item;return{id:W,name:f.name.trim(),description:f.description?.trim(),disabled:f.disabled===!0,skill:f}}).filter((W)=>_O(W.id,W.name,Q))}function OO($,J){return I6($,J).filter((Q)=>!Q.disabled).map((Q)=>Q.name.trim()).filter((Q)=>Q.length>0).sort((Q,Z)=>Q.localeCompare(Z))}function TO($,J,Q){let Z=M9(J);if(!Z)return{error:"Missing skill name."};let W=I6($,Q),j=W.find((H)=>H.id===Z);if(j){let{skill:H}=j;if(H.disabled===!0)return{error:`Skill "${H.name}" is configured but disabled.`};return{id:j.id,skill:H}}let f=Z.includes(":")?Z.split(":").at(-1)??Z:Z,X=W.filter(({id:H})=>{if(H===f)return!0;return H.endsWith(`:${f}`)}),Y=X.filter(({skill:H})=>H.disabled!==!0);if(Y.length===1){let{id:H,skill:B}=Y[0];return{id:H,skill:B}}if(Y.length>1)return{error:`Skill "${J}" is ambiguous. Use one of: ${Y.map(({id:H})=>H).join(", ")}`};if(X.length===1){let{skill:H}=X[0];return{error:`Skill "${H.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${J}" is ambiguous, and all matches are disabled: ${X.map(({id:H})=>H).join(", ")}`};let V=OO($,Q);return{error:V.length>0?`Skill "${J}" not found. Available skills: ${V.join(", ")}`:"No skills are currently available."}}function i7($,J=Promise.resolve(),Q){let Z=new Set,W=async(j,f)=>{await J;let X=TO($,j,Q);if("error"in X)return X.error;let{id:Y,skill:V}=X;if(Z.has(Y))return`Skill "${V.name}" is already running.`;Z.add(Y);try{let H=f?.trim(),B=H?`
201
201
  <command-args>${H}</command-args>`:"",A=V.description?.trim()?`Description: ${V.description.trim()}
202
202
 
203
203
  `:"";return`<command-name>${V.name}</command-name>${B}
204
204
  <command-instructions>
205
205
  ${A}${V.instructions}
206
- </command-instructions>`}finally{Z.delete(Y)}};return Object.defineProperty(W,"configuredSkills",{get:()=>I6($,Q).map(({skill:j,...f})=>f),enumerable:!0,configurable:!1}),W}function fH($){let J=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Z)=>Boolean(Z))},async setup(Z){if(await J,$.includeRules)Z.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>r7($.watcher)});if($.registerSkillsTool)Z.registerTool(v$(i7($.watcher,J,$.allowedSkillNames)));for(let W of k6($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Z.registerCommand({name:W.name,description:W.description,handler:(j)=>{let f=j.trim();return f?`${W.instructions}
206
+ </command-instructions>`}finally{Z.delete(Y)}};return Object.defineProperty(W,"configuredSkills",{get:()=>I6($,Q).map(({skill:j,...f})=>f),enumerable:!0,configurable:!1}),W}function jH($){let J=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Z)=>Boolean(Z))},async setup(Z){if(await J,$.includeRules)Z.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>r7($.watcher)});if($.registerSkillsTool)Z.registerTool(v$(i7($.watcher,J,$.allowedSkillNames)));for(let W of k6($.watcher).filter((j)=>j.kind==="skill"&&$.includeSkills||j.kind==="workflow"&&$.includeWorkflows))Z.registerCommand({name:W.name,description:W.description,handler:(j)=>{let f=j.trim();return f?`${W.instructions}
207
207
 
208
- ${f}`:W.instructions}})}}}class XH{watcher;ready;stopped=!1;constructor($){this.watcher=$H($)}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(([J,Q])=>({type:$,id:J,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return k6(this.watcher)}resolveRuntimeSlashCommand($){return ZH($,this.watcher)}hasConfiguredSkills($){return I6(this.watcher,$).some((J)=>!J.disabled)}createSkillsExecutor($){return i7(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return fH({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function _$($){return new XH($)}import{readFile as MO,writeFile as qO}from"node:fs/promises";import HH from"yaml";function PO($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q,j=HH.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}function VH($,J){return`---
209
- ${HH.stringify($).trimEnd()}
208
+ ${f}`:W.instructions}})}}}class fH{watcher;ready;stopped=!1;constructor($){this.watcher=eV($)}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(([J,Q])=>({type:$,id:J,filePath:Q.filePath,item:Q.item}))}listRuntimeCommands(){return k6(this.watcher)}resolveRuntimeSlashCommand($){return QH($,this.watcher)}hasConfiguredSkills($){return I6(this.watcher,$).some((J)=>!J.disabled)}createSkillsExecutor($){return i7(this.watcher,(this.ready??Promise.resolve()).catch(()=>{}),$)}createExtension($){return jH({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function _$($){return new fH($)}import{readFile as MO,writeFile as qO}from"node:fs/promises";import VH from"yaml";function PO($){let J=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,Q=$.match(J);if(!Q)return{data:{},body:$,hadFrontmatter:!1};let[,Z,W]=Q,j=VH.parse(Z);return{data:j&&typeof j==="object"&&!Array.isArray(j)?j:{},body:W,hadFrontmatter:!0}}function YH($,J){return`---
209
+ ${VH.stringify($).trimEnd()}
210
210
  ---
211
- ${J}`}function NO($,J){let{data:Q,body:Z,hadFrontmatter:W}=PO($);if(!W&&J)return $;if(J){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return Z;return VH(Q,Z)}return Q.disabled=!0,VH(Q,Z)}async function BH({filePath:$,enabled:J}){let Q=await MO($,"utf8"),Z=NO(Q,J);return await qO($,Z),{filePath:$,enabled:J,disabled:!J}}var CH={};w(CH,{updateMcpServerOAuthState:()=>H2,setMcpServerDisabled:()=>Y2,resolvePluginMcpServerRegistrations:()=>CQ,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>B0,registerMcpServersFromSettingsFile:()=>B2,normalizePluginMcpServerRegistration:()=>e7,loadMcpSettingsFile:()=>X2,listMcpServerOAuthStatuses:()=>g6,hasMcpSettingsFile:()=>c1,getMcpServerOAuthState:()=>V2,createMcpTools:()=>y8,createDisabledMcpToolPolicy:()=>m6,createDisabledMcpToolPolicies:()=>EQ,createDefaultMcpServerClientFactory:()=>S8,authorizeMcpServerOAuth:()=>wQ,InMemoryMcpManager:()=>A2});import{spawn as $T}from"node:child_process";import{StringDecoder as MH}from"node:string_decoder";import{UnauthorizedError as LH}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as JT}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as lO}from"node:crypto";import{UnauthorizedError as pO}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as rO}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as iO}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as nO}from"@modelcontextprotocol/sdk/client/streamableHttp.js";qQ();var aO="/mcp/oauth/callback",sO=[1456,1457,1458],oO=300000;function tO($){if($ instanceof Error){let J=$.message.trim();if(J.length>0)return J}return String($)}function eO($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function NQ($){let J={};try{J=V2($.serverName,{filePath:$.settingsPath})??{}}catch{J={}}let Q,Z,W=async(f)=>{let X=w8(f(J))??{};try{J=H2($.serverName,()=>X,{filePath:$.settingsPath})}catch{J=X}};return{provider:{get redirectUrl(){return J.redirectUrl??$.redirectUrl},get clientMetadata(){return eO(J.redirectUrl??$.redirectUrl)},state:()=>{return Z=lO(),Z},clientInformation:()=>J.clientInformation,saveClientInformation:async(f)=>{await W((X)=>({...X,clientInformation:f,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>J.tokens,saveTokens:async(f)=>{await W((X)=>({...X,tokens:f,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(f)=>{Q=f.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(f)=>{await W((X)=>({...X,codeVerifier:f,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!J.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return J.codeVerifier},invalidateCredentials:async(f)=>{await W((X)=>{if(f==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...f==="client"?{clientInformation:void 0}:{},...f==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...f==="verifier"?{codeVerifier:void 0}:{},...f==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(f)=>{await W((X)=>({...X,discoveryState:f}))},discoveryState:()=>J.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>Z,resetInteractiveState:async()=>{await W((f)=>({...f,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(f)=>{await W((X)=>({...X,lastError:f}))},clearError:async()=>{await W((f)=>({...f,lastError:void 0}))}}}function PQ($){let J=$.registration.transport;if(J.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=J.headers?{headers:J.headers}:void 0;if(J.type==="sse")return new iO(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new nO(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function zH($){return new rO({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function wQ($){let J=$.serverName.trim();if(!J)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (qQ(),RH)),Z=Q({filePath:$.filePath}).find((Y)=>Y.name===J);if(!Z)throw Error(`MCP server "${J}" is not configured.`);if(Z.disabled)throw Error(`MCP server "${J}" is disabled. Enable it before running OAuth.`);if(Z.transport.type==="stdio")throw Error(`MCP server "${J}" uses stdio transport and does not support OAuth browser flow.`);let W=await J1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:sO,callbackPath:$.callbackPath??aO,timeoutMs:$.timeoutMs??oO,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!W.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=NQ({settingsPath:$.filePath,serverName:J,redirectUrl:W.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await j.resetInteractiveState();let f=zH($),X;try{let Y=PQ({registration:Z,oauthProvider:j.provider,fetch:$.fetch});try{return await f.connect(Y),await f.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" is already authorized.`}}catch(V){if(!(V instanceof pO))throw V;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${J}" did not provide an authorization URL.`);let B=await W.waitForCallback();if(!B)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(B.error)throw Error(`OAuth authorization failed: ${B.error}`);if(!B.code)throw Error("OAuth callback did not include an authorization code.");let A=j.getLastOAuthState();if(!A)throw Error(`MCP server "${J}" did not start an OAuth stateful authorization flow.`);if(B.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(B.code),X=zH($);let K=PQ({registration:Z,oauthProvider:j.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" OAuth authorization completed.`}}}catch(Y){let V=tO(Y);throw await j.markError(V),Error(V)}finally{await f.close().catch(()=>{return}),await X?.close().catch(()=>{return}),W.close()}}var QT="2024-11-05",ZT=5000,WT=1500,_H="http://127.0.0.1:1456/mcp/oauth/callback";function SQ($){return $ instanceof Error?$.message:String($)}function OH($){let J=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${J.byteLength}\r
211
+ ${J}`}function NO($,J){let{data:Q,body:Z,hadFrontmatter:W}=PO($);if(!W&&J)return $;if(J){if(delete Q.disabled,Q.enabled===!1)delete Q.enabled;if(Object.keys(Q).length===0)return Z;return YH(Q,Z)}return Q.disabled=!0,YH(Q,Z)}async function HH({filePath:$,enabled:J}){let Q=await MO($,"utf8"),Z=NO(Q,J);return await qO($,Z),{filePath:$,enabled:J,disabled:!J}}var SH={};w(SH,{updateMcpServerOAuthState:()=>H2,setMcpServerDisabled:()=>Y2,resolvePluginMcpServerRegistrations:()=>C9,resolveMcpServerRegistrations:()=>A1,resolveDefaultMcpSettingsPath:()=>B0,registerMcpServersFromSettingsFile:()=>B2,normalizePluginMcpServerRegistration:()=>e7,loadMcpSettingsFile:()=>X2,listMcpServerOAuthStatuses:()=>g6,hasMcpSettingsFile:()=>c1,getMcpServerOAuthState:()=>V2,createMcpTools:()=>y8,createDisabledMcpToolPolicy:()=>m6,createDisabledMcpToolPolicies:()=>E9,createDefaultMcpServerClientFactory:()=>S8,authorizeMcpServerOAuth:()=>w9,InMemoryMcpManager:()=>A2});import{spawn as $T}from"node:child_process";import{StringDecoder as TH}from"node:string_decoder";import{UnauthorizedError as zH}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as JT}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as lO}from"node:crypto";import{UnauthorizedError as pO}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as rO}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as iO}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as nO}from"@modelcontextprotocol/sdk/client/streamableHttp.js";q9();var aO="/mcp/oauth/callback",sO=[1456,1457,1458],oO=300000;function tO($){if($ instanceof Error){let J=$.message.trim();if(J.length>0)return J}return String($)}function eO($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function N9($){let J={};try{J=V2($.serverName,{filePath:$.settingsPath})??{}}catch{J={}}let Q,Z,W=async(f)=>{let X=w8(f(J))??{};try{J=H2($.serverName,()=>X,{filePath:$.settingsPath})}catch{J=X}};return{provider:{get redirectUrl(){return J.redirectUrl??$.redirectUrl},get clientMetadata(){return eO(J.redirectUrl??$.redirectUrl)},state:()=>{return Z=lO(),Z},clientInformation:()=>J.clientInformation,saveClientInformation:async(f)=>{await W((X)=>({...X,clientInformation:f,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>J.tokens,saveTokens:async(f)=>{await W((X)=>({...X,tokens:f,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(f)=>{Q=f.toString(),await $.onAuthorizationUrl?.(Q)},saveCodeVerifier:async(f)=>{await W((X)=>({...X,codeVerifier:f,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!J.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return J.codeVerifier},invalidateCredentials:async(f)=>{await W((X)=>{if(f==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...f==="client"?{clientInformation:void 0}:{},...f==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...f==="verifier"?{codeVerifier:void 0}:{},...f==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(f)=>{await W((X)=>({...X,discoveryState:f}))},discoveryState:()=>J.discoveryState},getLastAuthorizationUrl:()=>Q,getLastOAuthState:()=>Z,resetInteractiveState:async()=>{await W((f)=>({...f,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(f)=>{await W((X)=>({...X,lastError:f}))},clearError:async()=>{await W((f)=>({...f,lastError:void 0}))}}}function P9($){let J=$.registration.transport;if(J.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let Q=J.headers?{headers:J.headers}:void 0;if(J.type==="sse")return new iO(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch});return new nO(new URL(J.url),{authProvider:$.oauthProvider,requestInit:Q,fetch:$.fetch})}function RH($){return new rO({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function w9($){let J=$.serverName.trim();if(!J)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:Q}=await Promise.resolve().then(() => (q9(),UH)),Z=Q({filePath:$.filePath}).find((Y)=>Y.name===J);if(!Z)throw Error(`MCP server "${J}" is not configured.`);if(Z.disabled)throw Error(`MCP server "${J}" is disabled. Enable it before running OAuth.`);if(Z.transport.type==="stdio")throw Error(`MCP server "${J}" uses stdio transport and does not support OAuth browser flow.`);let W=await J1({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:sO,callbackPath:$.callbackPath??aO,timeoutMs:$.timeoutMs??oO,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!W.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let j=N9({settingsPath:$.filePath,serverName:J,redirectUrl:W.callbackUrl,onAuthorizationUrl:async(Y)=>{await $.openUrl?.(Y)}});await j.resetInteractiveState();let f=RH($),X;try{let Y=P9({registration:Z,oauthProvider:j.provider,fetch:$.fetch});try{return await f.connect(Y),await f.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" is already authorized.`}}catch(V){if(!(V instanceof pO))throw V;if(!j.getLastAuthorizationUrl())throw Error(`MCP server "${J}" did not provide an authorization URL.`);let B=await W.waitForCallback();if(!B)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(B.error)throw Error(`OAuth authorization failed: ${B.error}`);if(!B.code)throw Error("OAuth callback did not include an authorization code.");let A=j.getLastOAuthState();if(!A)throw Error(`MCP server "${J}" did not start an OAuth stateful authorization flow.`);if(B.state!==A)throw Error("OAuth authorization failed: state mismatch.");await Y.finishAuth(B.code),X=RH($);let K=P9({registration:Z,oauthProvider:j.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await j.clearError(),{serverName:J,authorized:!0,message:`MCP server "${J}" OAuth authorization completed.`}}}catch(Y){let V=tO(Y);throw await j.markError(V),Error(V)}finally{await f.close().catch(()=>{return}),await X?.close().catch(()=>{return}),W.close()}}var QT="2024-11-05",ZT=5000,WT=1500,LH="http://127.0.0.1:1456/mcp/oauth/callback";function S9($){return $ instanceof Error?$.message:String($)}function _H($){let J=Buffer.from(JSON.stringify($),"utf8"),Q=Buffer.from(`Content-Length: ${J.byteLength}\r
212
212
  \r
213
- `,"utf8");return Buffer.concat([Q,J])}function TH($){return Buffer.from(`${JSON.stringify($)}
214
- `,"utf8")}class o7{buffer="";decoder=new MH("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`\r
213
+ `,"utf8");return Buffer.concat([Q,J])}function OH($){return Buffer.from(`${JSON.stringify($)}
214
+ `,"utf8")}class o7{buffer="";decoder=new TH("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`\r
215
215
  \r
216
- `);if(Q<0)break;let W=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(W[1],10),f=Q+4,X=f+j;if(this.buffer.length<X)break;J.push(this.buffer.slice(f,X)),this.buffer=this.buffer.slice(X)}return J}}class t7{buffer="";decoder=new MH("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`
217
- `);if(Q<0)break;let Z=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),Z.length>0)J.push(Z)}return J}}class qH{registration;process;nextRequestId=1;pending=new Map;framedParser=new o7;newlineParser=new t7;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"],J;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:QT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},WT),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(Z){J=Z instanceof Error?Z:Error(String(Z))}}throw J??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((J)=>typeof J?.name==="string"&&typeof J.inputSchema==="object"&&J.inputSchema!==null).map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let J=this.registration.transport;if(J.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${J.type}`);this.framedParser=new o7,this.newlineParser=new t7,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Z=$T(J.command,J.args??[],{cwd:J.cwd,env:{...process.env,...J.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=Z,Z.stdout.on("data",(W)=>this.handleStdout(W)),Z.stderr.on("data",(W)=>{if(this.process!==Z)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Z.once("error",(W)=>{if(this.process!==Z)return;this.failAllPending(Error(`MCP process error: ${SQ(W)}`))}),Z.once("exit",(W,j)=>{if(this.process!==Z)return;this.connected=!1,this.process=void 0;let f=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${j??"null"}).${f}`))})}handleStdout($){try{let J=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of J){let Z=JSON.parse(Q);if(typeof Z.id!=="number")continue;let W=this.pending.get(Z.id);if(!W)continue;if(this.pending.delete(Z.id),clearTimeout(W.timeout),Z.error){let j=Z.error.message||`MCP request failed with code ${Z.error.code??"unknown"}`;W.reject(Error(j));continue}W.resolve(Z.result)}}catch(J){this.handleProtocolFailure(J)}}handleProtocolFailure($){let J=this.process;if(!J)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${SQ($)}.${Q}`)),J.kill()}async request($,J,Q=ZT){let Z=this.process;if(!Z?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,j={jsonrpc:"2.0",id:W,method:$,...J?{params:J}:{}},f=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(W),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(W,{resolve:X,reject:Y,timeout:V})});try{Z.stdin.write(this.protocolMode==="framed"?OH(j):TH(j))}catch(X){let Y=this.pending.get(W);if(Y)clearTimeout(Y.timeout),this.pending.delete(W);throw X}return f}notify($,J){let Q=this.process;if(!Q?.stdin.writable)return;let Z={jsonrpc:"2.0",method:$,...J?{params:J}:{}};Q.stdin.write(this.protocolMode==="framed"?OH(Z):TH(Z))}failAllPending($){for(let[J,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(J),Q.reject($)}}class PH{registration;options;client;authContext;constructor($,J){this.registration=$;this.options=J}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 $=NQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??_H});this.authContext=$;try{let J=new JT({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=PQ({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await J.connect(Q),await $.clearError(),this.client=J}catch(J){let Q=J instanceof LH?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):SQ(J);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(J){return await this.handleOperationError(J)}}async callTool($){let J=await this.ensureConnectedClient();try{return await J.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let J=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${J} Run authorizeMcpServerOAuth for this server.`;return`${J} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let J=this.authContext??NQ({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??_H}),Q=$ instanceof LH?this.formatUnauthorizedMessage(J.getLastAuthorizationUrl()):SQ($);throw await J.markError(Q),Error(Q)}}function S8($={}){return(J)=>J.transport.type==="stdio"?new qH(J):new PH(J,$)}qQ();function l0(){return Date.now()}function jT($){return $.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}class A2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let J=this.servers.get($.name);if(!J){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:l0()});return}let Q=JSON.stringify(J.registration.transport)!==JSON.stringify($.transport);if(J.registration={...$},J.updatedAt=l0(),Q)await this.disconnectState(J),J.client=void 0,J.toolCache=void 0,J.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.connectState(J)})}async disconnectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J)})}async setServerDisabled($,J){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:J},Q.updatedAt=l0(),J)await this.disconnectState(Q)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,J)=>$.name.localeCompare(J.name))}async listTools($){let J=this.requireServer($),Q=J.toolCacheUpdatedAt??0;if(J.toolCache&&l0()-Q<=this.toolsCacheTtlMs)return J.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let J=this.requireServer($),Z=await(await this.ensureConnectedClient(J)).listTools(),W=jT(Z);return J.toolCache=W,J.toolCacheUpdatedAt=l0(),J.updatedAt=l0(),W})}async callTool($){return this.runExclusive($.serverName,async()=>{let J=this.requireServer($.serverName),Q=await this.ensureConnectedClient(J);return J.updatedAt=l0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let J of $)await this.unregisterServer(J)}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=l0();try{let J=$.client??await this.clientFactory($.registration);await J.connect(),$.client=J,$.status="connected",$.lastError=void 0,$.updatedAt=l0()}catch(J){throw $.status="disconnected",$.lastError=J instanceof Error?J.message:String(J),$.updatedAt=l0(),J}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=l0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=l0()}}requireServer($){let J=this.servers.get($);if(!J)throw Error(`Unknown MCP server: ${$}`);return J}async runExclusive($,J){let Q=this.operationLocks.get($)??Promise.resolve(),Z,W=new Promise((f)=>{Z=f}),j=Q.catch(()=>{return}).then(()=>W);this.operationLocks.set($,j),await Q.catch(()=>{return});try{return await J()}finally{if(Z?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function C8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function NH($){return C8($)&&Object.values($).every((J)=>typeof J==="string")}function fT($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function XT($){if(!C8($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function YT($){let J=$.env?Object.entries($.env):[];if(J.length===0)return{ok:!0};let Q={};for(let[Z,W]of J){if(typeof W==="string"){Q[Z]=W;continue}let j=W.fromEnv?.trim()||Z,f=process.env[j];if(typeof f==="string"&&f.length>0){Q[Z]=f;continue}if(typeof W.value==="string"){Q[Z]=W.value;continue}if(W.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function e7($){if(!C8($))return{name:"",loadError:"invalid MCP server registration"};let J=typeof $.name==="string"?$.name.trim():"";if(!J)return{name:J,loadError:"empty MCP server name"};let Q=$.env,Z=Q===void 0?void 0:Q;if(Z!==void 0){if(!C8(Z))return{name:J,loadError:"invalid env"};for(let[Y,V]of Object.entries(Z))if(typeof V!=="string"&&!XT(V))return{name:J,loadError:`invalid env "${Y}"`}}let W=$.transport;if(!C8(W))return{name:J,loadError:"invalid MCP transport"};let j=W.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:J,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Z!==void 0)return{name:J,loadError:"top-level env is only supported for stdio MCP transports"};let f=C8($.metadata)?$.metadata:void 0;if(j==="stdio"){let Y=W.command;if(typeof Y!=="string"||!Y.trim())return{name:J,loadError:"stdio MCP transport requires command"};let V=W.args;if(V!==void 0&&!fT(V))return{name:J,loadError:"stdio MCP transport args must be strings"};let H=W.cwd;if(H!==void 0&&typeof H!=="string")return{name:J,loadError:"stdio MCP transport cwd must be a string"};let B=W.env;if(B!==void 0&&!NH(B))return{name:J,loadError:"stdio MCP transport env must be strings"};let A=YT({name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:B},env:Z,metadata:f});if(!A.ok)return{name:J,loadError:A.reason};let K=B||A.env?{...B??{},...A.env??{}}:void 0;return{name:J,registration:{name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:K},metadata:f}}}if(typeof W.url!=="string"||!W.url.trim())return{name:J,loadError:`${j} MCP transport requires url`};let X=W.headers;if(X!==void 0&&!NH(X))return{name:J,loadError:`${j} MCP transport headers must be strings`};return{name:J,registration:{name:J,transport:j==="sse"?{type:"sse",url:W.url,headers:X}:{type:"streamableHttp",url:W.url,headers:X},metadata:f}}}function CQ($){let J=new Map;return $.map(({server:Q,owner:Z,ownerLabel:W})=>{let j=e7(Q);if(!j.registration)return{owner:Z,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let f=J.get(j.registration.name);if(J.has(j.registration.name)){let X=f?` already registered by ${f}`:"";return{owner:Z,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${X}`}}return J.set(j.registration.name,W),{owner:Z,name:j.registration.name,registration:j.registration}})}import{createHash as VT}from"node:crypto";var wH=128,HT=/[^a-zA-Z0-9_-]+/g,SH=8,BT=1,AT="mcp_tool";function KT($){return VT("sha1").update($).digest("hex").slice(0,SH)}function GT($){return $.replace(HT,"_")}var yQ=({serverName:$,toolName:J})=>{let Q=`${$}__${J}`,Z=GT(Q);if(Z===Q&&Q.length<=wH)return Q;let W=KT(Q),j=wH-BT-SH;return`${Z.slice(0,j)||AT}_${W}`};function m6($){return{[($.nameTransform??yQ)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function EQ($){let J={};for(let Q of $.toolNames)Object.assign(J,m6({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return J}import{createTool as FT}from"@cline/shared";function DT($,J){let Q=J.description?.trim();if(Q)return Q;return`Execute MCP tool "${J.name}" from server "${$}".`}async function y8($){let J=await $.provider.listTools($.serverName),Q=$.nameTransform??yQ;return J.map((Z)=>{let W=Q({serverName:$.serverName,toolName:Z.name});return FT({name:W,description:DT($.serverName,Z),inputSchema:Z.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,f)=>$.provider.callTool({serverName:$.serverName,toolName:Z.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:f})})})}W1();var bH={};w(bH,{listPluginToolsWithDiagnostics:()=>bQ,listPluginTools:()=>v6});import{stat as UT}from"node:fs/promises";import{isAbsolute as RT,relative as zT,resolve as yH}from"node:path";W1();function LT($,J){let Q=zT(yH($),yH(J));return Q===""||!Q.startsWith("..")&&!RT(Q)}var _T=32,E8=new Map;function OT($,J){if(!E8.has($)&&E8.size>=_T){let Q=E8.keys().next().value;if(Q)E8.delete(Q)}E8.set($,J)}async function TT($){let J=await Promise.all($.pluginPaths.map(async(Q)=>{try{let Z=await UT(Q);return`${Q}:${Z.mtimeMs}:${Z.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:J})}function EH($,J){return $.map((Q)=>({...Q,enabled:!J.has(Q.name)}))}function MT($){return $.sort((J,Q)=>{let Z=J.name.localeCompare(Q.name);if(Z!==0)return Z;return J.path.localeCompare(Q.path)})}async function qT($,J){if(!$.setup)return{tools:[]};let Q=[],Z={registerTool:(W)=>Q.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(W)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Z,{workspaceInfo:J}),{tools:Q}}async function bQ($){let J=e$({workspacePath:$.workspacePath,cwd:$.cwd}),Q=B1($.disabledToolNames);if(J.length===0)return{tools:[],failures:[],warnings:[]};let Z=await TT({pluginPaths:J,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),W=E8.get(Z);if(W)return{tools:EH(W.tools,Q),failures:W.failures,warnings:W.warnings};let j=[],f=[],X=[],Y;try{Y=await B8({pluginPaths:J,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),f=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;let A=LT($.workspacePath,B)?"workspace-plugin":"global-plugin",K;try{K=await qT(H,{rootPath:$.workspacePath})}catch(G){f.push({pluginPath:B,pluginName:H.name,phase:"setup",message:G instanceof Error?G.message:String(G),stack:G instanceof Error?G.stack:void 0});continue}for(let G of K.tools)j.push({name:G.name,pluginName:H.name,path:B,source:A,description:G.description?.trim()||void 0})}}catch(H){f=J.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=MT(j);return OT(Z,{tools:V,failures:f,warnings:X}),{tools:EH(V,Q),failures:f,warnings:X}}async function v6($){return(await bQ($)).tools}function kQ($,J){if(!J)return"global";let Q=NT(J,$);return!Q.startsWith("..")&&!PT(Q)?"workspace":"global"}function c6($){return[...$].sort((J,Q)=>{let Z=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(J.source!==Q.source)return Z(J.source)-Z(Q.source);return J.name.localeCompare(Q.name)})}function IH($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function kH($,J){if($.userInstructionService)return await J($.userInstructionService);let Q=IH($);if(!Q)return await J(void 0);let Z=$.cwd?.trim()||Q,W=_$({skills:{workspacePath:Q,includePluginSkills:!0,cwd:Z},rules:{workspacePath:Q},workflows:{workspacePath:Q}});try{return await W.start(),await J(W)}finally{W.stop()}}function wT($,J){if(!$)return;let Q=$.listRecords("skill");if(J.id){let Z=Q.find((W)=>W.id===J.id);if(Z)return Z}for(let Z of Q)if(Z.filePath===J.path||Z.item.name===J.name||Z.id===J.name)return Z;return}class O${async list($={}){return await kH($,async(J)=>{let Q=IH($),Z=[],W=[],j=[],f=[],X=[];if(J){for(let V of J.listRecords("workflow")){let H=V.item;Z.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"workflow",source:kQ(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("rule")){let H=V.item;W.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"rule",source:kQ(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("skill")){let H=V.item;j.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"skill",source:kQ(V.filePath,Q),description:H.description,toggleable:!0})}}if(Q)try{for(let V of await v6({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))f.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=B0();if(c1({filePath:Y}))try{for(let V of A1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:kQ(Y,Q),description:V.transport.type,toggleable:!0})}catch{}return{workflows:c6(Z.filter((V)=>hQ(V.path))),rules:c6(W.filter((V)=>hQ(V.path))),skills:c6(j.filter((V)=>hQ(V.path))),tools:c6(f),mcp:c6(X.filter((V)=>hQ(V.path)))}})}async toggle($){if($.type==="skills")return await kH($,async(J)=>{let Q=wT(J,$),Z=Q?.filePath;if(!Z)throw Error(`Unable to resolve skill setting '${$.id??$.name??hH($.path??"")}'.`);let W=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,j=$.enabled??(W!==void 0?!W:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??hH($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await BH({filePath:Z,enabled:j}),await J?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:J}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)z5($.name);else IX($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let J=$.name?.trim()||$.id?.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||B0(),Z=$.enabled;if(Z===void 0){let W=A1({filePath:Q}).find((j)=>j.name===J);if(!W)throw Error(`Unknown MCP server: ${J}`);Z=W.disabled===!0}return Y2({filePath:Q,name:J,disabled:!Z}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function K2(){return new O$}function gH($){return{async list(J){let Q=$;if(Q.listSettings)return await Q.listSettings(J);return await K2().list(J)},async toggle(J){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(J);return await K2().toggle(J)}}}function mH($){function J(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return J().list(Q)},update(Q){return J().update(Q)},delete(Q){return J().delete(Q)}}}var vH={};w(vH,{splitCoreSessionConfig:()=>u6,isSessionNotFoundError:()=>d1,SessionNotFoundError:()=>u1,SESSION_NOT_FOUND_ERROR_CODE:()=>G2});var G2="session_not_found";class u1 extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function d1($){return $ instanceof u1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function u6($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...B}=$,A={};if(J)A.hooks=J;if(Q)A.logger=Q;if(Z)A.telemetry=Z;if(W)A.extensionContext=W;if(j)A.extraTools=j;if(f)A.extensions=f;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(H?.compact)A.compaction=H;let K=Object.keys(A).length>0?A:void 0;return{config:{...B,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}function cH($){let J=$.config;return"providerId"in J?{...$,config:{...J,...ST($.localRuntime)},localRuntime:$.localRuntime}:$}function $W($,J={}){let Q=u6($.config),Z=L0(J.defaultCapabilities,$.capabilities),W=CT(Q.localRuntime,$.localRuntime),j=J.withExtensionContext?.(W?.extensionContext);if(j)W={...W??{},extensionContext:j};return{...$,...Q,...W?{localRuntime:W}:{},...Z?{capabilities:Z}:{}}}function ST($){if(!$)return{};let{modelCatalogDefaults:J,userInstructionService:Q,configExtensions:Z,onTeamRestored:W,...j}=$;return j}function CT(...$){let J={};for(let Q of $)if(Q)Object.assign(J,Q);return Object.keys(J).length>0?J:void 0}O0();function uH($){let J=$.input.config.telemetry??$.telemetry;if(!J)return;J.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??U0.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 d6($){return!!$&&typeof $==="object"&&!Array.isArray($)}function JW($){let J=$?.trim();return J?J:void 0}function yT($,J){let Q=$?.trim();if(!Q)return J;let Z=Date.parse(Q);if(!Number.isFinite(Z))return J;return new Date(Z).toISOString()}function dH($,J){return new Date(new Date($).getTime()+Math.max(0,Math.floor(J))*1000).toISOString()}function lH($,J){return new Date(new Date($).getTime()-Math.max(0,Math.floor(J))*1000).toISOString()}function ET($,J){if(!$)return J;return new Date($).getTime()>=new Date(J).getTime()?$:J}function bT($,J){let Q=$.eventId.trim(),Z=$.eventType.trim(),W=$.source.trim(),j=JW($.subject),f=JW($.dedupeKey)??`${Z}:${W}:${j??Q}`;return{eventId:Q,eventType:Z,source:W,subject:j,occurredAt:yT($.occurredAt,J),workspaceRoot:JW($.workspaceRoot),payload:d6($.payload)?$.payload:void 0,attributes:d6($.attributes)?$.attributes:void 0,dedupeKey:f}}function QW($,J){if(!J)return;let Q=J.split("."),Z=$;for(let W of Q){if(!d6(Z))return;Z=Z[W]}return Z}function hT($,J){if($.attributes&&Object.hasOwn($.attributes,J))return $.attributes[J];if($.payload&&Object.hasOwn($.payload,J))return $.payload[J];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Z=QW(Q,J);if(Z!==void 0)return Z;if($.attributes){let W=QW($.attributes,J);if(W!==void 0)return W}if($.payload)return QW($.payload,J);return}function IQ($,J){if(Array.isArray(J))return J.some((Q)=>IQ($,Q));if(Array.isArray($))return $.some((Q)=>IQ(Q,J));if(d6(J)){if(!d6($))return!1;return Object.entries(J).every(([Q,Z])=>IQ($[Q],Z))}return Object.is($,J)}function kT($,J){if(!J||Object.keys(J).length===0)return!0;return Object.entries(J).every(([Q,Z])=>IQ(hT($,Q),Z))}class ZW{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let J=new Date(this.nowFn()).toISOString(),Q=bT($,J),Z=this.store.insertEventLog(Q,{receivedAtIso:J});if(!Z.created)return this.logger?.debug("cron.event.duplicate",{eventId:Z.record.eventId,eventType:Z.record.eventType,source:Z.record.source}),{event:Z.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Z.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(Q.eventType),j=[],f=[],X=[];for(let H of W){if(!kT(Q,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}f.push(H);let B=this.materializeForSpec(H,Q,Z.record.receivedAt);if(B.run)X.push(B.run);else j.push({specId:H.specId,externalId:H.externalId,reason:B.reason,dedupeKey:Q.dedupeKey})}let Y=f.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Z.record.eventId,{status:Y,matchedSpecCount:f.length,queuedRunCount:X.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Z.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Z.record.eventId,eventType:Z.record.eventType,status:Y,matchedSpecCount:f.length,queuedRunCount:X.length}),{event:V??Z.record,duplicate:!1,matchedSpecs:f,queuedRuns:X,suppressions:j}}catch(W){if(this.store.updateEventLogProcessing(Z.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Z.record.eventId,eventType:Z.record.eventType,error:W});throw W}}materializeForSpec($,J,Q){let Z=J.dedupeKey??J.eventId,W=$.debounceSeconds??0;if(W>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Z});if(Y){let V=ET(Y.scheduledFor,dH(Q,W)),H=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:J.eventId,scheduledFor:V});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Z,sinceIso:lH(Q,j)}))return{reason:"dedupe_window"};let f=$.cooldownSeconds??0;if(f>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:lH(Q,f)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:J.eventId,scheduledFor:W>0?dH(Q,W):Q}),reason:"dedupe_window"}}}class l6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},J=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Z of J)if(this.materializeOneOff(Z))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of Q)try{if(this.materializeSchedule(Z))$.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 uT}from"node:path";import{buildClineSystemPrompt as dT}from"@cline/shared";import{nowIso as pH}from"@cline/shared/db";import{mkdirSync as IT,writeFileSync as xT}from"node:fs";import{join as gT}from"node:path";import{resolveCronReportsDir as mT}from"@cline/shared/storage";function T$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function F2($,J){if(J===void 0||J===null)return;return`${$}: ${T$(J)}`}function vT($,J,Q){let Z=[`runId: ${T$($.runId)}`,`specId: ${T$(J.specId)}`,`externalId: ${T$(J.externalId)}`,`title: ${T$(J.title)}`,`triggerKind: ${T$($.triggerKind)}`,`status: ${T$($.status)}`,`sourcePath: ${T$(J.sourcePath)}`],W=[F2("sessionId",$.sessionId),F2("startedAt",$.startedAt),F2("completedAt",$.completedAt),F2("triggerEventId",$.triggerEventId),F2("triggerEventType",Q?.eventType),F2("triggerEventSource",Q?.source),F2("triggerEventSubject",Q?.subject)];for(let j of W)if(j)Z.push(j);return`---
216
+ `);if(Q<0)break;let W=this.buffer.slice(0,Q).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!W)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let j=Number.parseInt(W[1],10),f=Q+4,X=f+j;if(this.buffer.length<X)break;J.push(this.buffer.slice(f,X)),this.buffer=this.buffer.slice(X)}return J}}class t7{buffer="";decoder=new TH("utf8");push($){this.buffer+=this.decoder.write($);let J=[];while(!0){let Q=this.buffer.indexOf(`
217
+ `);if(Q<0)break;let Z=this.buffer.slice(0,Q).trim();if(this.buffer=this.buffer.slice(Q+1),Z.length>0)J.push(Z)}return J}}class MH{registration;process;nextRequestId=1;pending=new Map;framedParser=new o7;newlineParser=new t7;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"],J;for(let Q of $){await this.disconnect().catch(()=>{}),this.spawnProcess(Q);try{await this.request("initialize",{protocolVersion:QT,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},WT),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=Q;return}catch(Z){J=Z instanceof Error?Z:Error(String(Z))}}throw J??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((J)=>typeof J?.name==="string"&&typeof J.inputSchema==="object"&&J.inputSchema!==null).map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let J=this.registration.transport;if(J.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${J.type}`);this.framedParser=new o7,this.newlineParser=new t7,this.stderrBuffer="",this.protocolMode=$;let Q=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Z=$T(J.command,J.args??[],{cwd:J.cwd,env:{...process.env,...J.env??{}},stdio:["pipe","pipe","pipe"],...Q});this.process=Z,Z.stdout.on("data",(W)=>this.handleStdout(W)),Z.stderr.on("data",(W)=>{if(this.process!==Z)return;if(this.stderrBuffer+=W.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Z.once("error",(W)=>{if(this.process!==Z)return;this.failAllPending(Error(`MCP process error: ${S9(W)}`))}),Z.once("exit",(W,j)=>{if(this.process!==Z)return;this.connected=!1,this.process=void 0;let f=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${W??"null"}, signal=${j??"null"}).${f}`))})}handleStdout($){try{let J=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let Q of J){let Z=JSON.parse(Q);if(typeof Z.id!=="number")continue;let W=this.pending.get(Z.id);if(!W)continue;if(this.pending.delete(Z.id),clearTimeout(W.timeout),Z.error){let j=Z.error.message||`MCP request failed with code ${Z.error.code??"unknown"}`;W.reject(Error(j));continue}W.resolve(Z.result)}}catch(J){this.handleProtocolFailure(J)}}handleProtocolFailure($){let J=this.process;if(!J)return;this.connected=!1,this.process=void 0;let Q=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${S9($)}.${Q}`)),J.kill()}async request($,J,Q=ZT){let Z=this.process;if(!Z?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let W=this.nextRequestId++,j={jsonrpc:"2.0",id:W,method:$,...J?{params:J}:{}},f=new Promise((X,Y)=>{let V=setTimeout(()=>{this.pending.delete(W),Y(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},Q);this.pending.set(W,{resolve:X,reject:Y,timeout:V})});try{Z.stdin.write(this.protocolMode==="framed"?_H(j):OH(j))}catch(X){let Y=this.pending.get(W);if(Y)clearTimeout(Y.timeout),this.pending.delete(W);throw X}return f}notify($,J){let Q=this.process;if(!Q?.stdin.writable)return;let Z={jsonrpc:"2.0",method:$,...J?{params:J}:{}};Q.stdin.write(this.protocolMode==="framed"?_H(Z):OH(Z))}failAllPending($){for(let[J,Q]of this.pending)clearTimeout(Q.timeout),this.pending.delete(J),Q.reject($)}}class qH{registration;options;client;authContext;constructor($,J){this.registration=$;this.options=J}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 $=N9({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??LH});this.authContext=$;try{let J=new JT({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),Q=P9({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await J.connect(Q),await $.clearError(),this.client=J}catch(J){let Q=J instanceof zH?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):S9(J);throw await $.markError(Q),Error(Q)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((Q)=>({name:Q.name,description:Q.description,inputSchema:Q.inputSchema&&typeof Q.inputSchema==="object"&&!Array.isArray(Q.inputSchema)?Q.inputSchema:{}}))}catch(J){return await this.handleOperationError(J)}}async callTool($){let J=await this.ensureConnectedClient();try{return await J.callTool({name:$.name,arguments:$.arguments??{}})}catch(Q){return await this.handleOperationError(Q)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let J=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${J} Run authorizeMcpServerOAuth for this server.`;return`${J} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let J=this.authContext??N9({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??LH}),Q=$ instanceof zH?this.formatUnauthorizedMessage(J.getLastAuthorizationUrl()):S9($);throw await J.markError(Q),Error(Q)}}function S8($={}){return(J)=>J.transport.type==="stdio"?new MH(J):new qH(J,$)}q9();function l0(){return Date.now()}function jT($){return $.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema}))}class A2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let J=this.servers.get($.name);if(!J){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:l0()});return}let Q=JSON.stringify(J.registration.transport)!==JSON.stringify($.transport);if(J.registration={...$},J.updatedAt=l0(),Q)await this.disconnectState(J),J.client=void 0,J.toolCache=void 0,J.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.connectState(J)})}async disconnectServer($){await this.runExclusive($,async()=>{let J=this.requireServer($);await this.disconnectState(J)})}async setServerDisabled($,J){await this.runExclusive($,async()=>{let Q=this.requireServer($);if(Q.registration={...Q.registration,disabled:J},Q.updatedAt=l0(),J)await this.disconnectState(Q)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,J)=>$.name.localeCompare(J.name))}async listTools($){let J=this.requireServer($),Q=J.toolCacheUpdatedAt??0;if(J.toolCache&&l0()-Q<=this.toolsCacheTtlMs)return J.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let J=this.requireServer($),Z=await(await this.ensureConnectedClient(J)).listTools(),W=jT(Z);return J.toolCache=W,J.toolCacheUpdatedAt=l0(),J.updatedAt=l0(),W})}async callTool($){return this.runExclusive($.serverName,async()=>{let J=this.requireServer($.serverName),Q=await this.ensureConnectedClient(J);return J.updatedAt=l0(),Q.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let J of $)await this.unregisterServer(J)}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=l0();try{let J=$.client??await this.clientFactory($.registration);await J.connect(),$.client=J,$.status="connected",$.lastError=void 0,$.updatedAt=l0()}catch(J){throw $.status="disconnected",$.lastError=J instanceof Error?J.message:String(J),$.updatedAt=l0(),J}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=l0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=l0()}}requireServer($){let J=this.servers.get($);if(!J)throw Error(`Unknown MCP server: ${$}`);return J}async runExclusive($,J){let Q=this.operationLocks.get($)??Promise.resolve(),Z,W=new Promise((f)=>{Z=f}),j=Q.catch(()=>{return}).then(()=>W);this.operationLocks.set($,j),await Q.catch(()=>{return});try{return await J()}finally{if(Z?.(),this.operationLocks.get($)===j)this.operationLocks.delete($)}}}function C8($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function PH($){return C8($)&&Object.values($).every((J)=>typeof J==="string")}function fT($){return Array.isArray($)&&$.every((J)=>typeof J==="string")}function XT($){if(!C8($))return!1;return($.fromEnv===void 0||typeof $.fromEnv==="string")&&($.value===void 0||typeof $.value==="string")&&($.required===void 0||typeof $.required==="boolean")}function YT($){let J=$.env?Object.entries($.env):[];if(J.length===0)return{ok:!0};let Q={};for(let[Z,W]of J){if(typeof W==="string"){Q[Z]=W;continue}let j=W.fromEnv?.trim()||Z,f=process.env[j];if(typeof f==="string"&&f.length>0){Q[Z]=f;continue}if(typeof W.value==="string"){Q[Z]=W.value;continue}if(W.required===!0)return{ok:!1,reason:`required environment variable "${j}" is not set`}}return{ok:!0,env:Object.keys(Q).length>0?Q:void 0}}function e7($){if(!C8($))return{name:"",loadError:"invalid MCP server registration"};let J=typeof $.name==="string"?$.name.trim():"";if(!J)return{name:J,loadError:"empty MCP server name"};let Q=$.env,Z=Q===void 0?void 0:Q;if(Z!==void 0){if(!C8(Z))return{name:J,loadError:"invalid env"};for(let[Y,V]of Object.entries(Z))if(typeof V!=="string"&&!XT(V))return{name:J,loadError:`invalid env "${Y}"`}}let W=$.transport;if(!C8(W))return{name:J,loadError:"invalid MCP transport"};let j=W.type;if(j!=="stdio"&&j!=="sse"&&j!=="streamableHttp")return{name:J,loadError:"invalid MCP transport type"};if(j!=="stdio"&&Z!==void 0)return{name:J,loadError:"top-level env is only supported for stdio MCP transports"};let f=C8($.metadata)?$.metadata:void 0;if(j==="stdio"){let Y=W.command;if(typeof Y!=="string"||!Y.trim())return{name:J,loadError:"stdio MCP transport requires command"};let V=W.args;if(V!==void 0&&!fT(V))return{name:J,loadError:"stdio MCP transport args must be strings"};let H=W.cwd;if(H!==void 0&&typeof H!=="string")return{name:J,loadError:"stdio MCP transport cwd must be a string"};let B=W.env;if(B!==void 0&&!PH(B))return{name:J,loadError:"stdio MCP transport env must be strings"};let A=YT({name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:B},env:Z,metadata:f});if(!A.ok)return{name:J,loadError:A.reason};let K=B||A.env?{...B??{},...A.env??{}}:void 0;return{name:J,registration:{name:J,transport:{type:"stdio",command:Y,args:V,cwd:H,env:K},metadata:f}}}if(typeof W.url!=="string"||!W.url.trim())return{name:J,loadError:`${j} MCP transport requires url`};let X=W.headers;if(X!==void 0&&!PH(X))return{name:J,loadError:`${j} MCP transport headers must be strings`};return{name:J,registration:{name:J,transport:j==="sse"?{type:"sse",url:W.url,headers:X}:{type:"streamableHttp",url:W.url,headers:X},metadata:f}}}function C9($){let J=new Map;return $.map(({server:Q,owner:Z,ownerLabel:W})=>{let j=e7(Q);if(!j.registration)return{owner:Z,name:j.name,loadError:j.loadError??"invalid MCP server registration"};let f=J.get(j.registration.name);if(J.has(j.registration.name)){let X=f?` already registered by ${f}`:"";return{owner:Z,name:j.registration.name,loadError:`duplicate MCP server name "${j.registration.name}"${X}`}}return J.set(j.registration.name,W),{owner:Z,name:j.registration.name,registration:j.registration}})}import{createHash as VT}from"node:crypto";var NH=128,HT=/[^a-zA-Z0-9_-]+/g,wH=8,BT=1,AT="mcp_tool";function KT($){return VT("sha1").update($).digest("hex").slice(0,wH)}function GT($){return $.replace(HT,"_")}var y9=({serverName:$,toolName:J})=>{let Q=`${$}__${J}`,Z=GT(Q);if(Z===Q&&Q.length<=NH)return Q;let W=KT(Q),j=NH-BT-wH;return`${Z.slice(0,j)||AT}_${W}`};function m6($){return{[($.nameTransform??y9)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function E9($){let J={};for(let Q of $.toolNames)Object.assign(J,m6({serverName:$.serverName,toolName:Q,nameTransform:$.nameTransform}));return J}import{createTool as FT}from"@cline/shared";function DT($,J){let Q=J.description?.trim();if(Q)return Q;return`Execute MCP tool "${J.name}" from server "${$}".`}async function y8($){let J=await $.provider.listTools($.serverName),Q=$.nameTransform??y9;return J.map((Z)=>{let W=Q({serverName:$.serverName,toolName:Z.name});return FT({name:W,description:DT($.serverName,Z),inputSchema:Z.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(j,f)=>$.provider.callTool({serverName:$.serverName,toolName:Z.name,arguments:j&&typeof j==="object"&&!Array.isArray(j)?j:void 0,context:f})})})}W1();var EH={};w(EH,{listPluginToolsWithDiagnostics:()=>b9,listPluginTools:()=>v6});import{stat as UT}from"node:fs/promises";import{isAbsolute as RT,relative as zT,resolve as CH}from"node:path";W1();function LT($,J){let Q=zT(CH($),CH(J));return Q===""||!Q.startsWith("..")&&!RT(Q)}var _T=32,E8=new Map;function OT($,J){if(!E8.has($)&&E8.size>=_T){let Q=E8.keys().next().value;if(Q)E8.delete(Q)}E8.set($,J)}async function TT($){let J=await Promise.all($.pluginPaths.map(async(Q)=>{try{let Z=await UT(Q);return`${Q}:${Z.mtimeMs}:${Z.size}`}catch{return`${Q}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:J})}function yH($,J){return $.map((Q)=>({...Q,enabled:!J.has(Q.name)}))}function MT($){return $.sort((J,Q)=>{let Z=J.name.localeCompare(Q.name);if(Z!==0)return Z;return J.path.localeCompare(Q.path)})}async function qT($,J){if(!$.setup)return{tools:[]};let Q=[],Z={registerTool:(W)=>Q.push(W),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(W)=>{if(!$.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability')}};return await $.setup(Z,{workspaceInfo:J}),{tools:Q}}async function b9($){let J=e$({workspacePath:$.workspacePath,cwd:$.cwd}),Q=B1($.disabledToolNames);if(J.length===0)return{tools:[],failures:[],warnings:[]};let Z=await TT({pluginPaths:J,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),W=E8.get(Z);if(W)return{tools:yH(W.tools,Q),failures:W.failures,warnings:W.warnings};let j=[],f=[],X=[],Y;try{Y=await B8({pluginPaths:J,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),f=[...Y.failures],X=[...Y.warnings];for(let H of Y.extensions??[]){let B=H.__clinePluginPath;if(!B)continue;let A=LT($.workspacePath,B)?"workspace-plugin":"global-plugin",K;try{K=await qT(H,{rootPath:$.workspacePath})}catch(G){f.push({pluginPath:B,pluginName:H.name,phase:"setup",message:G instanceof Error?G.message:String(G),stack:G instanceof Error?G.stack:void 0});continue}for(let G of K.tools)j.push({name:G.name,pluginName:H.name,path:B,source:A,description:G.description?.trim()||void 0})}}catch(H){f=J.map((B)=>({pluginPath:B,phase:"load",message:H instanceof Error?H.message:String(H),stack:H instanceof Error?H.stack:void 0}))}finally{await Y?.shutdown().catch(()=>{})}let V=MT(j);return OT(Z,{tools:V,failures:f,warnings:X}),{tools:yH(V,Q),failures:f,warnings:X}}async function v6($){return(await b9($)).tools}function k9($,J){if(!J)return"global";let Q=NT(J,$);return!Q.startsWith("..")&&!PT(Q)?"workspace":"global"}function c6($){return[...$].sort((J,Q)=>{let Z=(W)=>{switch(W){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(J.source!==Q.source)return Z(J.source)-Z(Q.source);return J.name.localeCompare(Q.name)})}function kH($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function hH($,J){if($.userInstructionService)return await J($.userInstructionService);let Q=kH($);if(!Q)return await J(void 0);let Z=$.cwd?.trim()||Q,W=_$({skills:{workspacePath:Q,includePluginSkills:!0,cwd:Z},rules:{workspacePath:Q},workflows:{workspacePath:Q}});try{return await W.start(),await J(W)}finally{W.stop()}}function wT($,J){if(!$)return;let Q=$.listRecords("skill");if(J.id){let Z=Q.find((W)=>W.id===J.id);if(Z)return Z}for(let Z of Q)if(Z.filePath===J.path||Z.item.name===J.name||Z.id===J.name)return Z;return}class O${async list($={}){return await hH($,async(J)=>{let Q=kH($),Z=[],W=[],j=[],f=[],X=[];if(J){for(let V of J.listRecords("workflow")){let H=V.item;Z.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"workflow",source:k9(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("rule")){let H=V.item;W.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"rule",source:k9(V.filePath,Q),description:H.instructions,toggleable:!1})}for(let V of J.listRecords("skill")){let H=V.item;j.push({id:V.id,name:H.name,path:V.filePath,enabled:H.disabled!==!0,kind:"skill",source:k9(V.filePath,Q),description:H.description,toggleable:!0})}}if(Q)try{for(let V of await v6({workspacePath:Q,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))f.push({id:`${V.pluginName}:${V.name}:${V.path}`,name:V.name,path:V.path,enabled:V.enabled,kind:"tool",source:V.source,description:V.description,toggleable:!0})}catch{}let Y=B0();if(c1({filePath:Y}))try{for(let V of A1({filePath:Y}))X.push({id:V.name,name:V.name,path:Y,enabled:V.disabled!==!0,kind:"mcp",source:k9(Y,Q),description:V.transport.type,toggleable:!0})}catch{}return{workflows:c6(Z.filter((V)=>h9(V.path))),rules:c6(W.filter((V)=>h9(V.path))),skills:c6(j.filter((V)=>h9(V.path))),tools:c6(f),mcp:c6(X.filter((V)=>h9(V.path)))}})}async toggle($){if($.type==="skills")return await hH($,async(J)=>{let Q=wT(J,$),Z=Q?.filePath;if(!Z)throw Error(`Unable to resolve skill setting '${$.id??$.name??bH($.path??"")}'.`);let W=Q?.item&&"disabled"in Q.item?Q.item.disabled!==!0:void 0,j=$.enabled??(W!==void 0?!W:void 0);if(j===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??bH($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await HH({filePath:Z,enabled:j}),await J?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:J}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)z5($.name);else kX($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let J=$.name?.trim()||$.id?.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=$.path?.trim()||B0(),Z=$.enabled;if(Z===void 0){let W=A1({filePath:Q}).find((j)=>j.name===J);if(!W)throw Error(`Unknown MCP server: ${J}`);Z=W.disabled===!0}return Y2({filePath:Q,name:J,disabled:!Z}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function K2(){return new O$}function xH($){return{async list(J){let Q=$;if(Q.listSettings)return await Q.listSettings(J);return await K2().list(J)},async toggle(J){let Q=$;if(Q.toggleSetting)return await Q.toggleSetting(J);return await K2().toggle(J)}}}function gH($){function J(){let Q=$.pendingPrompts;if(!Q)throw Error("Pending prompt service is not available.");return Q}return{list(Q){return J().list(Q)},update(Q){return J().update(Q)},delete(Q){return J().delete(Q)}}}var mH={};w(mH,{splitCoreSessionConfig:()=>u6,isSessionNotFoundError:()=>d1,SessionNotFoundError:()=>u1,SESSION_NOT_FOUND_ERROR_CODE:()=>G2});var G2="session_not_found";class u1 extends Error{sessionId;code="session_not_found";constructor($,J){super(J??($?`session not found: ${$}`:"session not found"));this.sessionId=$;this.name="SessionNotFoundError"}}function d1($){return $ instanceof u1||typeof $==="object"&&$!==null&&"code"in $&&$.code==="session_not_found"}function u6($){let{hooks:J,logger:Q,telemetry:Z,extensionContext:W,extraTools:j,extensions:f,onTeamEvent:X,onConsecutiveMistakeLimitReached:Y,checkpoint:V,compaction:H,...B}=$,A={};if(J)A.hooks=J;if(Q)A.logger=Q;if(Z)A.telemetry=Z;if(W)A.extensionContext=W;if(j)A.extraTools=j;if(f)A.extensions=f;if(X)A.onTeamEvent=X;if(Y)A.onConsecutiveMistakeLimitReached=Y;if(V?.createCheckpoint)A.checkpoint=V;if(H?.compact)A.compaction=H;let K=Object.keys(A).length>0?A:void 0;return{config:{...B,...V?{checkpoint:{enabled:V.enabled}}:{},...H?{compaction:{enabled:H.enabled,strategy:H.strategy,thresholdRatio:H.thresholdRatio,reserveTokens:H.reserveTokens,preserveRecentTokens:H.preserveRecentTokens,maxInputTokens:H.maxInputTokens,summarizer:H.summarizer}}:{}},...K?{localRuntime:K}:{}}}function vH($){let J=$.config;return"providerId"in J?{...$,config:{...J,...ST($.localRuntime)},localRuntime:$.localRuntime}:$}function $W($,J={}){let Q=u6($.config),Z=L0(J.defaultCapabilities,$.capabilities),W=CT(Q.localRuntime,$.localRuntime),j=J.withExtensionContext?.(W?.extensionContext);if(j)W={...W??{},extensionContext:j};return{...$,...Q,...W?{localRuntime:W}:{},...Z?{capabilities:Z}:{}}}function ST($){if(!$)return{};let{modelCatalogDefaults:J,userInstructionService:Q,configExtensions:Z,onTeamRestored:W,...j}=$;return j}function CT(...$){let J={};for(let Q of $)if(Q)Object.assign(J,Q);return Object.keys(J).length>0?J:void 0}O0();function cH($){let J=$.input.config.telemetry??$.telemetry;if(!J)return;J.capture({event:x.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??U0.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 d6($){return!!$&&typeof $==="object"&&!Array.isArray($)}function JW($){let J=$?.trim();return J?J:void 0}function yT($,J){let Q=$?.trim();if(!Q)return J;let Z=Date.parse(Q);if(!Number.isFinite(Z))return J;return new Date(Z).toISOString()}function uH($,J){return new Date(new Date($).getTime()+Math.max(0,Math.floor(J))*1000).toISOString()}function dH($,J){return new Date(new Date($).getTime()-Math.max(0,Math.floor(J))*1000).toISOString()}function ET($,J){if(!$)return J;return new Date($).getTime()>=new Date(J).getTime()?$:J}function bT($,J){let Q=$.eventId.trim(),Z=$.eventType.trim(),W=$.source.trim(),j=JW($.subject),f=JW($.dedupeKey)??`${Z}:${W}:${j??Q}`;return{eventId:Q,eventType:Z,source:W,subject:j,occurredAt:yT($.occurredAt,J),workspaceRoot:JW($.workspaceRoot),payload:d6($.payload)?$.payload:void 0,attributes:d6($.attributes)?$.attributes:void 0,dedupeKey:f}}function QW($,J){if(!J)return;let Q=J.split("."),Z=$;for(let W of Q){if(!d6(Z))return;Z=Z[W]}return Z}function hT($,J){if($.attributes&&Object.hasOwn($.attributes,J))return $.attributes[J];if($.payload&&Object.hasOwn($.payload,J))return $.payload[J];let Q={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Z=QW(Q,J);if(Z!==void 0)return Z;if($.attributes){let W=QW($.attributes,J);if(W!==void 0)return W}if($.payload)return QW($.payload,J);return}function I9($,J){if(Array.isArray(J))return J.some((Q)=>I9($,Q));if(Array.isArray($))return $.some((Q)=>I9(Q,J));if(d6(J)){if(!d6($))return!1;return Object.entries(J).every(([Q,Z])=>I9($[Q],Z))}return Object.is($,J)}function kT($,J){if(!J||Object.keys(J).length===0)return!0;return Object.entries(J).every(([Q,Z])=>I9(hT($,Q),Z))}class ZW{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let J=new Date(this.nowFn()).toISOString(),Q=bT($,J),Z=this.store.insertEventLog(Q,{receivedAtIso:J});if(!Z.created)return this.logger?.debug("cron.event.duplicate",{eventId:Z.record.eventId,eventType:Z.record.eventType,source:Z.record.source}),{event:Z.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Z.record.dedupeKey}]};try{let W=this.store.listEventSpecsForType(Q.eventType),j=[],f=[],X=[];for(let H of W){if(!kT(Q,H.filters)){j.push({specId:H.specId,externalId:H.externalId,reason:"filter_mismatch",dedupeKey:Q.dedupeKey});continue}f.push(H);let B=this.materializeForSpec(H,Q,Z.record.receivedAt);if(B.run)X.push(B.run);else j.push({specId:H.specId,externalId:H.externalId,reason:B.reason,dedupeKey:Q.dedupeKey})}let Y=f.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Z.record.eventId,{status:Y,matchedSpecCount:f.length,queuedRunCount:X.length,suppressedCount:j.filter((H)=>H.reason!=="filter_mismatch").length});let V=this.store.getEventLog(Z.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Z.record.eventId,eventType:Z.record.eventType,status:Y,matchedSpecCount:f.length,queuedRunCount:X.length}),{event:V??Z.record,duplicate:!1,matchedSpecs:f,queuedRuns:X,suppressions:j}}catch(W){if(this.store.updateEventLogProcessing(Z.record.eventId,{status:"failed",error:W instanceof Error?W.message:String(W)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Z.record.eventId,eventType:Z.record.eventType,error:W});throw W}}materializeForSpec($,J,Q){let Z=J.dedupeKey??J.eventId,W=$.debounceSeconds??0;if(W>0){let Y=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Z});if(Y){let V=ET(Y.scheduledFor,uH(Q,W)),H=this.store.updateQueuedEventRunForDebounce({runId:Y.runId,triggerEventId:J.eventId,scheduledFor:V});if(H)return{run:H,reason:"dedupe_window"}}}let j=$.dedupeWindowSeconds??0;if(j>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Z,sinceIso:dH(Q,j)}))return{reason:"dedupe_window"};let f=$.cooldownSeconds??0;if(f>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:dH(Q,f)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:J.eventId,scheduledFor:W>0?uH(Q,W):Q}),reason:"dedupe_window"}}}class l6{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},J=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Z of J)if(this.materializeOneOff(Z))$.oneOffQueued+=1;let Q=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Z of Q)try{if(this.materializeSchedule(Z))$.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 uT}from"node:path";import{buildClineSystemPrompt as dT}from"@cline/shared";import{nowIso as lH}from"@cline/shared/db";import{mkdirSync as IT,writeFileSync as xT}from"node:fs";import{join as gT}from"node:path";import{resolveCronReportsDir as mT}from"@cline/shared/storage";function T$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function F2($,J){if(J===void 0||J===null)return;return`${$}: ${T$(J)}`}function vT($,J,Q){let Z=[`runId: ${T$($.runId)}`,`specId: ${T$(J.specId)}`,`externalId: ${T$(J.externalId)}`,`title: ${T$(J.title)}`,`triggerKind: ${T$($.triggerKind)}`,`status: ${T$($.status)}`,`sourcePath: ${T$(J.sourcePath)}`],W=[F2("sessionId",$.sessionId),F2("startedAt",$.startedAt),F2("completedAt",$.completedAt),F2("triggerEventId",$.triggerEventId),F2("triggerEventType",Q?.eventType),F2("triggerEventSource",Q?.source),F2("triggerEventSubject",Q?.subject)];for(let j of W)if(j)Z.push(j);return`---
218
218
  ${Z.join(`
219
219
  `)}
220
220
  ---
@@ -238,16 +238,16 @@ ${Q.join(`
238
238
  `)}
239
239
  `)}return J.join(`
240
240
  `)}function WW($){let J=mT($.specs);IT(J,{recursive:!0});let Q=gT(J,`${$.run.runId}.md`),Z=`${vT($.run,$.spec,$.data.triggerEvent)}
241
- ${cT($.data)}`;return xT(Q,Z,"utf8"),Q}class jW{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,J,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Z=Math.max(1,Math.floor(Q)),W=this.activeExecutions.get($)??new Set;if(W.size>=Z)return!1;return W.add(J),this.activeExecutions.set($,W),!0}release($,J){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(J),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let J of this.activeExecutions.values())$+=J.size;return $}}var lT=15000,pT=90,rH=["rules","skills","plugins"];function rT($,J){return new Set($.extensions??rH).has(J)}function iT($,J){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let Z of $.tools)Q[Z]={enabled:!0,autoApprove:!0};if(J==="yolo")Q[K0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function nT($){let J=$?.trim();if(!J)return;return["# Notes Directory",`Use ${J} 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(`
242
- `)}class fW extends Error{constructor($){super($);this.name="TimeoutError"}}async function aT($,J){if(J<=0)return $;let Q,Z=new Promise((W,j)=>{Q=setTimeout(()=>{j(new fW("cron run timed out"))},J)});try{return await Promise.race([$,Z])}finally{if(Q)clearTimeout(Q)}}class p6{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 jW($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??pT)*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??lT);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 J=[...this.activeRuns.entries()];await Promise.all(J.map(async([Q,Z])=>{if(Z.sessionId)try{await this.options.runtimeHandlers.abortSession(Z.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:Z.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:pH(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((J)=>this.executeClaim(J)))}catch($){let J=this.options.logger;if(J)if(J.error)J.error("cron.runner.tick.failed",{error:$});else J.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,J])=>{let Q=this.store.getRun($);return Q?[{...Q,...J}]:[]})}async executeClaim($){let J=$.run,Q=this.store.getSpec(J.specId);if(!Q){this.store.completeRun(J.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(J.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Z=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,J.runId,Z)){this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,J.runId),this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(J.runId,{claimToken:$.claimToken});let j=J.triggerEventId?this.store.getEventLog(J.triggerEventId):void 0,f,X,Y=Date.now(),V;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)V=Y+Q.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Q);if(f=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!f)throw Error("runtime returned empty sessionId");this.activeRuns.set(J.runId,{claimToken:$.claimToken,sessionId:f}),this.store.attachSessionIdToRun(J.runId,f);let A={config:H,prompt:this.buildPrompt(Q,j)},K=this.options.runtimeHandlers.sendSession(f,A),G=V?Math.max(1,V-Date.now()):0,D=(await aT(K,G)).result,U=Date.now(),F=WW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"done"},spec:Q,data:{finalText:D.text,usage:D.usage,toolCalls:D.toolCalls,durationMs:U-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"done",sessionId:f,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,J.runId),this.store.updateSpecLastRunAt(Q.specId,pH())}catch(H){let B=H instanceof fW;if(f&&B)try{await this.options.runtimeHandlers.abortSession(f)}catch{}let A=H instanceof Error?H.message:String(H),K=Date.now(),G=WW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"failed"},spec:Q,data:{error:A,durationMs:K-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"failed",sessionId:f,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,J.runId)}finally{if(X?.(),f)try{await this.options.runtimeHandlers.stopSession(f)}catch{}this.activeRuns.delete(J.runId),this.limiter.release(Q.specId,J.runId)}}publishScheduleExecutionEvent($,J,Q){if(J.source!=="hub-schedule"||!this.options.eventPublisher)return;let Z=this.store.getRun(Q);if(!Z)return;let W=Z.status==="done"?"success":Z.status==="cancelled"?"aborted":Z.status==="running"?"running":Z.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:J.externalId,executionId:Z.runId,sessionId:Z.sessionId,triggeredAt:new Date(Z.scheduledFor??Z.createdAt).getTime(),startedAt:Z.startedAt?new Date(Z.startedAt).getTime():void 0,endedAt:Z.completedAt?new Date(Z.completedAt).getTime():void 0,status:W,errorMessage:Z.error})}buildPrompt($,J){let Q=$.prompt??"";if(!J)return Q;let Z={eventId:J.eventId,eventType:J.eventType,source:J.source,subject:J.subject,occurredAt:J.occurredAt,workspaceRoot:J.workspaceRoot,dedupeKey:J.dedupeKey,attributes:J.attributes,payload:J.payload};return`${Q}
241
+ ${cT($.data)}`;return xT(Q,Z,"utf8"),Q}class jW{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,J,Q){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Z=Math.max(1,Math.floor(Q)),W=this.activeExecutions.get($)??new Set;if(W.size>=Z)return!1;return W.add(J),this.activeExecutions.set($,W),!0}release($,J){let Q=this.activeExecutions.get($);if(!Q)return;if(Q.delete(J),Q.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let J of this.activeExecutions.values())$+=J.size;return $}}var lT=15000,pT=90,pH=["rules","skills","plugins"];function rT($,J){return new Set($.extensions??pH).has(J)}function iT($,J){if($.tools===void 0)return{"*":{autoApprove:!0}};let Q={"*":{enabled:!1,autoApprove:!0}};for(let Z of $.tools)Q[Z]={enabled:!0,autoApprove:!0};if(J==="yolo")Q[K0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return Q}function nT($){let J=$?.trim();if(!J)return;return["# Notes Directory",`Use ${J} 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(`
242
+ `)}class fW extends Error{constructor($){super($);this.name="TimeoutError"}}async function aT($,J){if(J<=0)return $;let Q,Z=new Promise((W,j)=>{Q=setTimeout(()=>{j(new fW("cron run timed out"))},J)});try{return await Promise.race([$,Z])}finally{if(Q)clearTimeout(Q)}}class p6{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 jW($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??pT)*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??lT);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 J=[...this.activeRuns.entries()];await Promise.all(J.map(async([Q,Z])=>{if(Z.sessionId)try{await this.options.runtimeHandlers.abortSession(Z.sessionId)}catch{}try{this.store.requeueRun({runId:Q,claimToken:Z.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:lH(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((J)=>this.executeClaim(J)))}catch($){let J=this.options.logger;if(J)if(J.error)J.error("cron.runner.tick.failed",{error:$});else J.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,J])=>{let Q=this.store.getRun($);return Q?[{...Q,...J}]:[]})}async executeClaim($){let J=$.run,Q=this.store.getSpec(J.specId);if(!Q){this.store.completeRun(J.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!Q.enabled||Q.removed){this.store.completeRun(J.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Z=Q.maxParallel&&Q.maxParallel>0?Q.maxParallel:1;if(!this.limiter.acquire(Q.specId,J.runId,Z)){this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(Q.specId,J.runId),this.store.requeueRun({runId:J.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(J.runId,{claimToken:$.claimToken});let j=J.triggerEventId?this.store.getEventLog(J.triggerEventId):void 0,f,X,Y=Date.now(),V;if(Q.timeoutSeconds&&Q.timeoutSeconds>0)V=Y+Q.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let H=await this.buildStartRequest(Q);if(f=(await this.options.runtimeHandlers.startSession(H)).sessionId.trim(),!f)throw Error("runtime returned empty sessionId");this.activeRuns.set(J.runId,{claimToken:$.claimToken,sessionId:f}),this.store.attachSessionIdToRun(J.runId,f);let A={config:H,prompt:this.buildPrompt(Q,j)},K=this.options.runtimeHandlers.sendSession(f,A),G=V?Math.max(1,V-Date.now()):0,D=(await aT(K,G)).result,U=Date.now(),F=WW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"done"},spec:Q,data:{finalText:D.text,usage:D.usage,toolCalls:D.toolCalls,durationMs:U-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"done",sessionId:f,reportPath:F,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",Q,J.runId),this.store.updateSpecLastRunAt(Q.specId,lH())}catch(H){let B=H instanceof fW;if(f&&B)try{await this.options.runtimeHandlers.abortSession(f)}catch{}let A=H instanceof Error?H.message:String(H),K=Date.now(),G=WW({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...J,sessionId:f,status:"failed"},spec:Q,data:{error:A,durationMs:K-Y,triggerEvent:j}});this.store.completeRun(J.runId,{status:"failed",sessionId:f,reportPath:G,error:A,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",Q,J.runId)}finally{if(X?.(),f)try{await this.options.runtimeHandlers.stopSession(f)}catch{}this.activeRuns.delete(J.runId),this.limiter.release(Q.specId,J.runId)}}publishScheduleExecutionEvent($,J,Q){if(J.source!=="hub-schedule"||!this.options.eventPublisher)return;let Z=this.store.getRun(Q);if(!Z)return;let W=Z.status==="done"?"success":Z.status==="cancelled"?"aborted":Z.status==="running"?"running":Z.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:J.externalId,executionId:Z.runId,sessionId:Z.sessionId,triggeredAt:new Date(Z.scheduledFor??Z.createdAt).getTime(),startedAt:Z.startedAt?new Date(Z.startedAt).getTime():void 0,endedAt:Z.completedAt?new Date(Z.completedAt).getTime():void 0,status:W,errorMessage:Z.error})}buildPrompt($,J){let Q=$.prompt??"";if(!J)return Q;let Z={eventId:J.eventId,eventType:J.eventType,source:J.source,subject:J.subject,occurredAt:J.occurredAt,workspaceRoot:J.workspaceRoot,dedupeKey:J.dedupeKey,attributes:J.attributes,payload:J.payload};return`${Q}
243
243
 
244
244
  Trigger event:
245
- ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let Z=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Z))clearInterval(Q)},J);return()=>clearInterval(Q)}async buildSystemPrompt($,J,Q,Z){let W=nT($.notesDirectory),j=N8(void 0,W),f=await z6(J),X=dT({ide:"Cline Cron",workspaceRoot:J,workspaceName:uT(J),metadata:f,rules:$.systemPrompt?void 0:j,mode:Q,providerId:Z,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?N8(X,j)??X:X}async buildStartRequest($){let J=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),Z=($.modelId??"").trim(),W=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():J;if(!J)throw Error("cron spec requires workspaceRoot");let f=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:J,cwd:j,provider:Q,model:Z,mode:f,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,J,f,Q),maxIterations:$.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:iT($,f),configExtensions:rH.filter((X)=>rT($,X))}}}import{existsSync as RM,readdirSync as zM,readFileSync as LM,statSync as _M}from"node:fs";import{relative as OM}from"node:path";import{resolveCronSpecsDir as TM}from"@cline/shared/storage";function r6($,J,Q,Z){let W=new Set;function j(f){let X=f.toLowerCase();if(Z){let V=Z.indexOf(X);if(V!==-1)return V+J}let Y=Number(f);if(!Number.isInteger(Y)||Y<J||Y>Q)throw Error(`Invalid cron value "${f}" for range [${J}-${Q}]`);return Y}for(let f of $.split(",")){if(f==="*"){for(let V=J;V<=Q;V+=1)W.add(V);continue}let X=f.indexOf("/");if(X!==-1){let V=f.slice(0,X),H=Number(f.slice(X+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${f.slice(X+1)}"`);let B=J,A=Q;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)B=j(V.slice(0,K)),A=j(V.slice(K+1));else B=j(V)}if(B>A)throw Error(`Invalid cron range "${V}"`);for(let K=B;K<=A;K+=H)W.add(K);continue}let Y=f.indexOf("-");if(Y!==-1){let V=j(f.slice(0,Y)),H=j(f.slice(Y+1));if(V>H)throw Error(`Invalid cron range "${f}"`);for(let B=V;B<=H;B+=1)W.add(B);continue}W.add(j(f))}return[...W].sort((f,X)=>f-X)}var sT=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],nH=["sun","mon","tue","wed","thu","fri","sat"];function i6($,J,Q){let Z=$[J];if(typeof Z!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${J+1}`);return Z}function XW($,J){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${J}`);return Q}function YW($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${J.length}`);return{minutes:r6(i6(J,0,$),0,59),hours:r6(i6(J,1,$),0,23),daysOfMonth:r6(i6(J,2,$),1,31),months:r6(i6(J,3,$),1,12,sT),daysOfWeek:r6(i6(J,4,$),0,6,nH)}}function VW($){YW($)}function aH($,J,Q=Date.now()){D2($,Q,J)}var iH=new Map,oT=new Map(nH.map(($,J)=>[$,J]));function sH($){let J=$?.trim();return J?J:void 0}function oH($){let J=iH.get($);if(J)return J;let Q=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return iH.set($,Q),Q}function tT($){let J=sH($);if(!J)return;oH(J).format(new Date)}function eT($,J){let Q=oH(J).formatToParts(new Date($)),Z=new Map(Q.map((f)=>[f.type,f.value])),W=Z.get("weekday")?.toLowerCase().slice(0,3)??"",j=oT.get(W);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${J}"`);return{month:Number(Z.get("month")),dayOfMonth:Number(Z.get("day")),dayOfWeek:j,hour:Number(Z.get("hour")),minute:Number(Z.get("minute"))}}function $M($){let J=new Date($);return{month:J.getMonth()+1,dayOfMonth:J.getDate(),dayOfWeek:J.getDay(),hour:J.getHours(),minute:J.getMinutes()}}function JM($,J){return $.months.includes(J.month)&&$.daysOfMonth.includes(J.dayOfMonth)&&$.daysOfWeek.includes(J.dayOfWeek)&&$.hours.includes(J.hour)&&$.minutes.includes(J.minute)}function QM($,J,Q){let Z=YW($),W=new Date(J);W.setSeconds(0,0);let j=W.getTime()+60000,f=new Date(J);f.setFullYear(f.getFullYear()+4);let X=f.getTime();while(j<=X){if(JM(Z,eT(j,Q)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function D2($,J,Q){let Z=sH(Q);if(Z)return tT(Z),QM($,J,Z);let W=YW($),j=new Date(J);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let f=new Date(J);f.setFullYear(f.getFullYear()+4);while(j<=f){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:H,minute:B}=$M(j.getTime());if(!W.months.includes(X)){let A=W.months.find((G)=>G>X)??XW(W.months,"months"),K=A<=X?1:0;j=new Date(j.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(Y)||!W.daysOfWeek.includes(V)){j=new Date(j.getFullYear(),j.getMonth(),Y+1,0,0,0,0);continue}if(!W.hours.includes(H)){let A=W.hours.find((G)=>G>H)??XW(W.hours,"hours"),K=A<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+K,A,0,0,0);continue}if(!W.minutes.includes(B)){let A=W.minutes.find((G)=>G>B)??XW(W.minutes,"minutes"),K=A<=B?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+K,A,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as ZM}from"node:crypto";import WM from"yaml";function jM($){let J=$.replace(/\\/g,"/");if(J.startsWith("events/")&&J.endsWith(".event.md"))return"event";if(J.endsWith(".cron.md"))return"schedule";return"one_off"}function fM($){let J=$.replace(/\r\n/g,`
245
+ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Math.floor(this.claimLeaseMs/2)),Q=setInterval(()=>{let Z=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Z))clearInterval(Q)},J);return()=>clearInterval(Q)}async buildSystemPrompt($,J,Q,Z){let W=nT($.notesDirectory),j=N8(void 0,W),f=await z6(J),X=dT({ide:"Cline Cron",workspaceRoot:J,workspaceName:uT(J),metadata:f,rules:$.systemPrompt?void 0:j,mode:Q,providerId:Z,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?N8(X,j)??X:X}async buildStartRequest($){let J=($.workspaceRoot??"").trim(),Q=($.providerId??"").trim(),Z=($.modelId??"").trim(),W=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,j=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():J;if(!J)throw Error("cron spec requires workspaceRoot");let f=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:J,cwd:j,provider:Q,model:Z,mode:f,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,J,f,Q),maxIterations:$.maxIterations,enableTools:W?.enableTools??!0,enableSpawn:W?.enableSpawn??!0,enableTeams:W?.enableTeams??!0,autoApproveTools:W?.autoApproveTools??!0,toolPolicies:iT($,f),configExtensions:pH.filter((X)=>rT($,X))}}}import{existsSync as RM,readdirSync as zM,readFileSync as LM,statSync as _M}from"node:fs";import{relative as OM}from"node:path";import{resolveCronSpecsDir as TM}from"@cline/shared/storage";function r6($,J,Q,Z){let W=new Set;function j(f){let X=f.toLowerCase();if(Z){let V=Z.indexOf(X);if(V!==-1)return V+J}let Y=Number(f);if(!Number.isInteger(Y)||Y<J||Y>Q)throw Error(`Invalid cron value "${f}" for range [${J}-${Q}]`);return Y}for(let f of $.split(",")){if(f==="*"){for(let V=J;V<=Q;V+=1)W.add(V);continue}let X=f.indexOf("/");if(X!==-1){let V=f.slice(0,X),H=Number(f.slice(X+1));if(!Number.isInteger(H)||H<1)throw Error(`Invalid step "${f.slice(X+1)}"`);let B=J,A=Q;if(V!=="*"){let K=V.indexOf("-");if(K!==-1)B=j(V.slice(0,K)),A=j(V.slice(K+1));else B=j(V)}if(B>A)throw Error(`Invalid cron range "${V}"`);for(let K=B;K<=A;K+=H)W.add(K);continue}let Y=f.indexOf("-");if(Y!==-1){let V=j(f.slice(0,Y)),H=j(f.slice(Y+1));if(V>H)throw Error(`Invalid cron range "${f}"`);for(let B=V;B<=H;B+=1)W.add(B);continue}W.add(j(f))}return[...W].sort((f,X)=>f-X)}var sT=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],iH=["sun","mon","tue","wed","thu","fri","sat"];function i6($,J,Q){let Z=$[J];if(typeof Z!=="string")throw Error(`Invalid cron pattern "${Q}": missing field ${J+1}`);return Z}function XW($,J){let Q=$[0];if(typeof Q!=="number")throw Error(`Invalid cron pattern: no values parsed for ${J}`);return Q}function YW($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${J.length}`);return{minutes:r6(i6(J,0,$),0,59),hours:r6(i6(J,1,$),0,23),daysOfMonth:r6(i6(J,2,$),1,31),months:r6(i6(J,3,$),1,12,sT),daysOfWeek:r6(i6(J,4,$),0,6,iH)}}function VW($){YW($)}function nH($,J,Q=Date.now()){D2($,Q,J)}var rH=new Map,oT=new Map(iH.map(($,J)=>[$,J]));function aH($){let J=$?.trim();return J?J:void 0}function sH($){let J=rH.get($);if(J)return J;let Q=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return rH.set($,Q),Q}function tT($){let J=aH($);if(!J)return;sH(J).format(new Date)}function eT($,J){let Q=sH(J).formatToParts(new Date($)),Z=new Map(Q.map((f)=>[f.type,f.value])),W=Z.get("weekday")?.toLowerCase().slice(0,3)??"",j=oT.get(W);if(j===void 0)throw Error(`Unable to resolve weekday for timezone "${J}"`);return{month:Number(Z.get("month")),dayOfMonth:Number(Z.get("day")),dayOfWeek:j,hour:Number(Z.get("hour")),minute:Number(Z.get("minute"))}}function $M($){let J=new Date($);return{month:J.getMonth()+1,dayOfMonth:J.getDate(),dayOfWeek:J.getDay(),hour:J.getHours(),minute:J.getMinutes()}}function JM($,J){return $.months.includes(J.month)&&$.daysOfMonth.includes(J.dayOfMonth)&&$.daysOfWeek.includes(J.dayOfWeek)&&$.hours.includes(J.hour)&&$.minutes.includes(J.minute)}function QM($,J,Q){let Z=YW($),W=new Date(J);W.setSeconds(0,0);let j=W.getTime()+60000,f=new Date(J);f.setFullYear(f.getFullYear()+4);let X=f.getTime();while(j<=X){if(JM(Z,eT(j,Q)))return j;j+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${Q}"`)}function D2($,J,Q){let Z=aH(Q);if(Z)return tT(Z),QM($,J,Z);let W=YW($),j=new Date(J);j.setSeconds(0,0),j=new Date(j.getTime()+60000);let f=new Date(J);f.setFullYear(f.getFullYear()+4);while(j<=f){let{month:X,dayOfMonth:Y,dayOfWeek:V,hour:H,minute:B}=$M(j.getTime());if(!W.months.includes(X)){let A=W.months.find((G)=>G>X)??XW(W.months,"months"),K=A<=X?1:0;j=new Date(j.getFullYear()+K,A-1,1,0,0,0,0);continue}if(!W.daysOfMonth.includes(Y)||!W.daysOfWeek.includes(V)){j=new Date(j.getFullYear(),j.getMonth(),Y+1,0,0,0,0);continue}if(!W.hours.includes(H)){let A=W.hours.find((G)=>G>H)??XW(W.hours,"hours"),K=A<=H?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate()+K,A,0,0,0);continue}if(!W.minutes.includes(B)){let A=W.minutes.find((G)=>G>B)??XW(W.minutes,"minutes"),K=A<=B?1:0;j=new Date(j.getFullYear(),j.getMonth(),j.getDate(),j.getHours()+K,A,0,0);continue}return j.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as ZM}from"node:crypto";import WM from"yaml";function jM($){let J=$.replace(/\\/g,"/");if(J.startsWith("events/")&&J.endsWith(".event.md"))return"event";if(J.endsWith(".cron.md"))return"schedule";return"one_off"}function fM($){let J=$.replace(/\r\n/g,`
246
246
  `);if(!J.startsWith(`---
247
247
  `))return{frontmatter:void 0,body:$};let Q=J.slice(4),Z=Q.indexOf(`
248
248
  ---`);if(Z===-1)return{frontmatter:void 0,body:$};let W=Q.slice(0,Z),j=Q.slice(Z+4);if(j.startsWith(`
249
- `))j=j.slice(1);return{frontmatter:W,body:j}}function p0($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function XM($){if(!Array.isArray($))return;let J=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return J.length>0?J:void 0}function AW($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function YM($){let J=AW($);if(!J)return;let Q=p0(J.providerId),Z=p0(J.modelId);if(Q===void 0&&Z===void 0)return;return{providerId:Q,modelId:Z}}function VM($){if(typeof $!=="string")return;let J=$.trim().toLowerCase();if(J==="act"||J==="plan"||J==="yolo")return J;return}function eH($,J={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let Z=[...new Set(Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray($)&&J.preserveEmptyArray)return Z;return Z.length>0?Z:void 0}var HM=new Set(W$);function BM($){let J=eH($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!HM.has(Z));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return J}var AM=new Set(["rules","skills","plugins"]);function KM($){let J=eH($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!AM.has(Z));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return J}function HW($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function BW($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function KW($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>KW(Q)).join(",")}]`;let J=Object.entries($).filter(([,Q])=>Q!==void 0);return J.sort(([Q],[Z])=>Q<Z?-1:Q>Z?1:0),`{${J.map(([Q,Z])=>`${JSON.stringify(Q)}:${KW(Z)}`).join(",")}}`}function $B($,J){let Q=ZM("sha256");return Q.update(KW($)),Q.update(`
250
- `),Q.update(J),Q.digest("hex")}function GM($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var FM=["schedule","timezone"],DM=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],UM=["cwd"];function tH($,J,Q,Z,W){return{externalId:$,relativePath:$,triggerKind:J,body:Q,contentHash:$B(Z,Q),error:W}}function K1($,J,Q,Z,W,j){return{externalId:$,relativePath:J,triggerKind:Q,body:Z,contentHash:W,error:j}}function JB($){let J=$.relativePath.replace(/\\/g,"/"),Q=jM(J),{frontmatter:Z,body:W}=fM($.raw),j={};if(Z!==void 0&&Z.trim().length>0)try{let F=WM.parse(Z);if(F&&typeof F==="object"&&!Array.isArray(F))j=F;else if(F!==null&&F!==void 0)return tH(J,Q,W,{},"frontmatter must be a YAML mapping")}catch(F){return tH(J,Q,W,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let f=$B(j,W),X=p0(j.id),Y=X??J;if(Q!=="schedule"){for(let F of FM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of UM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let F of DM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is only allowed on .event.md specs`)}let V=p0(j.prompt),H=W.trim(),B=V??(H.length>0?H:void 0);if(!B)return K1(Y,J,Q,W,f,"prompt is required (frontmatter `prompt` or markdown body)");let A=p0(j.workspaceRoot);if(!A)return K1(Y,J,Q,W,f,"workspaceRoot is required");let K,G;try{K=BM(j.tools),G=KM(j.extensions)}catch(F){return K1(Y,J,Q,W,f,F instanceof Error?F.message:String(F))}let R=VM(j.mode);if(j.mode!==void 0&&R===void 0)return K1(Y,J,Q,W,f,"mode must be one of: act, plan, yolo");let D={id:X,title:p0(j.title)??X??GM(J),prompt:B,workspaceRoot:A,mode:R??"yolo",systemPrompt:p0(j.systemPrompt),modelSelection:YM(j.modelSelection),maxIterations:HW(j.maxIterations),timeoutSeconds:HW(j.timeoutSeconds),tools:K,notesDirectory:p0(j.notesDirectory),extensions:G,source:p0(j.source)??"user",tags:XM(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:AW(j.metadata)},U;if(Q==="schedule"){let F=p0(j.schedule);if(!F)return K1(Y,J,Q,W,f,"schedule is required for *.cron.md specs");let O=p0(j.timezone);try{aH(F,O)}catch(L){return K1(Y,J,Q,W,f,L instanceof Error?L.message:String(L))}U={...D,triggerKind:"schedule",schedule:F,timezone:O}}else if(Q==="event"){let F=p0(j.event);if(!F)return K1(Y,J,Q,W,f,"event is required for .event.md specs");U={...D,triggerKind:"event",event:F,filters:AW(j.filters),debounceSeconds:BW(j.debounceSeconds),dedupeWindowSeconds:BW(j.dedupeWindowSeconds),cooldownSeconds:BW(j.cooldownSeconds),maxParallel:HW(j.maxParallel)}}else U={...D,triggerKind:"one_off"};return{externalId:Y,relativePath:J,triggerKind:Q,body:W,contentHash:f,spec:U}}function MM($,J){return OM($,J).replace(/\\/g,"/")}function qM($){if(!RM($))return[];let J=[],Q=[$];while(Q.length>0){let Z=Q.pop();if(!Z)continue;let W;try{W=zM(Z,{withFileTypes:!0})}catch{continue}for(let j of W){let f=`${Z}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Q.push(f);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;J.push(f)}}return J}class GW{store;cronDir;constructor($){this.store=$.store,this.cronDir=TM($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},J=qM(this.cronDir),Q=new Set;for(let W of J){let j=MM(this.cronDir,W);Q.add(j),$.scanned+=1;let f=await this.reconcileFile(j,W);if(f){if($.changes.push(f),$.upserted+=1,f.parse.error)$.invalidParses+=1}}let Z=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of Z)if(!Q.has(W.sourcePath))this.handleFileDeleted(W),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,J){let Q=this.store.getSpecBySourcePath($),Z,W;try{Z=LM(J,"utf8"),W=_M(J).mtimeMs}catch{return}let f=JB({relativePath:$,raw:Z}),X=this.store.upsertSpec({externalId:f.externalId,sourcePath:$,triggerKind:f.triggerKind,sourceMtimeMs:W,sourceHash:f.contentHash,parseStatus:f.error?"invalid":"valid",parseError:f.error,spec:f.spec});if(!f.error&&f.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==X.record.scheduleExpr||Q.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:f}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let J of $)this.applyScheduleNextRunAt(J,{forceReset:!1})}applyScheduleNextRunAt($,J){if(!$.scheduleExpr)return;if(!J.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),Z=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,W=D2($.scheduleExpr,Z,$.timezone),j=new Date(W).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as PM,mkdirSync as NM,watch as wM}from"node:fs";import{relative as SM,resolve as CM}from"node:path";var yM=250;class FW{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??yM),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{NM($,{recursive:!0}),this.watcher=wM($,{recursive:!0},(J,Q)=>{if(!Q)return;let Z=String(Q).replace(/\\/g,"/");if(!Z.endsWith(".md"))return;if(Z.startsWith("reports/"))return;this.scheduleReconcile(Z)}),this.watcher.on("error",this.onError)}catch(J){this.onError(J)}}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 J=this.pending.get($);if(J)clearTimeout(J);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let J=CM(this.reconciler.getCronDir(),$);if(!PM(J)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=SM(this.reconciler.getCronDir(),J).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,J),await this.onReconciled()}catch(J){this.onError(J)}}}import{randomUUID as n6}from"node:crypto";import{asOptionalString as g,asString as s,loadSqliteDb as bM,nowIso as _0}from"@cline/shared/db";import{resolveCronDbPath as hM}from"@cline/shared/storage";var EM=[`CREATE TABLE IF NOT EXISTS cron_specs (
249
+ `))j=j.slice(1);return{frontmatter:W,body:j}}function p0($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function XM($){if(!Array.isArray($))return;let J=$.map((Q)=>typeof Q==="string"?Q.trim():"").filter((Q)=>Q.length>0);return J.length>0?J:void 0}function AW($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function YM($){let J=AW($);if(!J)return;let Q=p0(J.providerId),Z=p0(J.modelId);if(Q===void 0&&Z===void 0)return;return{providerId:Q,modelId:Z}}function VM($){if(typeof $!=="string")return;let J=$.trim().toLowerCase();if(J==="act"||J==="plan"||J==="yolo")return J;return}function tH($,J={}){let Q=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!Q)return;let Z=[...new Set(Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0))];if(Array.isArray($)&&J.preserveEmptyArray)return Z;return Z.length>0?Z:void 0}var HM=new Set(W$);function BM($){let J=tH($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!HM.has(Z));if(Q.length>0)throw Error(`unknown tool(s): ${Q.join(", ")}`);return J}var AM=new Set(["rules","skills","plugins"]);function KM($){let J=tH($,{preserveEmptyArray:!0});if(!J)return;let Q=J.filter((Z)=>!AM.has(Z));if(Q.length>0)throw Error(`unknown extension(s): ${Q.join(", ")}`);return J}function HW($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function BW($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function KW($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((Q)=>KW(Q)).join(",")}]`;let J=Object.entries($).filter(([,Q])=>Q!==void 0);return J.sort(([Q],[Z])=>Q<Z?-1:Q>Z?1:0),`{${J.map(([Q,Z])=>`${JSON.stringify(Q)}:${KW(Z)}`).join(",")}}`}function eH($,J){let Q=ZM("sha256");return Q.update(KW($)),Q.update(`
250
+ `),Q.update(J),Q.digest("hex")}function GM($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var FM=["schedule","timezone"],DM=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],UM=["cwd"];function oH($,J,Q,Z,W){return{externalId:$,relativePath:$,triggerKind:J,body:Q,contentHash:eH(Z,Q),error:W}}function K1($,J,Q,Z,W,j){return{externalId:$,relativePath:J,triggerKind:Q,body:Z,contentHash:W,error:j}}function $B($){let J=$.relativePath.replace(/\\/g,"/"),Q=jM(J),{frontmatter:Z,body:W}=fM($.raw),j={};if(Z!==void 0&&Z.trim().length>0)try{let F=WM.parse(Z);if(F&&typeof F==="object"&&!Array.isArray(F))j=F;else if(F!==null&&F!==void 0)return oH(J,Q,W,{},"frontmatter must be a YAML mapping")}catch(F){return oH(J,Q,W,{},F instanceof Error?`failed to parse frontmatter: ${F.message}`:"failed to parse frontmatter")}let f=eH(j,W),X=p0(j.id),Y=X??J;if(Q!=="schedule"){for(let F of FM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is only allowed on *.cron.md specs`)}for(let F of UM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is no longer supported; cron specs use workspaceRoot as cwd`);if(Q!=="event"){for(let F of DM)if(j[F]!==void 0)return K1(Y,J,Q,W,f,`field "${F}" is only allowed on .event.md specs`)}let V=p0(j.prompt),H=W.trim(),B=V??(H.length>0?H:void 0);if(!B)return K1(Y,J,Q,W,f,"prompt is required (frontmatter `prompt` or markdown body)");let A=p0(j.workspaceRoot);if(!A)return K1(Y,J,Q,W,f,"workspaceRoot is required");let K,G;try{K=BM(j.tools),G=KM(j.extensions)}catch(F){return K1(Y,J,Q,W,f,F instanceof Error?F.message:String(F))}let R=VM(j.mode);if(j.mode!==void 0&&R===void 0)return K1(Y,J,Q,W,f,"mode must be one of: act, plan, yolo");let D={id:X,title:p0(j.title)??X??GM(J),prompt:B,workspaceRoot:A,mode:R??"yolo",systemPrompt:p0(j.systemPrompt),modelSelection:YM(j.modelSelection),maxIterations:HW(j.maxIterations),timeoutSeconds:HW(j.timeoutSeconds),tools:K,notesDirectory:p0(j.notesDirectory),extensions:G,source:p0(j.source)??"user",tags:XM(j.tags),enabled:typeof j.enabled==="boolean"?j.enabled:!0,metadata:AW(j.metadata)},U;if(Q==="schedule"){let F=p0(j.schedule);if(!F)return K1(Y,J,Q,W,f,"schedule is required for *.cron.md specs");let O=p0(j.timezone);try{nH(F,O)}catch(L){return K1(Y,J,Q,W,f,L instanceof Error?L.message:String(L))}U={...D,triggerKind:"schedule",schedule:F,timezone:O}}else if(Q==="event"){let F=p0(j.event);if(!F)return K1(Y,J,Q,W,f,"event is required for .event.md specs");U={...D,triggerKind:"event",event:F,filters:AW(j.filters),debounceSeconds:BW(j.debounceSeconds),dedupeWindowSeconds:BW(j.dedupeWindowSeconds),cooldownSeconds:BW(j.cooldownSeconds),maxParallel:HW(j.maxParallel)}}else U={...D,triggerKind:"one_off"};return{externalId:Y,relativePath:J,triggerKind:Q,body:W,contentHash:f,spec:U}}function MM($,J){return OM($,J).replace(/\\/g,"/")}function qM($){if(!RM($))return[];let J=[],Q=[$];while(Q.length>0){let Z=Q.pop();if(!Z)continue;let W;try{W=zM(Z,{withFileTypes:!0})}catch{continue}for(let j of W){let f=`${Z}/${j.name}`;if(j.isDirectory()){if(j.name==="reports")continue;Q.push(f);continue}if(!j.isFile())continue;if(!j.name.endsWith(".md"))continue;J.push(f)}}return J}class GW{store;cronDir;constructor($){this.store=$.store,this.cronDir=TM($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},J=qM(this.cronDir),Q=new Set;for(let W of J){let j=MM(this.cronDir,W);Q.add(j),$.scanned+=1;let f=await this.reconcileFile(j,W);if(f){if($.changes.push(f),$.upserted+=1,f.parse.error)$.invalidParses+=1}}let Z=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let W of Z)if(!Q.has(W.sourcePath))this.handleFileDeleted(W),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,J){let Q=this.store.getSpecBySourcePath($),Z,W;try{Z=LM(J,"utf8"),W=_M(J).mtimeMs}catch{return}let f=$B({relativePath:$,raw:Z}),X=this.store.upsertSpec({externalId:f.externalId,sourcePath:$,triggerKind:f.triggerKind,sourceMtimeMs:W,sourceHash:f.contentHash,parseStatus:f.error?"invalid":"valid",parseError:f.error,spec:f.spec});if(!f.error&&f.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!Q||Q.removed||!Q.enabled||Q.scheduleExpr!==X.record.scheduleExpr||Q.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:f}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let J of $)this.applyScheduleNextRunAt(J,{forceReset:!1})}applyScheduleNextRunAt($,J){if(!$.scheduleExpr)return;if(!J.forceReset&&$.nextRunAt)return;try{let Q=Date.now(),Z=$.lastRunAt?Math.max(Q,new Date($.lastRunAt).getTime()):Q,W=D2($.scheduleExpr,Z,$.timezone),j=new Date(W).toISOString();if($.nextRunAt!==j)this.store.updateSpecNextRunAt($.specId,j)}catch{}}}import{existsSync as PM,mkdirSync as NM,watch as wM}from"node:fs";import{relative as SM,resolve as CM}from"node:path";var yM=250;class FW{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??yM),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{NM($,{recursive:!0}),this.watcher=wM($,{recursive:!0},(J,Q)=>{if(!Q)return;let Z=String(Q).replace(/\\/g,"/");if(!Z.endsWith(".md"))return;if(Z.startsWith("reports/"))return;this.scheduleReconcile(Z)}),this.watcher.on("error",this.onError)}catch(J){this.onError(J)}}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 J=this.pending.get($);if(J)clearTimeout(J);let Q=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,Q)}async reconcileNow($){try{let J=CM(this.reconciler.getCronDir(),$);if(!PM(J)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let Q=SM(this.reconciler.getCronDir(),J).replace(/\\/g,"/");await this.reconciler.reconcileFile(Q,J),await this.onReconciled()}catch(J){this.onError(J)}}}import{randomUUID as n6}from"node:crypto";import{asOptionalString as g,asString as s,loadSqliteDb as bM,nowIso as _0}from"@cline/shared/db";import{resolveCronDbPath as hM}from"@cline/shared/storage";var EM=[`CREATE TABLE IF NOT EXISTS cron_specs (
251
251
  spec_id TEXT PRIMARY KEY,
252
252
  external_id TEXT NOT NULL,
253
253
  source_path TEXT NOT NULL UNIQUE,
@@ -338,11 +338,11 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
338
338
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
339
339
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
340
340
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
341
- ON cron_specs(source_path);`];function QB($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let J of EM)$.exec(J)}function xQ($){if(!$)return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function DW($,J={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let Z=Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if(J.preserveEmpty)return Z;return Z.length>0?Z:void 0}catch{return}}function U2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function M$($){return{specId:s($.spec_id),externalId:s($.external_id),sourcePath:s($.source_path),triggerKind:s($.trigger_kind),sourceMtimeMs:U2($.source_mtime_ms),sourceHash:g($.source_hash),parseStatus:s($.parse_status)==="invalid"?"invalid":"valid",parseError:g($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:s($.title),prompt:g($.prompt),workspaceRoot:g($.workspace_root),scheduleExpr:g($.schedule_expr),timezone:g($.timezone),eventType:g($.event_type),filters:xQ(g($.filters_json)),debounceSeconds:U2($.debounce_seconds),dedupeWindowSeconds:U2($.dedupe_window_seconds),cooldownSeconds:U2($.cooldown_seconds),mode:g($.mode),systemPrompt:g($.system_prompt),providerId:g($.provider_id),modelId:g($.model_id),maxIterations:U2($.max_iterations),timeoutSeconds:U2($.timeout_seconds),maxParallel:U2($.max_parallel),tools:DW(g($.tools_json),{preserveEmpty:!0}),notesDirectory:g($.notes_directory),extensions:DW(g($.extensions_json),{preserveEmpty:!0}),source:g($.source),tags:DW(g($.tags_json)),metadata:xQ(g($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:g($.last_materialized_run_id),lastRunAt:g($.last_run_at),nextRunAt:g($.next_run_at),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function UW($){return{runId:s($.run_id),specId:s($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:s($.trigger_kind),status:s($.status),claimToken:g($.claim_token),claimStartedAt:g($.claim_started_at),claimUntilAt:g($.claim_until_at),scheduledFor:g($.scheduled_for),triggerEventId:g($.trigger_event_id),startedAt:g($.started_at),completedAt:g($.completed_at),sessionId:g($.session_id),reportPath:g($.report_path),error:g($.error),attemptCount:Number($.attempt_count??0),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function ZB($){return{eventId:s($.event_id),eventType:s($.event_type),source:s($.source),subject:g($.subject),occurredAt:s($.occurred_at),receivedAt:s($.received_at),workspaceRoot:g($.workspace_root),dedupeKey:g($.dedupe_key),payload:xQ(g($.payload_json)),attributes:xQ(g($.attributes_json)),processingStatus:s($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:g($.error),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function WB($){return $?JSON.stringify($):null}var kM=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function jB($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function IM($,J,Q,Z){for(let W of kM){let j=$[W],f=J[W];if(jB(j)!==jB(f))return!0}if(Q===!1&&Z===!0)return!0;return!1}function xM($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function gM($){return`hub/schedules/${$}.cron.md`}function mM($){let J={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(J).length>0?J:void 0}function RW($){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((J)=>J.trim().length>0),enabled:$.enabled!==!1,metadata:mM($)}}function fB($){return JSON.stringify(RW($))}function vM($,J){let Q=$.metadata?{...$.metadata}:{},Z=J.createdBy===null?void 0:J.createdBy!==void 0?J.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,W=J.cwd!==void 0?J.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,j=J.runtimeOptions!==void 0?J.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:J.name??$.title,cronPattern:J.cronPattern??$.scheduleExpr??"",prompt:J.prompt??$.prompt??"",workspaceRoot:J.workspaceRoot??$.workspaceRoot??"",cwd:W,modelSelection:J.modelSelection!==void 0?J.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:J.enabled??$.enabled,mode:J.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:J.systemPrompt===null?void 0:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,maxIterations:J.maxIterations===null?void 0:J.maxIterations!==void 0?J.maxIterations:$.maxIterations,timeoutSeconds:J.timeoutSeconds===null?void 0:J.timeoutSeconds!==void 0?J.timeoutSeconds:$.timeoutSeconds,maxParallel:J.maxParallel??$.maxParallel??1,createdBy:Z,tags:J.tags??$.tags,runtimeOptions:j,metadata:J.metadata!==void 0?J.metadata:Object.keys(Q).length>0?Q:void 0}}class a6{db;constructor($={}){let J=$.dbPath??hM();this.db=bM(J),QB(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return J?M$(J):void 0}getSpec($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return J?M$(J):void 0}getSpecByExternalId($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return J?M$(J):void 0}listSpecs($={}){let J=[],Q=[];if($.triggerKind)J.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)J.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)J.push("removed = 0");let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>M$(f))}createHubSchedule($){let J=`sched_${n6()}`,Q=this.upsertSpec({externalId:J,sourcePath:gM(J),triggerKind:"schedule",sourceHash:fB($),parseStatus:"valid",spec:RW($)});this.initializeScheduleNextRun(Q.record.specId);let Z=this.getSpec(Q.record.specId);if(!Z)throw Error("failed to create hub schedule");return Z}getHubSchedule($){let J=this.db.prepare(`SELECT * FROM cron_specs
341
+ ON cron_specs(source_path);`];function JB($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let J of EM)$.exec(J)}function x9($){if(!$)return;try{let J=JSON.parse($);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function DW($,J={}){if(!$)return;try{let Q=JSON.parse($);if(!Array.isArray(Q))return;let Z=Q.map((W)=>typeof W==="string"?W.trim():"").filter((W)=>W.length>0);if(J.preserveEmpty)return Z;return Z.length>0?Z:void 0}catch{return}}function U2($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function M$($){return{specId:s($.spec_id),externalId:s($.external_id),sourcePath:s($.source_path),triggerKind:s($.trigger_kind),sourceMtimeMs:U2($.source_mtime_ms),sourceHash:g($.source_hash),parseStatus:s($.parse_status)==="invalid"?"invalid":"valid",parseError:g($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:s($.title),prompt:g($.prompt),workspaceRoot:g($.workspace_root),scheduleExpr:g($.schedule_expr),timezone:g($.timezone),eventType:g($.event_type),filters:x9(g($.filters_json)),debounceSeconds:U2($.debounce_seconds),dedupeWindowSeconds:U2($.dedupe_window_seconds),cooldownSeconds:U2($.cooldown_seconds),mode:g($.mode),systemPrompt:g($.system_prompt),providerId:g($.provider_id),modelId:g($.model_id),maxIterations:U2($.max_iterations),timeoutSeconds:U2($.timeout_seconds),maxParallel:U2($.max_parallel),tools:DW(g($.tools_json),{preserveEmpty:!0}),notesDirectory:g($.notes_directory),extensions:DW(g($.extensions_json),{preserveEmpty:!0}),source:g($.source),tags:DW(g($.tags_json)),metadata:x9(g($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:g($.last_materialized_run_id),lastRunAt:g($.last_run_at),nextRunAt:g($.next_run_at),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function UW($){return{runId:s($.run_id),specId:s($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:s($.trigger_kind),status:s($.status),claimToken:g($.claim_token),claimStartedAt:g($.claim_started_at),claimUntilAt:g($.claim_until_at),scheduledFor:g($.scheduled_for),triggerEventId:g($.trigger_event_id),startedAt:g($.started_at),completedAt:g($.completed_at),sessionId:g($.session_id),reportPath:g($.report_path),error:g($.error),attemptCount:Number($.attempt_count??0),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function QB($){return{eventId:s($.event_id),eventType:s($.event_type),source:s($.source),subject:g($.subject),occurredAt:s($.occurred_at),receivedAt:s($.received_at),workspaceRoot:g($.workspace_root),dedupeKey:g($.dedupe_key),payload:x9(g($.payload_json)),attributes:x9(g($.attributes_json)),processingStatus:s($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:g($.error),createdAt:s($.created_at),updatedAt:s($.updated_at)}}function ZB($){return $?JSON.stringify($):null}var kM=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function WB($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function IM($,J,Q,Z){for(let W of kM){let j=$[W],f=J[W];if(WB(j)!==WB(f))return!0}if(Q===!1&&Z===!0)return!0;return!1}function xM($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function gM($){return`hub/schedules/${$}.cron.md`}function mM($){let J={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(J).length>0?J:void 0}function RW($){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((J)=>J.trim().length>0),enabled:$.enabled!==!1,metadata:mM($)}}function jB($){return JSON.stringify(RW($))}function vM($,J){let Q=$.metadata?{...$.metadata}:{},Z=J.createdBy===null?void 0:J.createdBy!==void 0?J.createdBy:typeof Q.__hubScheduleCreatedBy==="string"?Q.__hubScheduleCreatedBy:void 0,W=J.cwd!==void 0?J.cwd:typeof Q.__hubScheduleCwd==="string"?Q.__hubScheduleCwd:void 0,j=J.runtimeOptions!==void 0?J.runtimeOptions:Q.__hubRuntimeOptions&&typeof Q.__hubRuntimeOptions==="object"&&!Array.isArray(Q.__hubRuntimeOptions)?Q.__hubRuntimeOptions:void 0;return delete Q.__hubScheduleCreatedBy,delete Q.__hubScheduleCwd,delete Q.__hubRuntimeOptions,{name:J.name??$.title,cronPattern:J.cronPattern??$.scheduleExpr??"",prompt:J.prompt??$.prompt??"",workspaceRoot:J.workspaceRoot??$.workspaceRoot??"",cwd:W,modelSelection:J.modelSelection!==void 0?J.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:J.enabled??$.enabled,mode:J.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:J.systemPrompt===null?void 0:J.systemPrompt!==void 0?J.systemPrompt:$.systemPrompt,maxIterations:J.maxIterations===null?void 0:J.maxIterations!==void 0?J.maxIterations:$.maxIterations,timeoutSeconds:J.timeoutSeconds===null?void 0:J.timeoutSeconds!==void 0?J.timeoutSeconds:$.timeoutSeconds,maxParallel:J.maxParallel??$.maxParallel??1,createdBy:Z,tags:J.tags??$.tags,runtimeOptions:j,metadata:J.metadata!==void 0?J.metadata:Object.keys(Q).length>0?Q:void 0}}class a6{db;constructor($={}){let J=$.dbPath??hM();this.db=bM(J),JB(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return J?M$(J):void 0}getSpec($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return J?M$(J):void 0}getSpecByExternalId($){let J=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return J?M$(J):void 0}listSpecs($={}){let J=[],Q=[];if($.triggerKind)J.push("trigger_kind = ?"),Q.push($.triggerKind);if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.parseStatus)J.push("parse_status = ?"),Q.push($.parseStatus);if(!$.includeRemoved)J.push("removed = 0");let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Z} ORDER BY created_at DESC LIMIT ?`).all(...Q,W).map((f)=>M$(f))}createHubSchedule($){let J=`sched_${n6()}`,Q=this.upsertSpec({externalId:J,sourcePath:gM(J),triggerKind:"schedule",sourceHash:jB($),parseStatus:"valid",spec:RW($)});this.initializeScheduleNextRun(Q.record.specId);let Z=this.getSpec(Q.record.specId);if(!Z)throw Error("failed to create hub schedule");return Z}getHubSchedule($){let J=this.db.prepare(`SELECT * FROM cron_specs
342
342
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
343
343
  ORDER BY created_at ASC LIMIT 1`).get($);return J?M$(J):void 0}listHubSchedules($={}){let J=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],Q=[];if(typeof $.enabled==="boolean")J.push("enabled = ?"),Q.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let j of $.tags)J.push("tags_json LIKE ?"),Q.push(`%"${j.trim()}"%`);let Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
344
344
  WHERE ${J.join(" AND ")}
345
- ORDER BY created_at DESC LIMIT ?`).all(...Q,Z).map((j)=>M$(j))}updateHubSchedule($,J){let Q=this.getHubSchedule($);if(!Q)return;let Z=vM(Q,J),W=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:fB(Z),parseStatus:"valid",spec:RW(Z)});if(J.cronPattern!==void 0||J.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule($){let J=this.getHubSchedule($);if(!J)return!1;return this.markSpecRemoved(J.specId),this.cancelQueuedRunsForSpec(J.specId),!0}enqueueHubScheduleRun($,J="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:J,scheduledFor:_0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
345
+ ORDER BY created_at DESC LIMIT ?`).all(...Q,Z).map((j)=>M$(j))}updateHubSchedule($,J){let Q=this.getHubSchedule($);if(!Q)return;let Z=vM(Q,J),W=this.upsertSpec({externalId:$,sourcePath:Q.sourcePath,triggerKind:"schedule",sourceHash:jB(Z),parseStatus:"valid",spec:RW(Z)});if(J.cronPattern!==void 0||J.enabled!==void 0)this.initializeScheduleNextRun(W.record.specId);return this.getSpec(W.record.specId)}deleteHubSchedule($){let J=this.getHubSchedule($);if(!J)return!1;return this.markSpecRemoved(J.specId),this.cancelQueuedRunsForSpec(J.specId),!0}enqueueHubScheduleRun($,J="manual"){let Q=this.getHubSchedule($);if(!Q||!Q.enabled||Q.removed||Q.parseStatus!=="valid")return;return this.enqueueRun({specId:Q.specId,specRevision:Q.revision,triggerKind:J,scheduledFor:_0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
346
346
  WHERE trigger_kind = 'event'
347
347
  AND event_type = ?
348
348
  AND enabled = 1
@@ -386,9 +386,9 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
386
386
  payload_json, attributes_json, processing_status,
387
387
  matched_spec_count, queued_run_count, suppressed_count,
388
388
  error, created_at, updated_at
389
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,j,f,$.subject?.trim()||null,X,Z,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,WB($.payload),WB($.attributes),"received",0,0,0,null,Q,Q).changes??0,V=this.getEventLog(W);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let J=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return J?ZB(J):void 0}listEventLogs($={}){let J=[],Q=[];if($.eventType)J.push("event_type = ?"),Q.push($.eventType);if($.source)J.push("source = ?"),Q.push($.source);if($.processingStatus)J.push("processing_status = ?"),Q.push($.processingStatus);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Z}
389
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(W,j,f,$.subject?.trim()||null,X,Z,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,ZB($.payload),ZB($.attributes),"received",0,0,0,null,Q,Q).changes??0,V=this.getEventLog(W);if(!V)throw Error("failed to insert cron_event_log row");return{record:V,created:Y===1}}getEventLog($){let J=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return J?QB(J):void 0}listEventLogs($={}){let J=[],Q=[];if($.eventType)J.push("event_type = ?"),Q.push($.eventType);if($.source)J.push("source = ?"),Q.push($.source);if($.processingStatus)J.push("processing_status = ?"),Q.push($.processingStatus);let Z=J.length>0?`WHERE ${J.join(" AND ")}`:"",W=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Z}
390
390
  ORDER BY received_at DESC, created_at DESC
391
- LIMIT ?`).all(...Q,W).map((f)=>ZB(f))}updateEventLogProcessing($,J){return(this.db.prepare(`UPDATE cron_event_log SET
391
+ LIMIT ?`).all(...Q,W).map((f)=>QB(f))}updateEventLogProcessing($,J){return(this.db.prepare(`UPDATE cron_event_log SET
392
392
  processing_status = ?,
393
393
  matched_spec_count = COALESCE(?, matched_spec_count),
394
394
  queued_run_count = COALESCE(?, queued_run_count),
@@ -483,40 +483,40 @@ ${JSON.stringify(Z,null,2)}`}startClaimLeaseHeartbeat($){let J=Math.max(1000,Mat
483
483
  error = ?,
484
484
  scheduled_for = COALESCE(?, scheduled_for),
485
485
  updated_at = ?
486
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,_0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,_0(),$)}}class s6{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a6({dbPath:$.dbPath});let J=$.specs;this.reconciler=new GW({store:this.store,specs:J}),this.materializer=new l6({store:this.store}),this.eventIngress=new ZW({store:this.store,logger:$.logger}),this.runner=new p6({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new FW({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var FB={};w(FB,{manifestToSessionRecord:()=>mQ,listSessionHistoryFromBackend:()=>OW,listSessionHistory:()=>vQ,hydrateSessionHistory:()=>GB});import{readdir as lM,readFile as BB}from"node:fs/promises";import{join as AB}from"node:path";import{formatDisplayUserInput as pM,normalizeUserInput as rM}from"@cline/shared";import{resolveSessionDataDir as KB}from"@cline/shared/storage";import{existsSync as cM}from"node:fs";import{readFile as uM}from"node:fs/promises";import{formatDisplayUserInput as XB}from"@cline/shared";class o6{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function q$($){let J=$?.trim();if(!J||!cM(J))return[];try{let Q=(await uM(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return YB(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return YB(W)}return[]}catch{return[]}}function dM($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:XB($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:XB(J.text)}})}}function YB($){return $.map(dM)}function zW($){return $?{...$}:void 0}async function VB($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function t6($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function r0($){let J=t6($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function gQ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function iM($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function _W($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function nM($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function aM($){return $.isSubagent!==!0&&!t6($.parentSessionId)}function sM($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function mQ($){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 oM($){let J=_W($);if(J===0)return[];let Q=KB(),W=(await lM(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:sM(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=AB(Q,X,`${X}.json`),V=await BB(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let B=S0.safeParse(H);if(!B.success)return;return mQ(B.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function tM($,J,Q){let Z=_W(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:nM(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(aM)).slice(0,Z)}function eM($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
487
- `).trim()}function HB($){return $.replace(/\s+/g," ").trim()}function $q($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function Jq($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=HB(eM(Q.content));if(!Z)continue;let W=J==="user"?HB(pM(Z)):Z,j=rM(W.split(`
488
- `)[0]??W);return $q(j,50)}return}function Qq($){let J=0;for(let Q of $)J+=gQ(Q.metrics?.cost)??0;return J}function Zq($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=r0(W.modelInfo?.provider);if(!Q)Q=r0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function Wq($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function jq($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function LW($,J){let Q=iM($.metadata),Z=t6(J?.title)??t6(Q?.title),W=gQ(J?.totalCost)??gQ(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:r0(J?.provider)??r0($.provider)??Wq(Q)??"",model:r0(J?.model)??r0($.model)??jq(Q)??"",metadata:j}}function fq($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function Xq($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!fq(Q)}async function Yq($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return Xq(Q,Z)?{...Q,status:"idle"}:Q}))}async function GB($,J){return await Promise.all(J.map(async(Q)=>{let Z=LW(Q),W=Boolean(t6(Z.metadata?.title)),j=Boolean(r0(Z.provider)),f=Boolean(r0(Z.model)),X=gQ(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=Zq(V),B=Qq(V);return LW(Q,{title:W?void 0:Jq(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||B<=0?void 0:B})}))}async function vQ($,J={}){let Q=_W(J.limit),Z=J.includeSubagents===!0,W=await tM($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await oM(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await Yq($,X);if(J.hydrate===!1)return Y.map((V)=>LW(V));return await GB($,Y)}async function Vq($){let J=$.trim();if(!J)return;let Q=AB(KB(),J,`${J}.json`),Z=await BB(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=S0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function OW($,J={}){let Q=new Map;return await vQ({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map($6)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await Vq(W);return await q$(j)}},J)}var wA={};w(wA,{resolveSessionBackend:()=>W3,createRuntimeHost:()=>p8});import{captureSdkError as PA}from"@cline/shared";import{createSessionId as ZP,isHubProtocolCompatible as WP,resolveClineBuildEnv as jP,resolveHubCommandTimeoutMs as fP}from"@cline/shared";import{spawn as hq}from"node:child_process";import{closeSync as kq,mkdirSync as Iq,openSync as xq}from"node:fs";import{basename as gq,dirname as mq,join as vq}from"node:path";import{fileURLToPath as cq}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as uq,isHubDaemonProcess as SB,isHubProtocolCompatible as dq,resolveClineBuildEnv as CB,withResolvedClineBuildEnv as lq}from"@cline/shared";import{createHash as Hq,randomBytes as Bq}from"node:crypto";import{existsSync as Aq}from"node:fs";import{chmod as Kq,mkdir as TW,readFile as LB,rm as MW,writeFile as _B}from"node:fs/promises";import{dirname as OB,join as qW}from"node:path";import{resolveClineDataDir as R2,resolveClineDir as TB}from"@cline/shared/storage";var UB="0.0.48-nightly.1781666345";var e6={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:UB,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Gq="CLINE_HUB_DISCOVERY_PATH",Fq="CLINE_HUB_BUILD_ID",RB=30000,Dq=15000,Uq=100;function Rq($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function zq($){return Hq("sha256").update($).digest("hex").slice(0,12)}function Lq($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function cQ(){return Bq(32).toString("hex")}function _q($){return new Promise((J)=>setTimeout(J,$))}function Oq($){return`${$}.lock`}async function Tq($){try{let J=JSON.parse(await LB(qW($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function zB($){await MW($,{recursive:!0,force:!0}).catch(()=>{return})}function uQ(){return process.env[Fq]?.trim()||String(e6.version)}function l1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${zq($)}`,Q=process.env[Gq]?.trim()||qW(R2(),"locks","hub","owners",`${Rq(J)}.json`);return{ownerId:J,discoveryPath:Q}}function MB($=`hub-${Date.now().toString(36)}`){return l1($)}async function A0($){try{let J=JSON.parse(await LB($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function dQ($,J){await TW(OB($),{recursive:!0}),await MW($,{force:!0}).catch(()=>{return}),await _B($,`${JSON.stringify(J,null,2)}
489
- `,{encoding:"utf8",mode:384}),await Kq($,384)}async function y0($){await MW($,{force:!0}).catch(()=>{return})}async function lQ($,J){let Q=Oq($);await TW(OB(Q),{recursive:!0});let Z=Date.now()+Dq;while(!0)try{await TW(Q,{recursive:!1}),await _B(qW(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
490
- `,"utf8");try{return await J()}finally{await zB(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await Tq(Q),X=f?Date.now()-Date.parse(f.acquiredAt):RB+1;if(!f||!Lq(f.pid)||X>RB){await zB(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await _q(Uq)}}async function p1($,J){try{let Q=await fetch(J?.authToken?PW($):pQ($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function j1($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function pQ($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function PW($){let J=new URL(pQ($));return J.pathname="/status",J.toString()}function qB($){return Aq($)}import{CLINE_HUB_DEV_PORT as Mq,CLINE_HUB_PORT as qq,resolveClineBuildEnv as Pq}from"@cline/shared";var Nq="CLINE_HUB_HOST",wq="CLINE_HUB_PORT",Sq="CLINE_HUB_PATHNAME",NW="127.0.0.1",wW=qq,SW="/hub";function PB($){return Pq($)==="development"?Mq:wW}function CW($={}){return($.env??process.env)[Nq]?.trim()||NW}function b8($={}){let Q=($.env??process.env)[wq]?.trim();if(!Q)return PB($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return PB($);return Z}function yW($={}){return($.env??process.env)[Sq]?.trim()||SW}function i0($={},J={}){return{host:$.host??CW(J),port:$.port??b8(J),pathname:$.pathname??yW(J)}}import{join as Cq}from"node:path";var yq="shared:cline",Eq="CLINE_HUB_DISCOVERY_PATH",bq="hub-production";function NB($){let J=m1($.trim());return l1(`workspace:${J||$.trim()}`)}function E0($=yq){return l1($)}function n0(){return{ownerId:bq,discoveryPath:process.env[Eq]?.trim()||Cq(R2(),"locks","hub","production.json")}}var pq=8000,rq=200,iq=3000,nq=100,aq=[100,250,500,1000,2000],sq="--cline-hub-daemon";function oq($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function tq(){try{let $=vq(R2(),"logs","hub-daemon.log");return Iq(mq($),{recursive:!0}),{fd:xq($,"a"),logPath:$}}catch{return}}function yB(){return CB()==="production"?n0():E0()}function z2($){return dq($).compatible}function wB($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function L2($,J){try{return await p1($,{authToken:J})}catch{return}}async function eq($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await L2($))?.url)return!0;await new Promise((W)=>setTimeout(W,nq))}return!1}async function rQ($,J){if(await JJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await eq($.url,iq);return await y0(J).catch(()=>{return}),Q}async function $J($,J){if(z2($))return!0;return rQ($,J)}async function EB($){if(CB()!=="production")return;let J=E0();if(J.discoveryPath===$.discoveryPath)return;let Q=await A0(J.discoveryPath);if(Q?.url)await rQ(Q,J.discoveryPath);else await y0(J.discoveryPath).catch(()=>{return})}function $P(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return cq(new URL(`./entry.${$}`,import.meta.url))}function JP($,J){let Q=$P(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=gq(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[sq]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...oq(J)],cwd:$,env:{...lq(process.env),CLINE_NO_INTERACTIVE:"1",[uq]:"1"}}}function QP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function EW($,J={}){if(SB())return;let Q=JP($,J),Z=tq();try{hq(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)kq(Z.fd)}}async function h8($,J={}){for(let Q=0;;Q++)try{EW($,J);return}catch(Z){let W=aq[Q];if(!QP(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function iQ($,J={}){if(SB())return;let Q=yB(),Z=i0(J),W=j1(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;EB(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await rQ(f,Q.discoveryPath)&&!j)return}else{let H=await L2(f.url,f.authToken);if(H?.url&&z2(H)&&await G1(H.url,{authToken:f.authToken}))return;if(H?.url)await $J({...H,authToken:f.authToken},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}let Y=await L2(W);if(Y?.url){if(z2(Y)){if(!j||!X)return}else if(!await $J({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await h8($,V)}).catch(()=>{})}async function bB($,J={}){let Q=yB(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=i0(J),j=j1(W.host,W.port,W.pathname),f=(K)=>{if(!Z)P$(K.url,K.authToken);return K};await EB(Q).catch(()=>{return});let X=await A0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await rQ(X,Q.discoveryPath);else{let G=await L2(X.url,K);if(G?.url&&z2(G)&&await G1(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await $J({...G,authToken:K},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}}let V=await L2(j);if(V?.url){let K=wB(V,X,j);if(z2(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await $J(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await h8($,B);let A=Date.now()+pq;while(Date.now()<A){let K=await A0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await L2(K.url,K.authToken);if(R?.url&&z2(R)&&await G1(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await L2(j);if(G?.url&&!z2(G)){let R=wB(G,K,j);if(!await $J(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,rq))}throw Error("Timed out waiting for detached hub startup.")}function nQ(){return jP()==="production"?n0():E0()}function XP(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function gB($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return gB($.data);return String($)}function YP($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function hB($){let J=$,Q=YP(J.reason);return new q0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:bW,{closeCode:J.code,closeReason:Q||void 0})}function VP($,J){if($ instanceof q0)return $;if($ instanceof Error)return new q0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new q0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new q0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new q0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var HP=8000,BP=200,kB="*",IB=8000,AP="cline-hub-auth.",mB=new Map,vB=new Set,KP=3000,GP=3000,FP=100,bW="Hub connection closed",DP=250,UP=5000,xB=0.5;class q0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function IW($){return $ instanceof q0}class k8 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function aQ($,J){return $ instanceof k8&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function cB($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=xW($.toString());return Q?mB.get(Q):void 0}function RP($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function xW($){if(!RP($))return;let J=new URL(N$($));return J.search="",J.hash="",J.toString()}function hW($){let J=xW($);return!!J&&vB.has(J)}function P$($,J){let Q=xW($);if(Q){if(vB.add(Q),J?.trim())mB.set(Q,J)}return $}class f1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new q0("hub_connection_closed",bW);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||cB($);$.hash="";let Z=new(XP())($.toString(),J?[`${AP}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new q0("hub_connect_timeout",`Timed out connecting to hub after ${IB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},IB);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=VP(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=hB(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(gB(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=hB(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=ZP("hubreq_"),j=fP($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new k8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(W,{resolve:(B)=>{if(H)clearTimeout(H);Y(B)},reject:(B)=>{if(H)clearTimeout(H);V(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===G2){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new u1(Y,X.error.message)}throw new k8($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!hW(this.currentUrl)||!IW($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(DP*2**this.reconnectAttempt,UP),J=Math.round($*(1-xB)+Math.random()*$*xB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!hW(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new q0("hub_connection_closed",bW),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??kB}subscriptionSessionIdFromKey($){return $===kB?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function N$($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function G1($,J){let Q=new f1({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function kW($,J){let Q=N$($),Z=await p1(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!WP(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await G1(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function zP($){let J=Date.now()+HP;while(Date.now()<J){let Q=await A0($.discoveryPath);if(Q?.url){let Z=await kW(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return P$(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,BP))}return}async function LP($){let J=Date.now()+GP;while(Date.now()<J){if(!(await p1($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,FP))}return!1}function _P($,J){try{return N$($)===N$(J)}catch{return!1}}function OP($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function TP($,J,Q){let Z=new f1({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:KP});return!OP(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function QJ($={}){if($.endpoint?.trim()){let W=await kW($.endpoint);return W.status==="compatible"?W.url:void 0}let J=nQ(),Q=await A0(J.discoveryPath);if(!Q?.url)return;let Z=await kW(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return P$(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await y0(J.discoveryPath).catch(()=>{return});return}async function _2($={}){let J=await QJ($);if(J&&await G1(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=nQ();return await h8($.workspaceRoot??process.cwd()),await zP(Q)}async function JJ($,J){let Q=new URL($),Z=J?.trim()||cB(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function gW($=nQ()){let J=await A0($.discoveryPath);if(!J?.url)return!1;try{if(await JJ(J.url,J.authToken))return!0}catch{}return!1}async function sQ($){if(!hW($.url))return;let J=nQ(),Q=await A0(J.discoveryPath);if(!Q?.url||!_P(Q.url,$.url))return;if(!await TP(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await gW())return;if(!await LP(Q.url))return;return await y0(J.discoveryPath).catch(()=>{return}),await _2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var $A={};w($A,{HubRuntimeHost:()=>r1});import{captureSdkError as dB,createSessionId as lB,HUB_CHECKPOINT_CAPABILITY as NP,HUB_COMPACTION_CAPABILITY as wP,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as SP,HUB_HOOK_CAPABILITY_PREFIX as CP,HUB_MISTAKE_LIMIT_CAPABILITY as yP,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as EP,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as bP,isHubToolExecutorName as hP}from"@cline/shared";var uB={};w(uB,{createCoreSessionSnapshot:()=>F1,coreSessionSnapshotToRecord:()=>oQ});function MP($){return $?JSON.parse(JSON.stringify($)):void 0}function qP($){return $?JSON.parse(JSON.stringify($)):void 0}function PP($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function F1($){let{session:J}=$,Q=MP(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:qP($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=PP(Q);return Z?{checkpoint:Z}:{}})()}}function oQ($){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 I8($){if(!$)return;return JSON.parse(JSON.stringify($))}var kP=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function pB($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function rB($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function iB($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function O2($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function nB($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(hP)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;O2(Q,{kind:"toolExecutor",executor:W,capabilityName:`${EP}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...iB(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])O2(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:I8(W.inputSchema)??{},...W.lifecycle?{lifecycle:I8(W.lifecycle)}:{},capabilityName:`${SP}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...iB(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of kP){let j=Z[W];if(typeof j!=="function")continue;O2(Q,{kind:"hook",name:W,capabilityName:`${CP}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;O2(Q,{kind:"compaction",capabilityName:wP,config:pB($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;O2(Q,{kind:"checkpoint",capabilityName:NP,config:pB($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;O2(Q,{kind:"mistakeLimit",capabilityName:yP},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;O2(Q,{kind:"userInstructionService",capabilityName:bP},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function tB($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function IP($){return tB($)??"Capability request was cancelled."}function xP($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function gP($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function mP($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function aB($){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 mW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function w$($,J){return mW($?.[J])??0}function vP($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:w$(J,"inputTokens"),outputTokens:w$(J,"outputTokens"),cacheReadTokens:w$(J,"cacheReadTokens"),cacheWriteTokens:w$(J,"cacheWriteTokens"),cost:mW(J?.totalCost),totalInputTokens:w$(Q,"inputTokens"),totalOutputTokens:w$(Q,"outputTokens"),totalCacheReadTokens:w$(Q,"cacheReadTokens"),totalCacheWriteTokens:w$(Q,"cacheWriteTokens"),totalCost:mW(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function cP($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=gP(Q)?Q:Q==="failed"?"error":"completed",W=mP($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function tQ($,J){return $.error?.message??`hub command failed: ${J}`}function ZJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function eB($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:U0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:ZJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:ZJ($.status)==="completed"?0:ZJ($.status)==="failed"?1:void 0,status:ZJ($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function S$($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function uP($){let J=S$($?.snapshot);if(J)return oQ(J);let Q=$?.session;return Q?eB(Q):void 0}function sB($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return S0.parse({version:1,session_id:$,source:J.source??U0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:ZJ(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function oB($,J){return S0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class r1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new o6;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new f1({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!aQ($,"session.create"))return!1;let J=await sQ({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=nB($.localRuntime,J),Z=$.config.sessionId?.trim()||lB(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:I8({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??U0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:I8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=S$(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?oB(f,$):sB(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?nB(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||lB():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:I8({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??U0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:I8(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=S$(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let B=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?oB(Y,Z??{}):sB(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=S$(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=aB(Z?.usage),j=aB(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:tB(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(d1(Q))return;throw Q}return uP(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=S$(W);return j?[oQ(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(eB)}async listSettings($){let J=await this.client.command("settings.list",rB($));if(!J.ok)throw Error(tQ(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",rB($));if(!J.ok)throw Error(tQ(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw dB(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(tQ(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(tQ(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:cP($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=vP($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=S$($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&j0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{dB(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(IP($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=xP($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}var JA={};w(JA,{RemoteRuntimeHost:()=>x8});class x8 extends r1{constructor($){super({url:N$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var QA={};w(QA,{SqliteSessionStore:()=>U1});import{existsSync as dP,mkdirSync as lP}from"node:fs";import{join as pP}from"node:path";import{asBool as WJ,asOptionalString as D1,asString as i1,ensureSessionSchema as rP,loadSqliteDb as iP,nowIso as eQ,toBoolInt as jJ}from"@cline/shared/db";import{resolveDbDataDir as nP}from"@cline/shared/storage";class U1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??nP()}init(){this.getRawDb()}ensureSessionsDir(){if(!dP(this.sessionsDirPath))lP(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return pP(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=iP(this.sessionDbPath());return rP($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=eQ();this.run(`INSERT OR REPLACE INTO sessions (
486
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,J,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,J){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(J,_0(),$)}attachReportPathToRun($,J){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(J,_0(),$)}}class s6{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a6({dbPath:$.dbPath});let J=$.specs;this.reconciler=new GW({store:this.store,specs:J}),this.materializer=new l6({store:this.store}),this.eventIngress=new ZW({store:this.store,logger:$.logger}),this.runner=new p6({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:J,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new FW({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(Q)=>{let Z=$.logger;if(Z)if(Z.error)Z.error("cron.watcher.failed",{error:Q});else Z.log("cron.watcher.failed",{error:Q})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}var GB={};w(GB,{manifestToSessionRecord:()=>m9,listSessionHistoryFromBackend:()=>OW,listSessionHistory:()=>v9,hydrateSessionHistory:()=>KB});import{readdir as lM,readFile as HB}from"node:fs/promises";import{join as BB}from"node:path";import{formatDisplayUserInput as pM,normalizeUserInput as rM}from"@cline/shared";import{resolveSessionDataDir as AB}from"@cline/shared/storage";import{existsSync as cM}from"node:fs";import{readFile as uM}from"node:fs/promises";import{formatDisplayUserInput as fB}from"@cline/shared";class o6{listeners=new Set;subscribe($,J){let Q={listener:$,sessionId:J?.sessionId?.trim()||void 0};return this.listeners.add(Q),()=>{this.listeners.delete(Q)}}emit($){let J=$.payload.sessionId?.trim();for(let Q of this.listeners){if(Q.sessionId&&Q.sessionId!==J)continue;Q.listener($)}}get size(){return this.listeners.size}}async function q$($){let J=$?.trim();if(!J||!cM(J))return[];try{let Q=(await uM(J,"utf8")).trim();if(!Q)return[];let Z=JSON.parse(Q);if(Array.isArray(Z))return XB(Z);if(Z&&typeof Z==="object"&&!Array.isArray(Z)){let W=Z.messages;if(Array.isArray(W))return XB(W)}return[]}catch{return[]}}function dM($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:fB($.content)};return{...$,content:$.content.map((J)=>{if(J.type!=="text"||typeof J.text!=="string")return J;return{...J,text:fB(J.text)}})}}function XB($){return $.map(dM)}function zW($){return $?{...$}:void 0}async function YB($,J){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await J.queueSpawnRequest($);let Z=await J.upsertSubagentSessionFromHook($);if(!Z)return;await J.appendSubagentHookAudit(Z,$),await J.applySubagentStatus(Z,$)}function t6($){if(typeof $!=="string")return;let J=$.trim();return J.length>0?J:void 0}function r0($){let J=t6($);if(!J)return;return J.toLowerCase()==="unknown"?void 0:J}function g9($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function iM($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function _W($){let J=$??200;return Number.isFinite(J)?Math.max(0,Math.floor(J)):200}function nM($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function aM($){return $.isSubagent!==!0&&!t6($.parentSessionId)}function sM($){let J=$.match(/\d{13,}/g);if(!J||J.length===0)return 0;let Q=0;for(let Z of J){let W=Number.parseInt(Z,10);if(Number.isFinite(W)&&W>Q)Q=W}return Q}function m9($){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 oM($){let J=_W($);if(J===0)return[];let Q=AB(),W=(await lM(Q,{withFileTypes:!0}).catch(()=>[])).filter((f)=>f.isDirectory()).map((f)=>({entry:f,recency:sM(f.name.trim())})).sort((f,X)=>X.recency-f.recency||X.entry.name.localeCompare(f.entry.name));return(await Promise.all(W.map(async({entry:f})=>{let X=f.name.trim();if(!X)return;let Y=BB(Q,X,`${X}.json`),V=await HB(Y,"utf8").catch(()=>{return});if(!V)return;let H;try{H=JSON.parse(V)}catch{return}let B=S0.safeParse(H);if(!B.success)return;return m9(B.data)}))).filter((f)=>Boolean(f)).sort((f,X)=>X.startedAt.localeCompare(f.startedAt)).slice(0,J)}async function tM($,J,Q){let Z=_W(J);if(Z===0)return await $.listSessions(0),[];let W=Q.includeSubagents?Z:nM(Z),j=await $.listSessions(W);return(Q.includeSubagents?j:j.filter(aM)).slice(0,Z)}function eM($){if(typeof $==="string")return $.trim();let J=[];for(let Q of $){if(!Q||typeof Q!=="object")continue;let Z=Q;if(Z.type!=="text")continue;let W=Z.text?.trim();if(W)J.push(W)}return J.join(`
487
+ `).trim()}function VB($){return $.replace(/\s+/g," ").trim()}function $q($,J){if($.length<=J)return $;return`${$.slice(0,Math.max(0,J-3)).trimEnd()}...`}function Jq($){for(let J of["user","assistant"])for(let Q of $){if(Q.role!==J)continue;let Z=VB(eM(Q.content));if(!Z)continue;let W=J==="user"?VB(pM(Z)):Z,j=rM(W.split(`
488
+ `)[0]??W);return $q(j,50)}return}function Qq($){let J=0;for(let Q of $)J+=g9(Q.metrics?.cost)??0;return J}function Zq($){let J,Q;for(let Z=$.length-1;Z>=0;Z-=1){let W=$[Z];if(!J)J=r0(W.modelInfo?.provider);if(!Q)Q=r0(W.modelInfo?.id);if(J&&Q)break}return{provider:J,model:Q}}function Wq($){return r0($?.provider)??r0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function jq($){return r0($?.model)??r0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function LW($,J){let Q=iM($.metadata),Z=t6(J?.title)??t6(Q?.title),W=g9(J?.totalCost)??g9(Q?.totalCost),j=Q||Z!==void 0||W!==void 0?{...Q??{},...Z!==void 0?{title:Z}:{},...W!==void 0?{totalCost:W}:{}}:void 0;return{...$,provider:r0(J?.provider)??r0($.provider)??Wq(Q)??"",model:r0(J?.model)??r0($.model)??jq(Q)??"",metadata:j}}function fq($){let J=$.content;if(!Array.isArray(J))return!1;return J.some((Q)=>!!Q&&typeof Q==="object"&&Q.type==="tool-call")}function Xq($,J){if($.status!=="running"||$.interactive!==!0)return!1;let Q=J.at(-1);return Q?.role==="assistant"&&!fq(Q)}async function Yq($,J){return await Promise.all(J.map(async(Q)=>{if(Q.status!=="running"||Q.interactive!==!0)return Q;let Z=await $.readSessionMessages(Q.sessionId);return Xq(Q,Z)?{...Q,status:"idle"}:Q}))}async function KB($,J){return await Promise.all(J.map(async(Q)=>{let Z=LW(Q),W=Boolean(t6(Z.metadata?.title)),j=Boolean(r0(Z.provider)),f=Boolean(r0(Z.model)),X=g9(Z.metadata?.totalCost),Y=X!==void 0&&X>0;if(W&&j&&f&&Y)return Z;let V=await $.readSessionMessages(Q.sessionId);if(V.length===0)return Z;let H=Zq(V),B=Qq(V);return LW(Q,{title:W?void 0:Jq(V),provider:j?void 0:H.provider,model:f?void 0:H.model,totalCost:Y||B<=0?void 0:B})}))}async function v9($,J={}){let Q=_W(J.limit),Z=J.includeSubagents===!0,W=await tM($,Q,{includeSubagents:Z}),j=J.includeManifestFallback===!0&&W.length<Q?await oM(Math.min(Math.max(Q*2,100),500)):[],f=new Map;for(let V of[...W,...j]){if(f.has(V.sessionId))continue;f.set(V.sessionId,V)}let X=j.length===0?W:Array.from(f.values()).sort((V,H)=>H.startedAt.localeCompare(V.startedAt)).slice(0,Q),Y=await Yq($,X);if(J.hydrate===!1)return Y.map((V)=>LW(V));return await KB($,Y)}async function Vq($){let J=$.trim();if(!J)return;let Q=BB(AB(),J,`${J}.json`),Z=await HB(Q,"utf8").catch(()=>{return});if(!Z)return;try{let W=S0.safeParse(JSON.parse(Z));return W.success?W.data.messages_path:void 0}catch{return}}async function OW($,J={}){let Q=new Map;return await v9({listSessions:async(W)=>{let j=await $.listSessions(W);Q.clear();for(let f of j)Q.set(f.sessionId,f);return j.map($6)},readSessionMessages:async(W)=>{let j=Q.get(W)?.messagesPath??await Vq(W);return await q$(j)}},J)}var NA={};w(NA,{resolveSessionBackend:()=>W3,createRuntimeHost:()=>p8});import{captureSdkError as qA}from"@cline/shared";import{createSessionId as ZP,isHubProtocolCompatible as WP,resolveClineBuildEnv as jP,resolveHubCommandTimeoutMs as fP}from"@cline/shared";import{spawn as hq}from"node:child_process";import{closeSync as kq,mkdirSync as Iq,openSync as xq}from"node:fs";import{basename as gq,dirname as mq,join as vq}from"node:path";import{fileURLToPath as cq}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as uq,isHubDaemonProcess as wB,isHubProtocolCompatible as dq,resolveClineBuildEnv as SB,withResolvedClineBuildEnv as lq}from"@cline/shared";import{createHash as Hq,randomBytes as Bq}from"node:crypto";import{existsSync as Aq}from"node:fs";import{chmod as Kq,mkdir as TW,readFile as zB,rm as MW,writeFile as LB}from"node:fs/promises";import{dirname as _B,join as qW}from"node:path";import{resolveClineDataDir as R2,resolveClineDir as OB}from"@cline/shared/storage";var DB="0.0.49";var e6={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:DB,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"},"./services/feature-flags/posthog":{types:"./dist/services/feature-flags/posthog.d.ts",import:"./dist/services/feature-flags/posthog.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},peerDependencies:{"posthog-node":"^5.8.0"},peerDependenciesMeta:{"posthog-node":{optional:!0}},devDependencies:{"@types/ws":"^8.18.1","posthog-node":"^5.8.0"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var Gq="CLINE_HUB_DISCOVERY_PATH",Fq="CLINE_HUB_BUILD_ID",UB=30000,Dq=15000,Uq=100;function Rq($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function zq($){return Hq("sha256").update($).digest("hex").slice(0,12)}function Lq($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(J){return J instanceof Error&&"code"in J?String(J.code)==="EPERM":!1}}function c9(){return Bq(32).toString("hex")}function _q($){return new Promise((J)=>setTimeout(J,$))}function Oq($){return`${$}.lock`}async function Tq($){try{let J=JSON.parse(await zB(qW($,"owner.json"),"utf8"));if(typeof J.pid!=="number"||typeof J.acquiredAt!=="string")return;return{pid:J.pid,acquiredAt:J.acquiredAt}}catch{return}}async function RB($){await MW($,{recursive:!0,force:!0}).catch(()=>{return})}function u9(){return process.env[Fq]?.trim()||String(e6.version)}function l1($=process.argv[1]?.trim()||process.cwd()){let J=`hub-${zq($)}`,Q=process.env[Gq]?.trim()||qW(R2(),"locks","hub","owners",`${Rq(J)}.json`);return{ownerId:J,discoveryPath:Q}}function TB($=`hub-${Date.now().toString(36)}`){return l1($)}async function A0($){try{let J=JSON.parse(await zB($,"utf8"));if(typeof J.hubId!=="string"||typeof J.protocolVersion!=="string"||typeof J.authToken!=="string"||typeof J.host!=="string"||typeof J.port!=="number"||typeof J.url!=="string"||typeof J.startedAt!=="string"||typeof J.updatedAt!=="string")return;return{hubId:J.hubId,protocolVersion:J.protocolVersion,minClientProtocolVersion:typeof J.minClientProtocolVersion==="string"?J.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof J.maxClientProtocolVersion==="string"?J.maxClientProtocolVersion:void 0,capabilities:Array.isArray(J.capabilities)?J.capabilities.filter((Q)=>typeof Q==="string"):void 0,coreVersion:typeof J.coreVersion==="string"?J.coreVersion:void 0,buildId:typeof J.buildId==="string"?J.buildId:void 0,authToken:J.authToken,host:J.host,port:J.port,url:J.url,pid:typeof J.pid==="number"?J.pid:void 0,startedAt:J.startedAt,updatedAt:J.updatedAt}}catch{return}}async function d9($,J){await TW(_B($),{recursive:!0}),await MW($,{force:!0}).catch(()=>{return}),await LB($,`${JSON.stringify(J,null,2)}
489
+ `,{encoding:"utf8",mode:384}),await Kq($,384)}async function y0($){await MW($,{force:!0}).catch(()=>{return})}async function l9($,J){let Q=Oq($);await TW(_B(Q),{recursive:!0});let Z=Date.now()+Dq;while(!0)try{await TW(Q,{recursive:!1}),await LB(qW(Q,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
490
+ `,"utf8");try{return await J()}finally{await RB(Q)}}catch(W){if((W instanceof Error&&"code"in W?String(W.code):"")!=="EEXIST")throw W;let f=await Tq(Q),X=f?Date.now()-Date.parse(f.acquiredAt):UB+1;if(!f||!Lq(f.pid)||X>UB){await RB(Q);continue}if(Date.now()>=Z)throw Error(`Timed out waiting for hub startup lock ${Q}`);await _q(Uq)}}async function p1($,J){try{let Q=await fetch(J?.authToken?PW($):p9($),{headers:J?.authToken?{authorization:`Bearer ${J.authToken}`}:void 0});if(!Q.ok)return;let Z=await Q.json();if(typeof Z.protocolVersion!=="string"||typeof Z.host!=="string"||typeof Z.port!=="number"||typeof Z.url!=="string")return;return{protocolVersion:Z.protocolVersion,minClientProtocolVersion:typeof Z.minClientProtocolVersion==="string"?Z.minClientProtocolVersion:void 0,maxClientProtocolVersion:typeof Z.maxClientProtocolVersion==="string"?Z.maxClientProtocolVersion:void 0,capabilities:Array.isArray(Z.capabilities)?Z.capabilities.filter((W)=>typeof W==="string"):void 0,coreVersion:typeof Z.coreVersion==="string"?Z.coreVersion:void 0,buildId:typeof Z.buildId==="string"?Z.buildId:void 0,host:Z.host,port:Z.port,url:Z.url,hubId:typeof Z.hubId==="string"?Z.hubId:void 0,authToken:typeof Z.authToken==="string"?Z.authToken:void 0,pid:typeof Z.pid==="number"?Z.pid:void 0,startedAt:typeof Z.startedAt==="string"?Z.startedAt:void 0,updatedAt:typeof Z.updatedAt==="string"?Z.updatedAt:void 0}}catch{return}}function j1($,J,Q="/hub"){return new URL(`ws://${$}:${J}${Q}`).toString()}function p9($){let J=new URL($);return J.protocol=J.protocol==="wss:"?"https:":"http:",J.pathname="/health",J.search="",J.toString()}function PW($){let J=new URL(p9($));return J.pathname="/status",J.toString()}function MB($){return Aq($)}import{CLINE_HUB_DEV_PORT as Mq,CLINE_HUB_PORT as qq,resolveClineBuildEnv as Pq}from"@cline/shared";var Nq="CLINE_HUB_HOST",wq="CLINE_HUB_PORT",Sq="CLINE_HUB_PATHNAME",NW="127.0.0.1",wW=qq,SW="/hub";function qB($){return Pq($)==="development"?Mq:wW}function CW($={}){return($.env??process.env)[Nq]?.trim()||NW}function b8($={}){let Q=($.env??process.env)[wq]?.trim();if(!Q)return qB($);let Z=Number.parseInt(Q,10);if(!Number.isInteger(Z)||Z<1||Z>65535)return qB($);return Z}function yW($={}){return($.env??process.env)[Sq]?.trim()||SW}function i0($={},J={}){return{host:$.host??CW(J),port:$.port??b8(J),pathname:$.pathname??yW(J)}}import{join as Cq}from"node:path";var yq="shared:cline",Eq="CLINE_HUB_DISCOVERY_PATH",bq="hub-production";function PB($){let J=m1($.trim());return l1(`workspace:${J||$.trim()}`)}function E0($=yq){return l1($)}function n0(){return{ownerId:bq,discoveryPath:process.env[Eq]?.trim()||Cq(R2(),"locks","hub","production.json")}}var pq=8000,rq=200,iq=3000,nq=100,aq=[100,250,500,1000,2000],sq="--cline-hub-daemon";function oq($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function tq(){try{let $=vq(R2(),"logs","hub-daemon.log");return Iq(mq($),{recursive:!0}),{fd:xq($,"a"),logPath:$}}catch{return}}function CB(){return SB()==="production"?n0():E0()}function z2($){return dq($).compatible}function NB($,J,Q){if(!J||J.url!==Q)return $;return{...$,authToken:$.authToken??J.authToken,pid:$.pid??J.pid}}async function L2($,J){try{return await p1($,{authToken:J})}catch{return}}async function eq($,J){let Q=Date.now()+J;while(Date.now()<Q){if(!(await L2($))?.url)return!0;await new Promise((W)=>setTimeout(W,nq))}return!1}async function r9($,J){if(await JJ($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}let Q=await eq($.url,iq);return await y0(J).catch(()=>{return}),Q}async function $J($,J){if(z2($))return!0;return r9($,J)}async function yB($){if(SB()!=="production")return;let J=E0();if(J.discoveryPath===$.discoveryPath)return;let Q=await A0(J.discoveryPath);if(Q?.url)await r9(Q,J.discoveryPath);else await y0(J.discoveryPath).catch(()=>{return})}function $P(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return cq(new URL(`./entry.${$}`,import.meta.url))}function JP($,J){let Q=$P(),Z=process.execPath?.trim();if(!Z)throw Error("unable to resolve runtime executable for hub daemon");let W=gq(Z).toLowerCase().includes("bun"),j=Q.startsWith("/$bunfs/"),f=W&&Q.toLowerCase().endsWith(".ts"),X=j?[sq]:[...f?["--conditions=development"]:[],Q];return{launcher:Z,args:[...X,"--cwd",$,...oq(J)],cwd:$,env:{...lq(process.env),CLINE_NO_INTERACTIVE:"1",[uq]:"1"}}}function QP($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let Q="message"in $?$.message:void 0;return typeof Q==="string"&&Q.includes("ETXTBSY")}function EW($,J={}){if(wB())return;let Q=JP($,J),Z=tq();try{hq(Q.launcher,Q.args,{detached:!0,stdio:Z?["ignore",Z.fd,Z.fd]:"ignore",env:Q.env,cwd:Q.cwd,windowsHide:!0}).unref()}finally{if(Z)kq(Z.fd)}}async function h8($,J={}){for(let Q=0;;Q++)try{EW($,J);return}catch(Z){let W=aq[Q];if(!QP(Z)||W===void 0)throw Z;await new Promise((j)=>setTimeout(j,W))}}function i9($,J={}){if(wB())return;let Q=CB(),Z=i0(J),W=j1(Z.host,Z.port,Z.pathname),j=J.allowPortFallback===!0&&Z.port!==0;yB(Q).catch(()=>{return}).then(()=>A0(Q.discoveryPath)).then(async(f)=>{let X=!1;if(f?.url)if(!f.authToken){if(X=!0,!await r9(f,Q.discoveryPath)&&!j)return}else{let H=await L2(f.url,f.authToken);if(H?.url&&z2(H)&&await G1(H.url,{authToken:f.authToken}))return;if(H?.url)await $J({...H,authToken:f.authToken},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}let Y=await L2(W);if(Y?.url){if(z2(Y)){if(!j||!X)return}else if(!await $J({...Y,authToken:void 0},Q.discoveryPath)&&!j)return}let V=j?{...Z,port:0}:Z;await h8($,V)}).catch(()=>{})}async function EB($,J={}){let Q=CB(),Z=J.host!==void 0||J.port!==void 0||J.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=i0(J),j=j1(W.host,W.port,W.pathname),f=(K)=>{if(!Z)P$(K.url,K.authToken);return K};await yB(Q).catch(()=>{return});let X=await A0(Q.discoveryPath),Y=!1;if(X?.url){let K=X.authToken;if(!K)Y=!0,await r9(X,Q.discoveryPath);else{let G=await L2(X.url,K);if(G?.url&&z2(G)&&await G1(G.url,{authToken:K}))return f({url:G.url,authToken:K});if(G?.url)await $J({...G,authToken:K},Q.discoveryPath);else await y0(Q.discoveryPath).catch(()=>{return})}}let V=await L2(j);if(V?.url){let K=NB(V,X,j);if(z2(V))throw Error(`A compatible Cline Hub is already running at ${j}, but its discovery record is missing or unreadable. Run 'cline doctor fix' to repair local hub discovery.${Y?" This can happen immediately after upgrading from a build that wrote an empty hub auth token; run 'cline doctor fix' to stop the old daemon and repair local hub discovery.":""}`);if(!await $J(K,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is already running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}let B=J.allowPortFallback===!0&&W.port!==0?{...W,port:0}:W;await h8($,B);let A=Date.now()+pq;while(Date.now()<A){let K=await A0(Q.discoveryPath);if(K?.url&&K.authToken){let R=await L2(K.url,K.authToken);if(R?.url&&z2(R)&&await G1(R.url,{authToken:K.authToken}))return f({url:R.url,authToken:K.authToken})}let G=await L2(j);if(G?.url&&!z2(G)){let R=NB(G,K,j);if(!await $J(R,Q.discoveryPath)&&J.allowPortFallback!==!0&&W.port!==0)throw Error(`An incompatible Cline Hub is still running at ${j} and could not be retired automatically. Run 'cline doctor fix' to stop stale hub daemons before starting a new hub.`)}await new Promise((R)=>setTimeout(R,rq))}throw Error("Timed out waiting for detached hub startup.")}function n9(){return jP()==="production"?n0():E0()}function XP(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function xB($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return xB($.data);return String($)}function YP($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function bB($){let J=$,Q=YP(J.reason);return new q0("hub_connection_closed",J.code||Q?`Hub connection closed (code=${J.code??0}${Q?`, reason=${Q}`:""})`:bW,{closeCode:J.code,closeReason:Q||void 0})}function VP($,J){if($ instanceof q0)return $;if($ instanceof Error)return new q0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new q0("hub_connect_failed",$.error.message);let Q=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(Q)return new q0("hub_connect_failed",Q);let Z=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new q0("hub_connect_failed",Z?`Failed to connect to hub at ${J.toString()} (${Z} event before socket open).`:`Failed to connect to hub at ${J.toString()}.`)}var HP=8000,BP=200,hB="*",kB=8000,AP="cline-hub-auth.",gB=new Map,mB=new Set,KP=3000,GP=3000,FP=100,bW="Hub connection closed",DP=250,UP=5000,IB=0.5;class q0 extends Error{code;details;constructor($,J,Q){super(J);this.code=$;this.details=Q;this.name="HubTransportError"}}function IW($){return $ instanceof q0}class k8 extends Error{command;code;constructor($,J,Q){super(Q);this.command=$;this.code=J;this.name="HubCommandError"}}function a9($,J){return $ instanceof k8&&$.code==="hub_command_timeout"&&(J===void 0||$.command===J)}function vB($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=xW($.toString());return Q?gB.get(Q):void 0}function RP($){try{let Q=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return Q==="localhost"||Q==="127.0.0.1"||Q==="::1"}catch{return!1}}function xW($){if(!RP($))return;let J=new URL(N$($));return J.search="",J.hash="",J.toString()}function hW($){let J=xW($);return!!J&&mB.has(J)}function P$($,J){let Q=xW($);if(Q){if(mB.add(Q),J?.trim())gB.set(Q,J)}return $}class f1{options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new q0("hub_connection_closed",bW);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),J=this.options.authToken?.trim()||vB($);$.hash="";let Z=new(XP())($.toString(),J?[`${AP}${J}`]:void 0);this.socket=Z;let W=!1;this.connectPromise=new Promise((j,f)=>{let X=!1,Y=setTimeout(()=>{if(X)return;X=!0,W=!0,this.lastCloseError=new q0("hub_connect_timeout",`Timed out connecting to hub after ${kB}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Z.close()}catch{}f(this.lastCloseError)},kB);Z.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(Y),j()}),Z.addEventListener("error",(V)=>{if(X)return;X=!0,clearTimeout(Y),this.lastCloseError=VP(V,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)}),Z.addEventListener("close",(V)=>{if(X)return;if(X=!0,clearTimeout(Y),!W)this.lastCloseError=bB(V),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,f(this.lastCloseError)})}),Z.addEventListener("message",(j)=>{this.handleFrame(JSON.parse(xB(j)))}),Z.addEventListener("close",(j)=>{if(this.socket!==Z)return;if(!W)this.lastCloseError=bB(j),this.sawSocketClose=!0;this.registered=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let j of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(j));this.reconnectAttempt=0}subscribe($,J){let Q=J?.sessionId?.trim()||void 0,Z={listener:$,sessionId:Q};return this.listeners.add(Z),this.adjustSubscriptionCount(Q,1),()=>{if(!this.listeners.delete(Z))return;this.adjustSubscriptionCount(Q,-1)}}async command($,J,Q,Z){let W=0,j=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,J,Q,Z)}catch(f){if(!j||W>=1||!await this.recoverLocalHubTransport(f))throw f;W+=1}}async commandOnce($,J,Q,Z){await this.connect();let W=ZP("hubreq_"),j=fP($,Z?.timeoutMs),f=new Promise((Y,V)=>{let H=j===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(W))return;V(new k8($,"hub_command_timeout",`Hub command ${$} timed out after ${j}ms (hub=${this.currentUrl}, requestId=${W}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},j);this.pendingReplies.set(W,{resolve:(B)=>{if(H)clearTimeout(H);Y(B)},reject:(B)=>{if(H)clearTimeout(H);V(B)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:W,clientId:this.clientId,sessionId:Q,timeoutMs:j,payload:J}})}catch(Y){throw this.pendingReplies.delete(W),Y}let X=await f;if(!X.ok){if(X.error?.code===G2){let Y=Q??(typeof J?.sessionId==="string"?J.sessionId:void 0);throw new u1(Y,X.error.message)}throw new k8($,X.error?.code,X.error?.message??`Hub command ${$} failed`)}return X}async recoverLocalHubTransport($){if(!hW(this.currentUrl)||!IW($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let J=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!J)return!1;return this.currentUrl=J,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(DP*2**this.reconnectAttempt,UP),J=Math.round($*(1-IB)+Math.random()*$*IB);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},J)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!hW(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await _2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd});if($){this.currentUrl=$,await this.connect(),this.reconnectAttempt=0;return}}catch{}this.reconnectAttempt+=1,this.scheduleReconnect()}}close(){let $=this.socket;if(this.closedByClient=!0,this.clearReconnectTimer(),this.registered=!1,!$)return;this.lastCloseError=new q0("hub_connection_closed",bW),this.sawSocketClose=!1;for(let J of this.pendingReplies.values())J.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new q0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,J){this.sendFrame({kind:$,clientId:this.clientId,...J?{sessionId:J}:{}})}adjustSubscriptionCount($,J){let Q=this.subscriptionKeyForSessionId($),Z=(this.subscriptionCounts.get(Q)??0)+J;if(Z<=0){if(this.subscriptionCounts.delete(Q),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(J<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(Q,Z),J>0&&Z===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??hB}subscriptionSessionIdFromKey($){return $===hB?void 0:$}handleFrame($){switch($.kind){case"reply":{let J=$.envelope.requestId;if(!J)return;let Q=this.pendingReplies.get(J);if(!Q)return;this.pendingReplies.delete(J),Q.resolve($.envelope);return}case"event":for(let J of this.listeners){if(J.sessionId&&J.sessionId!==$.envelope.sessionId?.trim())continue;J.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function N$($){let J=new URL($);if(J.protocol==="http:")J.protocol="ws:";else if(J.protocol==="https:")J.protocol="wss:";return J.toString()}async function G1($,J){let Q=new f1({url:$,authToken:J?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{return await Q.connect(),!0}catch{return!1}finally{Q.close()}}async function kW($,J){let Q=N$($),Z=await p1(Q,{authToken:J?.authToken});if(!Z)return{status:"unreachable",url:Q};if(!WP(Z).compatible)return{status:"protocol_mismatch",url:Q};if(J?.verifyConnection===!0&&!await G1(Q,{workspaceRoot:J.workspaceRoot,cwd:J.cwd,authToken:J.authToken}))return{status:"unreachable",url:Q};return{status:"compatible",url:Q}}async function zP($){let J=Date.now()+HP;while(Date.now()<J){let Q=await A0($.discoveryPath);if(Q?.url){let Z=await kW(Q.url,{verifyConnection:!0,authToken:Q.authToken});if(Z.status==="compatible")return P$(Z.url,Q.authToken)}await new Promise((Z)=>setTimeout(Z,BP))}return}async function LP($){let J=Date.now()+GP;while(Date.now()<J){if(!(await p1($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,FP))}return!1}function _P($,J){try{return N$($)===N$(J)}catch{return!1}}function OP($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((Q)=>{if(!Q||typeof Q!=="object")return!1;let Z=Q;if(Z.status==="running"||Z.status==="idle"||Z.status==="pending")return!0;return Array.isArray(Z.participants)&&Z.participants.length>0})}async function TP($,J,Q){let Z=new f1({url:$,authToken:J,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:Q?.workspaceRoot,cwd:Q?.cwd});try{let W=await Z.command("session.list",{limit:500},void 0,{timeoutMs:KP});return!OP(W.payload)}catch{return!1}finally{await Z.dispose().catch(()=>{return})}}async function QJ($={}){if($.endpoint?.trim()){let W=await kW($.endpoint);return W.status==="compatible"?W.url:void 0}let J=n9(),Q=await A0(J.discoveryPath);if(!Q?.url)return;let Z=await kW(Q.url,{authToken:Q.authToken});if(Z.status==="compatible")return P$(Z.url,Q.authToken);if(Z.status==="protocol_mismatch")await y0(J.discoveryPath).catch(()=>{return});return}async function _2($={}){let J=await QJ($);if(J&&await G1(J,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return J;if($.endpoint?.trim())return;let Q=n9();return await h8($.workspaceRoot??process.cwd()),await zP(Q)}async function JJ($,J){let Q=new URL($),Z=J?.trim()||vB(Q);if(Q.protocol==="ws:")Q.protocol="http:";else if(Q.protocol==="wss:")Q.protocol="https:";return Q.pathname="/shutdown",Q.hash="",(await fetch(Q,{method:"POST",headers:Z?{authorization:`Bearer ${Z}`}:void 0})).ok}async function gW($=n9()){let J=await A0($.discoveryPath);if(!J?.url)return!1;try{if(await JJ(J.url,J.authToken))return!0}catch{}return!1}async function s9($){if(!hW($.url))return;let J=n9(),Q=await A0(J.discoveryPath);if(!Q?.url||!_P(Q.url,$.url))return;if(!await TP(Q.url,Q.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await gW())return;if(!await LP(Q.url))return;return await y0(J.discoveryPath).catch(()=>{return}),await _2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}var eB={};w(eB,{HubRuntimeHost:()=>r1});import{captureSdkError as uB,createSessionId as dB,HUB_CHECKPOINT_CAPABILITY as NP,HUB_COMPACTION_CAPABILITY as wP,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as SP,HUB_HOOK_CAPABILITY_PREFIX as CP,HUB_MISTAKE_LIMIT_CAPABILITY as yP,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as EP,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as bP,isHubToolExecutorName as hP}from"@cline/shared";var cB={};w(cB,{createCoreSessionSnapshot:()=>F1,coreSessionSnapshotToRecord:()=>o9});function MP($){return $?JSON.parse(JSON.stringify($)):void 0}function qP($){return $?JSON.parse(JSON.stringify($)):void 0}function PP($){let J=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Z=(Array.isArray(J?.history)?J.history:[]).filter((f)=>!!f&&typeof f==="object"&&!Array.isArray(f)).flatMap((f)=>{let X=typeof f.ref==="string"?f.ref.trim():"",Y=Number(f.createdAt),V=Number(f.runCount);if(!X||!Number.isFinite(Y)||!Number.isInteger(V))return[];return[{ref:X,createdAt:Y,runCount:V,...f.kind==="stash"||f.kind==="commit"?{kind:f.kind}:{}}]}),W=Z.at(-1),j=$?.checkpointEnabled===!0?!0:void 0;if(!j&&Z.length===0)return;return{...j?{enabled:j}:{},...W?{latest:W}:{},history:Z}}function F1($){let{session:J}=$,Q=MP(J.metadata);return{version:1,sessionId:J.sessionId,source:J.source,status:J.status,createdAt:J.startedAt,updatedAt:J.updatedAt,endedAt:J.endedAt??null,exitCode:J.exitCode??null,interactive:J.interactive,workspace:{cwd:J.cwd,root:J.workspaceRoot},model:{providerId:J.provider,modelId:J.model},capabilities:{enableTools:J.enableTools,enableSpawn:J.enableSpawn,enableTeams:J.enableTeams},lineage:{...J.parentSessionId?{parentSessionId:J.parentSessionId}:{},...J.parentAgentId?{parentAgentId:J.parentAgentId}:{},...J.agentId?{agentId:J.agentId}:{},...J.conversationId?{conversationId:J.conversationId}:{},isSubagent:J.isSubagent},...J.teamName?{team:{name:J.teamName}}:{},...J.prompt?{prompt:J.prompt}:{},...Q?{metadata:Q}:{},...J.messagesPath?{artifacts:{messagesPath:J.messagesPath}}:{},...$.messages?{messages:qP($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Z=PP(Q);return Z?{checkpoint:Z}:{}})()}}function o9($){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 I8($){if(!$)return;return JSON.parse(JSON.stringify($))}var kP=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function lB($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function pB($){if(!$)return;let{userInstructionService:J,...Q}=$;return JSON.parse(JSON.stringify(Q))}function rB($){let J=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof J.agentId==="string"?J.agentId:"",conversationId:typeof J.conversationId==="string"?J.conversationId:"",iteration:typeof J.iteration==="number"?J.iteration:0,metadata:J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0}}function O2($,J,Q){$.manifest.push(J),$.handlers.set(J.capabilityName,Q)}function iB($,J){let Q={manifest:[],handlers:new Map};for(let W of Object.keys(J.toolExecutors??{}).filter(hP)){let j=J.toolExecutors?.[W];if(typeof j!=="function")continue;O2(Q,{kind:"toolExecutor",executor:W,capabilityName:`${EP}${W}`},async({payload:f,abortSignal:X})=>{let Y=Array.isArray(f.args)?[...f.args]:[],V={...rB(f.context),signal:X};return{result:await j(...Y,V)}})}for(let W of $?.extraTools??[])O2(Q,{kind:"tool",name:W.name,description:W.description,inputSchema:I8(W.inputSchema)??{},...W.lifecycle?{lifecycle:I8(W.lifecycle)}:{},capabilityName:`${SP}${W.name}`},async({payload:j,abortSignal:f,progress:X})=>{let Y={...rB(j.context),signal:f};return{result:await W.execute(j.input,{...Y,emitUpdate:(H)=>{X({update:H})}})}});let Z=$?.hooks;if(Z)for(let W of kP){let j=Z[W];if(typeof j!=="function")continue;O2(Q,{kind:"hook",name:W,capabilityName:`${CP}${W}`},async({payload:f})=>({control:await j(f.context)}))}if($?.compaction?.compact){let W=$.compaction.compact;O2(Q,{kind:"compaction",capabilityName:wP,config:lB($.compaction)},async({payload:j})=>({result:await W(j.context)}))}if($?.checkpoint?.createCheckpoint){let W=$.checkpoint.createCheckpoint;O2(Q,{kind:"checkpoint",capabilityName:NP,config:lB($.checkpoint)},async({payload:j})=>({result:await W(j.context)}))}if($?.onConsecutiveMistakeLimitReached){let W=$.onConsecutiveMistakeLimitReached;O2(Q,{kind:"mistakeLimit",capabilityName:yP},async({payload:j})=>({result:await W(j.context)}))}if($?.userInstructionService){let W=$.userInstructionService;O2(Q,{kind:"userInstructionService",capabilityName:bP},async()=>{return await W.start().catch(()=>{}),{snapshot:{records:{skill:W.listRecords("skill"),rule:W.listRecords("rule"),workflow:W.listRecords("workflow")},runtimeCommands:W.listRuntimeCommands()}}})}return Q}function oB($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let J=$.message;if(typeof J==="string"&&J.trim())return J.trim()}return}function IP($){return oB($)??"Capability request was cancelled."}function xP($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function gP($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function mP($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=typeof J.inputTokens==="number"?J.inputTokens:void 0,Z=typeof J.outputTokens==="number"?J.outputTokens:void 0;if(Q===void 0||Z===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:typeof J.cacheReadTokens==="number"?J.cacheReadTokens:0,cacheWriteTokens:typeof J.cacheWriteTokens==="number"?J.cacheWriteTokens:0,totalCost:typeof J.totalCost==="number"?J.totalCost:0}}function nB($){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 mW($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function w$($,J){return mW($?.[J])??0}function vP($){let J=$?.delta&&typeof $.delta==="object"?$.delta:void 0,Q=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Z=$?.agent&&typeof $.agent==="object"?$.agent:void 0,W=Z?.teamRole==="teammate"||Z?.teamRole==="lead"?Z.teamRole:void 0;return{event:{type:"usage",agentId:typeof Z?.agentId==="string"?Z.agentId:void 0,conversationId:typeof Z?.conversationId==="string"?Z.conversationId:void 0,parentAgentId:typeof Z?.parentAgentId==="string"?Z.parentAgentId:void 0,inputTokens:w$(J,"inputTokens"),outputTokens:w$(J,"outputTokens"),cacheReadTokens:w$(J,"cacheReadTokens"),cacheWriteTokens:w$(J,"cacheWriteTokens"),cost:mW(J?.totalCost),totalInputTokens:w$(Q,"inputTokens"),totalOutputTokens:w$(Q,"outputTokens"),totalCacheReadTokens:w$(Q,"cacheReadTokens"),totalCacheWriteTokens:w$(Q,"cacheWriteTokens"),totalCost:mW(Q?.totalCost)},teamAgentId:typeof Z?.teamAgentId==="string"?Z.teamAgentId:void 0,teamRole:W}}function cP($){let J=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,Q=$?.reason??J?.finishReason,Z=gP(Q)?Q:Q==="failed"?"error":"completed",W=mP($?.usage??J?.usage);return{type:"done",reason:Z,text:typeof $?.text==="string"?$.text:typeof J?.text==="string"?J.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof J?.iterations==="number"?J.iterations:0,usage:W}}function t9($,J){return $.error?.message??`hub command failed: ${J}`}function ZJ($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function tB($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof J?.agentId==="string"?J.agentId:void 0),parentAgentId:typeof J?.parentAgentId==="string"?J.parentAgentId:void 0,conversationId:typeof J?.conversationId==="string"?J.conversationId:void 0,isSubagent:typeof J?.isSubagent==="boolean"?J.isSubagent:!1,source:typeof J?.source==="string"?J.source:U0.CORE,pid:typeof J?.pid==="number"?J.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:ZJ($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:ZJ($.status)==="completed"?0:ZJ($.status)==="failed"?1:void 0,status:ZJ($.status),interactive:J?.interactive===!0,provider:typeof J?.provider==="string"?J.provider:"hub",model:typeof J?.model==="string"?J.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof J?.teamName==="string"?J.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??J?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??J?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??J?.enableTeams===!0,prompt:typeof J?.prompt==="string"?J.prompt:void 0,metadata:J,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,hookPath:typeof J?.hookPath==="string"?J.hookPath:void 0}}function S$($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;return J.version===1&&typeof J.sessionId==="string"?JSON.parse(JSON.stringify(J)):void 0}function uP($){let J=S$($?.snapshot);if(J)return o9(J);let Q=$?.session;return Q?tB(Q):void 0}function aB($,J,Q){let Z=Q?.workspaceRoot?.trim()||J.config.workspaceRoot||J.config.cwd;return S0.parse({version:1,session_id:$,source:J.source??U0.CORE,pid:process.pid,started_at:new Date(Q?.createdAt??Date.now()).toISOString(),status:ZJ(Q?.status),interactive:J.interactive===!0,provider:J.config.providerId,model:J.config.modelId,cwd:Q?.cwd?.trim()||J.config.cwd,workspace_root:Z,team_name:J.config.teamName,enable_tools:J.config.enableTools,enable_spawn:J.config.enableSpawnAgent,enable_teams:J.config.enableAgentTeams,prompt:J.prompt?.trim()||void 0,metadata:J.sessionMetadata&&Object.keys(J.sessionMetadata).length>0?J.sessionMetadata:void 0})}function sB($,J){return S0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??J.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class r1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new o6;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,J){this.clientContext=J,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd},this.defaultCapabilities=L0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(Q)=>this.requestPendingPromptsList(Q),update:(Q)=>this.requestPendingPromptUpdate(Q),delete:(Q)=>this.requestPendingPromptDelete(Q)},this.client=this.createClient($.url)}createClient($){return new f1({...this.clientOptions,url:$})}async replaceClient($){let J=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(J.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!a9($,"session.create"))return!1;let J=await s9({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!J)return!1;return await this.replaceClient(J),!0}registerPlannedSession($,J,Q){if(this.sessionCapabilities.set($,J),Q.size>0)this.sessionClientContributionHandlers.set($,Q);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let J=this.resolveCapabilities($),Q=iB($.localRuntime,J),Z=$.config.sessionId?.trim()||dB(),W=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:I8({...$.config,sessionId:Z}),metadata:{...$.sessionMetadata??{},source:$.source??U0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...Q.manifest.length>0?{clientContributions:Q.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:I8($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Z,J,Q.handlers);let j;try{j=await W()}catch(V){if(this.cleanupPlannedSession(Z),await this.recoverLocalHubStartupDeadlock(V)){this.registerPlannedSession(Z,J,Q.handlers);try{j=await W()}catch(H){throw this.cleanupPlannedSession(Z),H}}else throw V}let f=S$(j.payload?.snapshot),X=j.payload?.session,Y=(f?.sessionId??X?.sessionId)?.trim();if(!Y)throw this.cleanupPlannedSession(Z),Error("Hub runtime did not return a session id.");if(Y!==Z)this.cleanupPlannedSession(Z),this.registerPlannedSession(Y,J,Q.handlers);return{sessionId:Y,manifest:f?sB(f,$):aB(Y,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.start)throw Error("start is required when restore.messages is true");let Z=$.start,W=Z?this.resolveCapabilities(Z):void 0,j=Z?iB(Z.localRuntime,W??{}):{manifest:[],handlers:new Map},f=Z?Z.config.sessionId?.trim()||dB():void 0;if(f&&W)this.sessionCapabilities.set(f,W);if(f&&j.handlers.size>0)this.sessionClientContributionHandlers.set(f,j.handlers),this.ensureSessionSubscription(f);let X;try{X=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.config.workspaceRoot?.trim()||Z.config.cwd,cwd:Z.config.cwd??$.cwd,sessionConfig:I8({...Z.config,sessionId:f}),metadata:{...Z.sessionMetadata??{},source:Z.source??U0.CORE,provider:Z.config.providerId,model:Z.config.modelId,enableTools:Z.config.enableTools,enableSpawn:Z.config.enableSpawnAgent,enableTeams:Z.config.enableAgentTeams,teamName:Z.config.teamName,prompt:Z.prompt,interactive:Z.interactive===!0},runtimeOptions:{...j.manifest.length>0?{clientContributions:j.manifest}:{},...Z.localRuntime?.configExtensions?{configExtensions:Z.localRuntime.configExtensions}:{}},toolPolicies:I8(Z.toolPolicies)}:{}},J)}catch(K){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error(K)}let Y=S$(X.payload?.snapshot),V=X.payload?.session,H=(Y?.sessionId??V?.sessionId)?.trim();if(Q&&!H){if(f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);throw Error("Hub checkpoint restore returned no session id")}if(H&&f&&H!==f)this.sessionCapabilities.delete(f),this.sessionClientContributionHandlers.delete(f),this.disposeSessionSubscription(f);if(H&&W)this.sessionCapabilities.set(H,W);if(H&&j.handlers.size>0)this.sessionClientContributionHandlers.set(H,j.handlers);if(H)this.ensureSessionSubscription(H);let B=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,A=X.payload?.checkpoint;if(!A)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:H,startResult:H?{sessionId:H,manifest:Y?sB(Y,Z??{}):aB(H,Z??{},V),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:B,checkpoint:A}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(J.payload?.prompts)?J.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,updated:J.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let J=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(J.payload?.prompts)?J.payload.prompts:[],prompt:J.payload?.prompt,removed:J.payload?.removed===!0}}async getAccumulatedUsage($){let J=await this.client.command("session.get",{includeSnapshot:!0},$),Q=S$(J.payload?.snapshot);if(Q){let f=Q.usage?{...Q.usage}:void 0,X=Q.aggregateUsage?{...Q.aggregateUsage}:void 0;return f||X?{usage:f,aggregateUsage:X}:void 0}let Z=J.payload?.session,W=nB(Z?.usage),j=nB(Z?.aggregateUsage);return W||j?{usage:W,aggregateUsage:j}:void 0}async abort($,J){await this.client.command("run.abort",{sessionId:$,reason:oB(J)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,J]of this.sessionSubscriptions){J();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(d1(Q))return;throw Q}return uP(J.payload)}async listSessions($=100){let J=await this.client.command("session.list",{limit:$}),Q=Array.isArray(J.payload?.snapshots)?J.payload.snapshots.flatMap((W)=>{let j=S$(W);return j?[o9(j)]:[]}):[];if(Q.length>0)return Q;return(J.payload?.sessions??[]).map(tB)}async listSettings($){let J=await this.client.command("settings.list",pB($));if(!J.ok)throw Error(t9(J,"settings.list"));return J.payload?.snapshot}async toggleSetting($){let J=await this.client.command("settings.toggle",pB($));if(!J.ok)throw Error(t9(J,"settings.toggle"));return{snapshot:J.payload?.snapshot,changedTypes:Array.isArray(J.payload?.changedTypes)?J.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,J){let Q={...J.metadata??{}};if(typeof J.prompt==="string")Q.prompt=J.prompt;if(typeof J.title==="string")Q.title=J.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:Q})).ok}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw uB(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(t9(Q,"session.messages")),severity:Q.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:J,errorCode:Q.error?.code,runtimeAddress:this.runtimeAddress}}),Error(t9(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,J){return this.events.subscribe($,J)}ensureSessionSubscription($){let J=$.trim();if(!J||this.sessionSubscriptions.has(J))return;let Q=this.client.subscribe((Z)=>{this.handleHubEvent(Z)},{sessionId:J});this.sessionSubscriptions.set(J,typeof Q==="function"?Q:()=>{})}disposeSessionSubscription($){let J=$.trim();if(!J)return;this.sessionSubscriptions.get(J)?.(),this.sessionSubscriptions.delete(J),this.agentDoneEmittedForCurrentRunBySession.delete(J)}resolveCapabilities($){return L0(this.defaultCapabilities,$.capabilities)??{}}emitToolCallContentStart($){this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:{type:"content_start",contentType:"tool",toolCallId:$.toolCallId,toolName:$.toolName,input:$.toolInput}}})}emitAgentDoneIfNeeded($){if(this.agentDoneEmittedForCurrentRunBySession.has($.sessionId))return;this.agentDoneEmittedForCurrentRunBySession.add($.sessionId),this.events.emit({type:"agent_event",payload:{sessionId:$.sessionId,event:cP($.payload)}})}handleHubEvent($){let J=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",Q,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((Q)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",Q,$)});return}if(!J)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(J);let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"";if(!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"text",text:Q}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let Q=typeof $.payload?.text==="string"?$.payload.text:"",Z=$.payload?.redacted===!0;if(!Q&&!Z)return;this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_start",contentType:"reasoning",reasoning:Q,redacted:Z}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:J,payload:$.payload});return}case"usage.updated":{let Q=vP($.payload);this.events.emit({type:"agent_event",payload:{sessionId:J,event:Q.event,teamAgentId:Q.teamAgentId,teamRole:Q.teamRole}});return}case"tool.started":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q&&this.pendingApprovalToolCallIds.delete(Q))return;this.emitToolCallContentStart({sessionId:J,toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let Q=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(Q)this.pendingApprovalToolCallIds.delete(Q);this.events.emit({type:"agent_event",payload:{sessionId:J,event:{type:"content_end",contentType:"tool",toolCallId:Q,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let Q=S$($.payload?.snapshot),Z=$.payload?.session;if(Q)this.events.emit({type:"session_snapshot",payload:{sessionId:J,snapshot:Q}});this.events.emit({type:"status",payload:{sessionId:J,status:Z?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:J,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let Q=$.payload?.prompt;if(!Q)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:J,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let Q=S$($.payload?.snapshot),Z=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:J,payload:{...$.payload,reason:Z}}),Q?.interactive===!0&&j0(Q.status))return;this.events.emit({type:"ended",payload:{sessionId:J,reason:Z,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,J,Q){try{uB(this.telemetry,{component:"core",operation:$,error:J,severity:"warn",handled:!0,context:{event:Q.event,sessionId:Q.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let J=$.sessionId?.trim();if(!J)return;let Q=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(Q&&Q!==this.client.getClientId())return;let Z=typeof $.payload?.requestId==="string"?$.payload.requestId:"",W=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Z)return;let j=this.sessionClientContributionHandlers.get(J)?.get(W);if(!j){await this.client.command("capability.respond",{requestId:Z,ok:!1,error:`No client contribution handler registered for capability ${W} in session ${J}.`},J).catch(()=>{});return}let f=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Z,X);let Y=(V)=>{this.client.command("capability.progress",{requestId:Z,payload:V},J).catch((H)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",H,$)})};try{let V=await j({payload:f,abortSignal:X.signal,progress:Y});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!0,payload:V},J)}catch(V){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Z,ok:!1,error:V instanceof Error?V.message:String(V)},J)}finally{this.activeCapabilityAbortControllers.delete(Z)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let J=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!J)return;let Q=this.activeCapabilityAbortControllers.get(J);if(!Q)return;Q.abort(IP($.payload.error))}async handleApprovalRequested($){let J=$.sessionId?.trim();if(!J)return;let Q=this.sessionCapabilities.get(J)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!Q)return;let Z=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",W=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",j=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Z||!W||!j)return;let f=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=xP($.payload?.inputJson);this.pendingApprovalToolCallIds.add(W),this.emitToolCallContentStart({sessionId:J,toolCallId:W,toolName:j,toolInput:X});let Y=await Promise.resolve(Q({sessionId:J,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:J,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:W,toolName:j,input:X,policy:f})).catch((V)=>({approved:!1,reason:V instanceof Error?V.message:`Tool approval request failed: ${String(V)}`}));await this.client.command("approval.respond",{approvalId:Z,approved:Y.approved,reason:Y.reason},J).catch(()=>{})}}var $A={};w($A,{RemoteRuntimeHost:()=>x8});class x8 extends r1{constructor($){super({url:N$($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}var JA={};w(JA,{SqliteSessionStore:()=>U1});import{existsSync as dP,mkdirSync as lP}from"node:fs";import{join as pP}from"node:path";import{asBool as WJ,asOptionalString as D1,asString as i1,ensureSessionSchema as rP,loadSqliteDb as iP,nowIso as e9,toBoolInt as jJ}from"@cline/shared/db";import{resolveDbDataDir as nP}from"@cline/shared/storage";class U1{sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??nP()}init(){this.getRawDb()}ensureSessionsDir(){if(!dP(this.sessionsDirPath))lP(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return pP(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=iP(this.sessionDbPath());return rP($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}create($){let J=e9();this.run(`INSERT OR REPLACE INTO sessions (
491
491
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
492
492
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
493
493
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
494
494
  metadata_json, transcript_path, hook_path, messages_path, updated_at
495
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,jJ($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,jJ($.enableTools),jJ($.enableSpawn),jJ($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,jJ($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,J])}update($){let J=[],Q=[];if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId);if(J.length===0)return;J.push("updated_at = ?"),Q.push(eQ()),Q.push($.sessionId),this.run(`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`,Q)}updateStatus($,J,Q){this.update({sessionId:$,status:J,endedAt:j0(J)?null:eQ(),exitCode:j0(J)?null:Q??(J==="failed"?1:0)})}get($){let J=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
495
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,jJ($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,jJ($.enableTools),jJ($.enableSpawn),jJ($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,jJ($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,J])}update($){let J=[],Q=[];if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId);if(J.length===0)return;J.push("updated_at = ?"),Q.push(e9()),Q.push($.sessionId),this.run(`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`,Q)}updateStatus($,J,Q){this.update({sessionId:$,status:J,endedAt:j0(J)?null:e9(),exitCode:j0(J)?null:Q??(J==="failed"?1:0)})}get($){let J=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
496
496
  provider, model, cwd, workspace_root, team_name,
497
497
  enable_tools, enable_spawn, enable_teams,
498
498
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
499
499
  prompt, metadata_json, hook_path, messages_path, updated_at
500
- FROM sessions WHERE session_id = ?`,[$]);if(!J)return;return{sessionId:i1(J.session_id),source:i1(J.source),pid:Number(J.pid??0),startedAt:i1(J.started_at),endedAt:J.ended_at??null,exitCode:J.exit_code??null,status:i1(J.status),interactive:WJ(J.interactive),provider:i1(J.provider),model:i1(J.model),cwd:i1(J.cwd),workspaceRoot:i1(J.workspace_root),teamName:D1(J.team_name),enableTools:WJ(J.enable_tools),enableSpawn:WJ(J.enable_spawn),enableTeams:WJ(J.enable_teams),parentSessionId:D1(J.parent_session_id),parentAgentId:D1(J.parent_agent_id),agentId:D1(J.agent_id),conversationId:D1(J.conversation_id),isSubagent:WJ(J.is_subagent),prompt:D1(J.prompt),metadata:(()=>{let Q=D1(J.metadata_json);if(!Q)return;try{let Z=JSON.parse(Q);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return})(),hookPath:D1(J.hook_path),messagesPath:D1(J.messages_path),updatedAt:D1(J.updated_at)??eQ()}}list($=200){let J=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let Z of J){let W=this.get(i1(Z.session_id));if(W)Q.push(W)}return Q}delete($,J=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}g8();import{existsSync as tW,mkdirSync as vN,readFileSync as RA,renameSync as cN,writeFileSync as uN}from"node:fs";import{join as zA}from"node:path";import{resolveSessionDataDir as dN}from"@cline/shared/storage";import{dirname as gN}from"node:path";import{nanoid as mN}from"nanoid";import{appendFileSync as XN,existsSync as YN,mkdirSync as ZA,readFileSync as VN,writeFileSync as WA}from"node:fs";import{dirname as jA,join as HN}from"node:path";import{ensureHookLogDir as BN}from"@cline/shared/storage";class vW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,J,Q){this.adapter=$;this.messagesArtifactUploader=J;this.logger=Q;this.artifacts=new m7(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,J,Q){kY(J,Q,Z7($))}writeSessionManifest($,J){ZA(jA($),{recursive:!0}),WA($,`${JSON.stringify(S0.parse(J),null,2)}
500
+ FROM sessions WHERE session_id = ?`,[$]);if(!J)return;return{sessionId:i1(J.session_id),source:i1(J.source),pid:Number(J.pid??0),startedAt:i1(J.started_at),endedAt:J.ended_at??null,exitCode:J.exit_code??null,status:i1(J.status),interactive:WJ(J.interactive),provider:i1(J.provider),model:i1(J.model),cwd:i1(J.cwd),workspaceRoot:i1(J.workspace_root),teamName:D1(J.team_name),enableTools:WJ(J.enable_tools),enableSpawn:WJ(J.enable_spawn),enableTeams:WJ(J.enable_teams),parentSessionId:D1(J.parent_session_id),parentAgentId:D1(J.parent_agent_id),agentId:D1(J.agent_id),conversationId:D1(J.conversation_id),isSubagent:WJ(J.is_subagent),prompt:D1(J.prompt),metadata:(()=>{let Q=D1(J.metadata_json);if(!Q)return;try{let Z=JSON.parse(Q);if(Z&&typeof Z==="object"&&!Array.isArray(Z))return Z}catch{}return})(),hookPath:D1(J.hook_path),messagesPath:D1(J.messages_path),updatedAt:D1(J.updated_at)??e9()}}list($=200){let J=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),Q=[];for(let Z of J){let W=this.get(i1(Z.session_id));if(W)Q.push(W)}return Q}delete($,J=!1){let Q=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}}g8();import{existsSync as tW,mkdirSync as vN,readFileSync as UA,renameSync as cN,writeFileSync as uN}from"node:fs";import{join as RA}from"node:path";import{resolveSessionDataDir as dN}from"@cline/shared/storage";import{dirname as gN}from"node:path";import{nanoid as mN}from"nanoid";import{appendFileSync as XN,existsSync as YN,mkdirSync as QA,readFileSync as VN,writeFileSync as ZA}from"node:fs";import{dirname as WA,join as HN}from"node:path";import{ensureHookLogDir as BN}from"@cline/shared/storage";class vW{adapter;messagesArtifactUploader;logger;artifacts;constructor($,J,Q){this.adapter=$;this.messagesArtifactUploader=J;this.logger=Q;this.artifacts=new m7(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,J,Q){hY(J,Q,Z7($))}writeSessionManifest($,J){QA(WA($),{recursive:!0}),ZA($,`${JSON.stringify(S0.parse(J),null,2)}
501
501
  `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let J=this.artifacts.sessionManifestPath($,!1);if(!YN(J))return{path:J};try{return{path:J,manifest:S0.parse(JSON.parse(VN(J,"utf8")))}}catch{return{path:J}}}async resolveArtifactPath($,J,Q){let W=(await this.adapter.getSession($))?.[J];return typeof W==="string"&&W.trim().length>0?W:Q($)}async persistSessionMessages($,J,Q){let Z=await this.resolveArtifactPath($,"messagesPath",(f)=>this.artifacts.sessionMessagesPath(f)),W=W7({updatedAt:e(),context:Z7($),messages:J,systemPrompt:Q}),j=`${JSON.stringify(W,null,2)}
502
- `;if(ZA(jA(Z),{recursive:!0}),WA(Z,j,"utf8"),!this.messagesArtifactUploader)return;try{let f=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Z,contents:j,row:f})}catch(f){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:f})}}appendStaleSessionHookLog($,J,Q,Z,W){let f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??HN(BN(),"hooks.jsonl");XN(f,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Z,sessionId:J,pid:Q,source:W})}
503
- `,"utf8")}}import{appendFileSync as AN}from"node:fs";import{join as KN}from"node:path";import{resolveRootSessionId as fA}from"@cline/shared";import{ensureHookLogDir as GN}from"@cline/shared/storage";import{z as cW}from"zod";var FN="subagent",DN=cW.looseObject({task:cW.string().optional(),systemPrompt:cW.string().optional()});class $9{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,J,Q,Z){this.adapter=$;this.manifestStore=J;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=Z}teamTaskQueueKey($,J){return`${$}::${J}`}activeTeamTaskSessionId($,J){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,J))?.at(-1)}buildSubsessionRow($,J){return{sessionId:J.sessionId,source:FN,pid:process.ppid,startedAt:J.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:J.parentSessionId,parentAgentId:J.parentAgentId,agentId:J.agentId,conversationId:J.conversationId??null,isSubagent:!0,prompt:J.prompt,metadata:J6({prompt:J.prompt}),hookPath:"",messagesPath:J.messagesPath,updatedAt:J.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let J=fA($.sessionContext);if(!J)return;let Q=DN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:J,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let J=$.rootSessionId;if(!J)return;let Q=await this.adapter.getSession(J);if(!Q)return;let Z=Z8(J,$.agentId),W=await this.adapter.getSession(Z),j=e(),f=this.manifestStore.artifacts.subagentArtifactPaths(Z,$.agentId,this.activeTeamTaskSessionId(J,$.parentAgentId)),X=$.prompt??W?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(J,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:j,...f})),this.manifestStore.initializeMessagesFile(Z,f.messagesPath,j),Z;return await this.adapter.updateSession({sessionId:Z,setRunning:!0,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:W.prompt??X??null,metadata:J6({metadata:W.metadata??void 0,prompt:W.prompt??X??null}),expectedStatusLock:W.statusLock}),Z}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let J=fA($.sessionContext);if(!J)return;if($.hookName==="session_shutdown"){let Q=Z8(J,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:J})}async applySubagentStatus($,J){await this.applySubagentStatusBySessionId($,t4(J))}async applySubagentStatusBySessionId($,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=j0(J)?null:e(),W=j0(J)?null:J==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:J,endedAt:Z,exitCode:W,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,J){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Z of Q)await this.applySubagentStatusBySessionId(Z.sessionId,J)}async onTeamTaskStart($,J,Q){let Z=await this.adapter.getSession($);if(!Z)return;let W=s4($,J),j=e(),{messagesPath:f}=this.manifestStore.artifacts.subagentArtifactPaths(W,J);await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:W,parentSessionId:$,parentAgentId:"lead",agentId:J,prompt:Q||`Team task for ${J}`,startedAt:j,messagesPath:f})),this.manifestStore.initializeMessagesFile(W,f,j);let X=this.teamTaskQueueKey($,J),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(W),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,J,Q,Z,W,j){let f=this.teamTaskQueueKey($,J),X=this.teamTaskSessionsByAgent.get(f);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(f);if(!Y)return;let V=W?.messages??j,H=this.toPersistedMessages(V,W,j);if(H)await this.manifestStore.persistSessionMessages(Y,H);await this.applySubagentStatusBySessionId(Y,Q),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,J,Q,Z){let W=this.teamTaskQueueKey($,J),j=this.teamTaskSessionsByAgent.get(W)?.[0];if(!j)return;let f=Q.trim();if(!f)return;let X=Z?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(V-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${f}`:`[progress] ${f}`;if(this.teamTaskLastProgressLineBySession.get(j)===Y)return;this.teamTaskLastProgressLineBySession.set(j,Y)}async handleSubAgentStart($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;if(J.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let Z=this.toPersistedMessages(J.agentResult?.messages,J.agentResult);if(Z)await this.manifestStore.persistSessionMessages(Q,Z);let W=J.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??KN(GN(),"hooks.jsonl");AN(Q,`${JSON.stringify({ts:e(),...$})}
504
- `,"utf8")}}import{formatUserInputBlock as xN}from"@cline/shared";var UA={};w(UA,{toTeamProgressLifecycleEvent:()=>u8,sanitizeTeamName:()=>qY,reviveTeamStateDates:()=>P5,parseConfiguredAgentConfig:()=>fJ,loadConfiguredAgentConfigs:()=>m8,createWorkerReviewerTeam:()=>DA,createSpawnAgentTool:()=>A$,createDelegatedAgentConfigProvider:()=>H$,createDelegatedAgent:()=>B$,createConfiguredAgentTools:()=>v8,createAgentTeamsTools:()=>r$,createAgentTeam:()=>lW,buildTeamProgressSummary:()=>c8,buildDelegatedAgentConfig:()=>l$,buildConfiguredAgentToolName:()=>XJ,buildConfiguredAgentToolDescriptors:()=>YJ,bootstrapAgentTeams:()=>Q8,AgentTeamsRuntime:()=>T2,AgentTeam:()=>l8});import{existsSync as UN,readdirSync as RN,readFileSync as zN}from"node:fs";import{basename as XA,extname as LN,join as _N}from"node:path";import{resolveAgentConfigSearchPaths as ON}from"@cline/shared/storage";import VA from"yaml";import{z as P0}from"zod";var HA=P0.object({name:P0.string().trim().min(1),description:P0.string().trim().min(1),tools:P0.union([P0.string(),P0.array(P0.string())]).optional(),skills:P0.union([P0.string(),P0.array(P0.string())]).optional(),providerId:P0.string().trim().min(1).optional(),modelId:P0.string().trim().min(1).optional(),maxIterations:P0.number().int().positive().optional()});function TN($){let J=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!J)throw Error("Missing YAML frontmatter block in agent config file.");let Q=J[0].length,Z=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Z.lastIndex=Q;let W,j=Array.from($.matchAll(Z)).filter((f)=>f.index>=Q);for(let f of j){let X=f.index,Y=$.slice(Q,X);try{let V=VA.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;HA.parse(V);let H=$.slice(X+f[0].length);W={frontmatter:Y,body:H}}catch{}}if(W)return W;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function YA($){if($===void 0)return;let J=Array.isArray($)?$:$.split(",");return Array.from(new Set(J.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function MN($){return $.trim().toLowerCase()}function qN($){let J=LN($).toLowerCase();return J===".yml"||J===".yaml"}function fJ($,J={}){let{frontmatter:Q,body:Z}=TN($),W=VA.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Agent config frontmatter must be a YAML mapping.");let j=HA.parse(W),f=Z.trim();if(!f)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:YA(j.tools),skills:YA(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:f,path:J.path}}function m8($){let J=$.searchPaths??ON($.workspaceRoot),Q=new Map,Z=[];for(let j of J.filter(Boolean)){if(!UN(j))continue;let f;try{f=RN(j,{withFileTypes:!0})}catch(X){Z.push({path:j,error:X instanceof Error?X:Error(String(X))});continue}for(let X of f){if(!X.isFile()||!qN(X.name))continue;let Y=_N(j,X.name);try{let V=zN(Y,"utf8"),H=fJ(V,{path:Y}),B=MN(H.name);if(!Q.has(B))Q.set(B,H)}catch(V){Z.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(Q.values()).sort((j,f)=>(j.path?XA(j.path):j.name).localeCompare(f.path?XA(f.path):f.name)),errors:Z}}import{createTool as PN,zodToJsonSchema as NN}from"@cline/shared";import{z as BA}from"zod";var uW="subagent_",J9=64,wN=BA.object({prompt:BA.string().trim().min(1).describe("Task for the subagent to perform")});function SN($){let J="",Q=!0;for(let Z of $.trim().toLowerCase()){let W=Z.charCodeAt(0);if(!(W>=97&&W<=122||W>=48&&W<=57||Z==="_")||Z==="_"){if(!Q)J+="_",Q=!0;continue}J+=Z,Q=!1}return Q?J.slice(0,-1):J}function CN($){let J=2166136261;for(let Q=0;Q<$.length;Q++)J^=$.charCodeAt(Q),J=Math.imul(J,16777619);return(J>>>0).toString(36)}function XJ($){let J=SN($)||"agent",Q=CN($).slice(0,6),Z=`${uW}${J}`;if(Z.length<=J9)return Z;let W=J9-uW.length-Q.length-1,j=J.slice(0,Math.max(1,W));return`${uW}${j}_${Q}`.slice(0,J9)}function YJ($){let J=new Set,Q=[];for(let Z of[...$].sort((W,j)=>W.name.localeCompare(j.name))){let W=XJ(Z.name),j=W,f=2;while(J.has(j)){let X=`_${f++}`,Y=Math.max(1,J9-X.length);j=`${W.slice(0,Y)}${X}`}J.add(j),Q.push({toolName:j,config:Z})}return Q}function yN($,J){return{...$,providerId:J.providerId??$.providerId,modelId:J.modelId??$.modelId,maxIterations:J.maxIterations??$.maxIterations}}function v8($){return YJ($.agents).map(({toolName:J,config:Q})=>{return PN({name:J,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:NN(wN),execute:async(W,j)=>{let f=$.configProvider.getRuntimeConfig(),X=H$(yN(f,Q)),Y=$.createSubAgentTools?await $.createSubAgentTools(Q,W,j):[],V=B$({kind:"subagent",prompt:Q.systemPrompt,configProvider:X,tools:Y,maxIterations:Q.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=V.getAgentId(),B=V.getConversationId(),A=j.agentId,K={systemPrompt:Q.systemPrompt,task:W.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:B,parentAgentId:A,input:K})}catch{}try{let G=await V.run(W.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function R1(){return new Date().toISOString()}function AA($,J){if(J<=0)return 0;return Math.round($/J*100)}function EN($,J){let Q=new Set;for(let W of J)if(W.status==="reviewed")Q.add(`${W.outcomeId}:${W.section}`);let Z=new Set;for(let W of $){if(W.status==="finalized")continue;for(let j of W.requiredSections)if(!Q.has(`${W.id}:${j}`))Z.add(`${W.id}:${j}`)}return[...Z].sort((W,j)=>W.localeCompare(j))}function c8($,J){let Q={idle:0,running:0,stopped:0},Z={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},f={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let D of J.members)if(Q[D.status]+=1,D.role==="lead")X+=1;else Y+=1;let V=[],H=[],B=J.tasks.filter((D)=>D.status==="completed").length,A=new Map(J.tasks.map((D)=>[D.id,D]));for(let D of J.tasks){if(Z[D.status]+=1,D.status==="blocked"){V.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((F)=>{return A.get(F)?.status==="completed"}))H.push(D.id)}let K=[],G,R=0;for(let D of J.runs){if(W[D.status]+=1,D.status==="queued"||D.status==="running")K.push(D.id);let U=D.startedAt.getTime();if(U>=R)R=U,G=D.id}for(let D of J.outcomes)j[D.status]+=1;for(let D of J.outcomeFragments)f[D.status]+=1;return{teamName:$,updatedAt:R1(),members:{total:J.members.length,byStatus:Q,leadCount:X,teammateCount:Y},tasks:{total:J.tasks.length,byStatus:Z,blockedTaskIds:V,readyTaskIds:H,completionPct:AA(B,J.tasks.length)},runs:{total:J.runs.length,byStatus:W,activeRunIds:K,latestRunId:G},outcomes:{total:J.outcomes.length,byStatus:j,finalizedPct:AA(j.finalized,J.outcomes.length),missingRequiredSections:EN(J.outcomes,J.outcomeFragments)},fragments:{total:J.outcomeFragments.length,byStatus:f}}}function u8($){let{event:J}=$;switch(J.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.task.id,agentId:J.task.assignee??J.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:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.fragment.outcomeId,fragmentId:J.fragment.id,agentId:J.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.message.taskId,agentId:J.message.fromAgentId,message:J.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.entry.taskId,agentId:J.entry.agentId,message:J.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),agentId:J.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1()}}import{sanitizeFileName as bN,TeamMessageType as I}from"@cline/shared";import{nanoid as hN}from"nanoid";import{TeamMessageType as ru}from"@cline/shared";function dW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function KA($,J){return $?.status==="stopped"&&dW(J)}var kN=600000,GA="recovered_queued";function IN($){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.
502
+ `;if(QA(WA(Z),{recursive:!0}),ZA(Z,j,"utf8"),!this.messagesArtifactUploader)return;try{let f=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Z,contents:j,row:f})}catch(f){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:f})}}appendStaleSessionHookLog($,J,Q,Z,W){let f=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??HN(BN(),"hooks.jsonl");XN(f,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Z,sessionId:J,pid:Q,source:W})}
503
+ `,"utf8")}}import{appendFileSync as AN}from"node:fs";import{join as KN}from"node:path";import{resolveRootSessionId as jA}from"@cline/shared";import{ensureHookLogDir as GN}from"@cline/shared/storage";import{z as cW}from"zod";var FN="subagent",DN=cW.looseObject({task:cW.string().optional(),systemPrompt:cW.string().optional()});class $Q{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,J,Q,Z){this.adapter=$;this.manifestStore=J;this.toPersistedMessages=Q;this.heartbeatLogIntervalMs=Z}teamTaskQueueKey($,J){return`${$}::${J}`}activeTeamTaskSessionId($,J){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,J))?.at(-1)}buildSubsessionRow($,J){return{sessionId:J.sessionId,source:FN,pid:process.ppid,startedAt:J.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:J.parentSessionId,parentAgentId:J.parentAgentId,agentId:J.agentId,conversationId:J.conversationId??null,isSubagent:!0,prompt:J.prompt,metadata:J6({prompt:J.prompt}),hookPath:"",messagesPath:J.messagesPath,updatedAt:J.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let J=jA($.sessionContext);if(!J)return;let Q=DN.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:J,parentAgentId:$.agent_id,task:Q.success?Q.data.task:void 0,systemPrompt:Q.success?Q.data.systemPrompt:void 0})}async upsertSubagentSession($){let J=$.rootSessionId;if(!J)return;let Q=await this.adapter.getSession(J);if(!Q)return;let Z=Z8(J,$.agentId),W=await this.adapter.getSession(Z),j=e(),f=this.manifestStore.artifacts.subagentArtifactPaths(Z,$.agentId,this.activeTeamTaskSessionId(J,$.parentAgentId)),X=$.prompt??W?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(J,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!W)return await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:j,...f})),this.manifestStore.initializeMessagesFile(Z,f.messagesPath,j),Z;return await this.adapter.updateSession({sessionId:Z,setRunning:!0,parentSessionId:J,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:W.prompt??X??null,metadata:J6({metadata:W.metadata??void 0,prompt:W.prompt??X??null}),expectedStatusLock:W.statusLock}),Z}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let J=jA($.sessionContext);if(!J)return;if($.hookName==="session_shutdown"){let Q=Z8(J,$.agent_id);return await this.adapter.getSession(Q)?Q:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:J})}async applySubagentStatus($,J){await this.applySubagentStatusBySessionId($,t4(J))}async applySubagentStatusBySessionId($,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=j0(J)?null:e(),W=j0(J)?null:J==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:J,endedAt:Z,exitCode:W,expectedStatusLock:Q.statusLock})}async applyStatusToRunningChildSessions($,J){if(!$)return;let Q=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Z of Q)await this.applySubagentStatusBySessionId(Z.sessionId,J)}async onTeamTaskStart($,J,Q){let Z=await this.adapter.getSession($);if(!Z)return;let W=s4($,J),j=e(),{messagesPath:f}=this.manifestStore.artifacts.subagentArtifactPaths(W,J);await this.adapter.upsertSession(this.buildSubsessionRow(Z,{sessionId:W,parentSessionId:$,parentAgentId:"lead",agentId:J,prompt:Q||`Team task for ${J}`,startedAt:j,messagesPath:f})),this.manifestStore.initializeMessagesFile(W,f,j);let X=this.teamTaskQueueKey($,J),Y=this.teamTaskSessionsByAgent.get(X)??[];Y.push(W),this.teamTaskSessionsByAgent.set(X,Y)}async onTeamTaskEnd($,J,Q,Z,W,j){let f=this.teamTaskQueueKey($,J),X=this.teamTaskSessionsByAgent.get(f);if(!X||X.length===0)return;let Y=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(f);if(!Y)return;let V=W?.messages??j,H=this.toPersistedMessages(V,W,j);if(H)await this.manifestStore.persistSessionMessages(Y,H);await this.applySubagentStatusBySessionId(Y,Q),this.teamTaskLastHeartbeatBySession.delete(Y),this.teamTaskLastProgressLineBySession.delete(Y)}async onTeamTaskProgress($,J,Q,Z){let W=this.teamTaskQueueKey($,J),j=this.teamTaskSessionsByAgent.get(W)?.[0];if(!j)return;let f=Q.trim();if(!f)return;let X=Z?.kind??"progress";if(X==="heartbeat"){let V=Date.now(),H=this.teamTaskLastHeartbeatBySession.get(j)??0;if(V-H<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(j,V)}let Y=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${f}`:`[progress] ${f}`;if(this.teamTaskLastProgressLineBySession.get(j)===Y)return;this.teamTaskLastProgressLineBySession.set(j,Y)}async handleSubAgentStart($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;await this.applySubagentStatusBySessionId(Q,"running")}async handleSubAgentEnd($,J){let Q=await this.upsertSubagentSession({agentId:J.subAgentId,parentAgentId:J.parentAgentId,conversationId:J.conversationId,prompt:J.input.task,rootSessionId:$});if(!Q)return;if(J.error){await this.applySubagentStatusBySessionId(Q,"failed");return}let Z=this.toPersistedMessages(J.agentResult?.messages,J.agentResult);if(Z)await this.manifestStore.persistSessionMessages(Q,Z);let W=J.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(Q,W==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let Q=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??KN(GN(),"hooks.jsonl");AN(Q,`${JSON.stringify({ts:e(),...$})}
504
+ `,"utf8")}}import{formatUserInputBlock as xN}from"@cline/shared";var DA={};w(DA,{toTeamProgressLifecycleEvent:()=>u8,sanitizeTeamName:()=>MY,reviveTeamStateDates:()=>P5,parseConfiguredAgentConfig:()=>fJ,loadConfiguredAgentConfigs:()=>m8,createWorkerReviewerTeam:()=>FA,createSpawnAgentTool:()=>A$,createDelegatedAgentConfigProvider:()=>H$,createDelegatedAgent:()=>B$,createConfiguredAgentTools:()=>v8,createAgentTeamsTools:()=>r$,createAgentTeam:()=>lW,buildTeamProgressSummary:()=>c8,buildDelegatedAgentConfig:()=>l$,buildConfiguredAgentToolName:()=>XJ,buildConfiguredAgentToolDescriptors:()=>YJ,bootstrapAgentTeams:()=>Q8,AgentTeamsRuntime:()=>T2,AgentTeam:()=>l8});import{existsSync as UN,readdirSync as RN,readFileSync as zN}from"node:fs";import{basename as fA,extname as LN,join as _N}from"node:path";import{resolveAgentConfigSearchPaths as ON}from"@cline/shared/storage";import YA from"yaml";import{z as P0}from"zod";var VA=P0.object({name:P0.string().trim().min(1),description:P0.string().trim().min(1),tools:P0.union([P0.string(),P0.array(P0.string())]).optional(),skills:P0.union([P0.string(),P0.array(P0.string())]).optional(),providerId:P0.string().trim().min(1).optional(),modelId:P0.string().trim().min(1).optional(),maxIterations:P0.number().int().positive().optional()});function TN($){let J=$.match(/^(---)[^\S\r\n]*(?:\r?\n|$)/);if(!J)throw Error("Missing YAML frontmatter block in agent config file.");let Q=J[0].length,Z=/^---[^\S\r\n]*(?:\r?\n|$)/gm;Z.lastIndex=Q;let W,j=Array.from($.matchAll(Z)).filter((f)=>f.index>=Q);for(let f of j){let X=f.index,Y=$.slice(Q,X);try{let V=YA.parse(Y);if(!V||typeof V!=="object"||Array.isArray(V))continue;VA.parse(V);let H=$.slice(X+f[0].length);W={frontmatter:Y,body:H}}catch{}}if(W)return W;throw Error("Missing closing YAML frontmatter delimiter in agent config file.")}function XA($){if($===void 0)return;let J=Array.isArray($)?$:$.split(",");return Array.from(new Set(J.map((Q)=>Q.trim()).filter((Q)=>Q.length>0)))}function MN($){return $.trim().toLowerCase()}function qN($){let J=LN($).toLowerCase();return J===".yml"||J===".yaml"}function fJ($,J={}){let{frontmatter:Q,body:Z}=TN($),W=YA.parse(Q);if(!W||typeof W!=="object"||Array.isArray(W))throw Error("Agent config frontmatter must be a YAML mapping.");let j=VA.parse(W),f=Z.trim();if(!f)throw Error("Missing system prompt body in agent config file.");return{name:j.name,description:j.description,tools:XA(j.tools),skills:XA(j.skills),providerId:j.providerId,modelId:j.modelId,maxIterations:j.maxIterations,systemPrompt:f,path:J.path}}function m8($){let J=$.searchPaths??ON($.workspaceRoot),Q=new Map,Z=[];for(let j of J.filter(Boolean)){if(!UN(j))continue;let f;try{f=RN(j,{withFileTypes:!0})}catch(X){Z.push({path:j,error:X instanceof Error?X:Error(String(X))});continue}for(let X of f){if(!X.isFile()||!qN(X.name))continue;let Y=_N(j,X.name);try{let V=zN(Y,"utf8"),H=fJ(V,{path:Y}),B=MN(H.name);if(!Q.has(B))Q.set(B,H)}catch(V){Z.push({path:Y,error:V instanceof Error?V:Error(String(V))})}}}return{configs:Array.from(Q.values()).sort((j,f)=>(j.path?fA(j.path):j.name).localeCompare(f.path?fA(f.path):f.name)),errors:Z}}import{createTool as PN,zodToJsonSchema as NN}from"@cline/shared";import{z as HA}from"zod";var uW="subagent_",JQ=64,wN=HA.object({prompt:HA.string().trim().min(1).describe("Task for the subagent to perform")});function SN($){let J="",Q=!0;for(let Z of $.trim().toLowerCase()){let W=Z.charCodeAt(0);if(!(W>=97&&W<=122||W>=48&&W<=57||Z==="_")||Z==="_"){if(!Q)J+="_",Q=!0;continue}J+=Z,Q=!1}return Q?J.slice(0,-1):J}function CN($){let J=2166136261;for(let Q=0;Q<$.length;Q++)J^=$.charCodeAt(Q),J=Math.imul(J,16777619);return(J>>>0).toString(36)}function XJ($){let J=SN($)||"agent",Q=CN($).slice(0,6),Z=`${uW}${J}`;if(Z.length<=JQ)return Z;let W=JQ-uW.length-Q.length-1,j=J.slice(0,Math.max(1,W));return`${uW}${j}_${Q}`.slice(0,JQ)}function YJ($){let J=new Set,Q=[];for(let Z of[...$].sort((W,j)=>W.name.localeCompare(j.name))){let W=XJ(Z.name),j=W,f=2;while(J.has(j)){let X=`_${f++}`,Y=Math.max(1,JQ-X.length);j=`${W.slice(0,Y)}${X}`}J.add(j),Q.push({toolName:j,config:Z})}return Q}function yN($,J){return{...$,providerId:J.providerId??$.providerId,modelId:J.modelId??$.modelId,maxIterations:J.maxIterations??$.maxIterations}}function v8($){return YJ($.agents).map(({toolName:J,config:Q})=>{return PN({name:J,description:`Use the "${Q.name}" subagent: ${Q.description}`,inputSchema:NN(wN),execute:async(W,j)=>{let f=$.configProvider.getRuntimeConfig(),X=H$(yN(f,Q)),Y=$.createSubAgentTools?await $.createSubAgentTools(Q,W,j):[],V=B$({kind:"subagent",prompt:Q.systemPrompt,configProvider:X,tools:Y,maxIterations:Q.maxIterations,parentAgentId:j.agentId,abortSignal:j.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),H=V.getAgentId(),B=V.getConversationId(),A=j.agentId,K={systemPrompt:Q.systemPrompt,task:W.prompt};if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:H,conversationId:B,parentAgentId:A,input:K})}catch{}try{let G=await V.run(W.prompt),R={text:G.text,iterations:G.iterations,finishReason:G.finishReason,usage:{inputTokens:G.usage.inputTokens,outputTokens:G.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,result:R,agentResult:G})}catch{}return R}catch(G){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:H,conversationId:B,parentAgentId:A,input:K,error:G instanceof Error?G:Error(String(G))})}catch{}throw G}},timeoutMs:300000,retryable:!1})})}function R1(){return new Date().toISOString()}function BA($,J){if(J<=0)return 0;return Math.round($/J*100)}function EN($,J){let Q=new Set;for(let W of J)if(W.status==="reviewed")Q.add(`${W.outcomeId}:${W.section}`);let Z=new Set;for(let W of $){if(W.status==="finalized")continue;for(let j of W.requiredSections)if(!Q.has(`${W.id}:${j}`))Z.add(`${W.id}:${j}`)}return[...Z].sort((W,j)=>W.localeCompare(j))}function c8($,J){let Q={idle:0,running:0,stopped:0},Z={pending:0,in_progress:0,blocked:0,completed:0},W={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},j={draft:0,in_review:0,finalized:0},f={draft:0,reviewed:0,rejected:0},X=0,Y=0;for(let D of J.members)if(Q[D.status]+=1,D.role==="lead")X+=1;else Y+=1;let V=[],H=[],B=J.tasks.filter((D)=>D.status==="completed").length,A=new Map(J.tasks.map((D)=>[D.id,D]));for(let D of J.tasks){if(Z[D.status]+=1,D.status==="blocked"){V.push(D.id);continue}if(D.status!=="pending")continue;if(D.dependsOn.every((F)=>{return A.get(F)?.status==="completed"}))H.push(D.id)}let K=[],G,R=0;for(let D of J.runs){if(W[D.status]+=1,D.status==="queued"||D.status==="running")K.push(D.id);let U=D.startedAt.getTime();if(U>=R)R=U,G=D.id}for(let D of J.outcomes)j[D.status]+=1;for(let D of J.outcomeFragments)f[D.status]+=1;return{teamName:$,updatedAt:R1(),members:{total:J.members.length,byStatus:Q,leadCount:X,teammateCount:Y},tasks:{total:J.tasks.length,byStatus:Z,blockedTaskIds:V,readyTaskIds:H,completionPct:BA(B,J.tasks.length)},runs:{total:J.runs.length,byStatus:W,activeRunIds:K,latestRunId:G},outcomes:{total:J.outcomes.length,byStatus:j,finalizedPct:BA(j.finalized,J.outcomes.length),missingRequiredSections:EN(J.outcomes,J.outcomeFragments)},fragments:{total:J.outcomeFragments.length,byStatus:f}}}function u8($){let{event:J}=$;switch(J.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.task.id,agentId:J.task.assignee??J.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:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),runId:J.run.id,taskId:J.run.taskId,agentId:J.run.agentId,message:J.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),outcomeId:J.fragment.outcomeId,fragmentId:J.fragment.id,agentId:J.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.message.taskId,agentId:J.message.fromAgentId,message:J.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),taskId:J.entry.taskId,agentId:J.entry.agentId,message:J.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1(),agentId:J.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:J.type,ts:R1()}}import{sanitizeFileName as bN,TeamMessageType as I}from"@cline/shared";import{nanoid as hN}from"nanoid";import{TeamMessageType as ru}from"@cline/shared";function dW($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function AA($,J){return $?.status==="stopped"&&dW(J)}var kN=600000,KA="recovered_queued";function IN($){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.
505
505
 
506
506
  ${$.message}`}class l8{agents=new Map;configs=new Map;onTeamEvent;constructor($,J){if(this.onTeamEvent=J,$)for(let[Q,Z]of Object.entries($))this.addAgent(Q,Z)}addAgent($,J){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let Q={...J,onEvent:(W)=>{J.onEvent?.(W),this.emitEvent({type:I.AgentEvent,agentId:$,event:W})}},Z=new V$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);this.agents.set($,Z),this.configs.set($,J)}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($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let Z=await Q.run(J);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async continueTo($,J){let Q=this.agents.get($);if(!Q)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let Z=await Q.continue(J);return this.emitEvent({type:I.TaskEnd,agentId:$,result:Z}),Z}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));throw this.emitEvent({type:I.TaskEnd,agentId:$,error:W,messages:Q.getMessages()}),Z}}async runParallel($){let J=$.map(async(Q)=>{let Z=this.agents.get(Q.agentId);if(!Z)return{agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata};this.emitEvent({type:I.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);return this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,result:W}),{agentId:Q.agentId,result:W,metadata:Q.metadata}}catch(W){let j=W instanceof Error?W:Error(String(W));return this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),{agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata}}});return Promise.all(J)}async runSequential($){let J=[];for(let Q of $){let Z=this.agents.get(Q.agentId);if(!Z){J.push({agentId:Q.agentId,result:void 0,error:Error(`Agent "${Q.agentId}" not found in team`),metadata:Q.metadata});continue}this.emitEvent({type:I.TaskStart,agentId:Q.agentId,message:Q.message});try{let W=await Z.run(Q.message);this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,result:W}),J.push({agentId:Q.agentId,result:W,metadata:Q.metadata})}catch(W){let j=W instanceof Error?W:Error(String(W));this.emitEvent({type:I.TaskEnd,agentId:Q.agentId,error:j,messages:Z.getMessages()}),J.push({agentId:Q.agentId,result:void 0,error:j,metadata:Q.metadata})}}return J}async runPipeline($,J,Q){let Z=[],W=J;for(let j of $){let f=this.agents.get(j);if(!f){Z.push({agentId:j,result:void 0,error:Error(`Agent "${j}" not found in team`)});break}this.emitEvent({type:I.TaskStart,agentId:j,message:W});try{let X=await f.run(W);this.emitEvent({type:I.TaskEnd,agentId:j,result:X}),Z.push({agentId:j,result:X});let Y=$.indexOf(j)+1;if(Y<$.length){let V=$[Y];W=Q?Q(X,V):`Previous agent output:
507
507
  ${X.text}
508
508
 
509
- Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:I.TaskEnd,agentId:j,error:Y,messages:f.getMessages()}),Z.push({agentId:j,result:void 0,error:Y});break}}return Z}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 lW($,J){return new l8($,J)}function DA($){let J=lW({worker:$.worker,reviewer:$.reviewer}),Q=J;return Q.doAndReview=async(Z)=>{let W=await J.routeTo("worker",Z),j=await J.routeTo("reviewer",`Please review this work:
509
+ Please continue from here.`}}catch(X){let Y=X instanceof Error?X:Error(String(X));this.emitEvent({type:I.TaskEnd,agentId:j,error:Y,messages:f.getMessages()}),Z.push({agentId:j,result:void 0,error:Y});break}}return Z}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 lW($,J){return new l8($,J)}function FA($){let J=lW({worker:$.worker,reviewer:$.reviewer}),Q=J;return Q.doAndReview=async(Z)=>{let W=await J.routeTo("worker",Z),j=await J.routeTo("reviewer",`Please review this work:
510
510
 
511
511
  ${W.text}`);return{workerResult:W,reviewResult:j}},Q}class T2{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_${bN(hN(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 J=$.leadAgentId??"lead";this.members.set(J,{agentId:J,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((J)=>{let Q=this.getUnresolvedDependencies(J);return{...J,blockedBy:Q,isReady:J.status==="pending"&&!J.assignee&&Q.length===0}}).filter((J)=>{if($?.status&&J.status!==$.status)return!1;if($?.assignee&&J.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,J){let Q=J?.unreadOnly??!0,Z=J?.markRead??!0,W=J?.limit,j=this.mailbox.filter((X)=>X.toAgentId===$&&(!Q||!X.readAt)),f=typeof W==="number"&&W>0?j.slice(Math.max(0,j.length-W)):j;if(Z){let X=new Date;for(let Y of f)if(!Y.readAt)Y.readAt=X}return f.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let Q of this.tasks.values())$[Q.status]++;let J={draft:0,in_review:0,finalized:0};for(let Q of this.outcomes.values())J[Q.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((Q)=>({agentId:Q.agentId,role:Q.role,description:Q.description,status:Q.status})),taskCounts:$,unreadMessages:this.mailbox.filter((Q)=>!Q.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").length,outcomeCounts:J}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let Q of $.tasks)this.tasks.set(Q.id,{...Q});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((Q)=>({...Q}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((Q)=>({...Q}))),this.runs.clear();for(let Q of $.runs??[])this.runs.set(Q.id,{...Q});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((Q)=>Q.status==="queued").map((Q)=>Q.id)),this.outcomes.clear();for(let Q of $.outcomes??[])this.outcomes.set(Q.id,{...Q});this.outcomeFragments.clear();for(let Q of $.outcomeFragments??[])this.outcomeFragments.set(Q.id,{...Q});let J=Array.from(this.members.values()).filter((Q)=>Q.role==="lead");this.members.clear();for(let Q of J)this.members.set(Q.agentId,{...Q,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let Q of $.members){if(Q.role!=="teammate")continue;this.members.set(Q.agentId,{agentId:Q.agentId,role:"teammate",description:Q.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,d8($.tasks.map((Q)=>Q.id),"task_")),this.messageCounter=Math.max(this.messageCounter,d8($.mailbox.map((Q)=>Q.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,d8($.missionLog.map((Q)=>Q.id),"log_")),this.runCounter=Math.max(this.runCounter,d8(($.runs??[]).map((Q)=>Q.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,d8(($.outcomes??[]).map((Q)=>Q.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,d8(($.outcomeFragments??[]).map((Q)=>Q.id),"frag_"))}isTeammateActive($){let J=this.members.get($);return!!J&&J.role==="teammate"&&!!J.agent}spawnTeammate({agentId:$,config:J}){let Q=this.members.get($);if(Q&&Q.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(Q&&Q.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Z={...J,apiTimeoutMs:kN,consumePendingUserMessage:()=>{let f=this.members.get($);if(!f||!f.pendingSteerMessage)return;let X=f.pendingSteerMessage;return f.pendingSteerMessage=void 0,X},onEvent:(f)=>{J.onEvent?.(f),this.emitEvent({type:I.AgentEvent,agentId:$,event:f}),this.trackMeaningfulEvent($,f)}},W=new V$(Z);if(Z.onEvent)W.subscribeEvents(Z.onEvent);let j={agentId:$,role:"teammate",description:J.role,status:"idle",agent:W,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,j),this.emitEvent({type:I.TeammateSpawned,agentId:$,role:J.role,teammate:{rolePrompt:J.systemPrompt,modelId:J.modelId,maxIterations:J.maxIterations,runtimeAgentId:W.getAgentId(),conversationId:W.getConversationId(),parentAgentId:null}}),{agentId:j.agentId,role:j.role,description:j.description,status:j.status}}shutdownTeammate($,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{Q.agent?.abort()}catch(Z){if(!dW(Z))throw Z}Q.status="stopped",this.emitEvent({type:I.TeammateShutdown,agentId:$,reason:J})}updateTeammateConnections($){for(let J of this.members.values()){if(J.role!=="teammate"||!J.agent)continue;J.agent.updateConnection($)}}createTask($){let J=`task_${String(++this.taskCounter).padStart(4,"0")}`,Q=new Date,Z={id:J,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:Q,updatedAt:Q,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(J,Z),this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),{...Z}}claimTask($,J){let Q=this.requireTask($);return this.assertDependenciesResolved(Q),Q.status="in_progress",Q.assignee=J,Q.updatedAt=new Date,this.emitEvent({type:I.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:J,taskId:$,kind:"progress",summary:`Claimed task "${Q.title}"`}),{...Q}}blockTask($,J,Q){let Z=this.requireTask($);return Z.status="blocked",Z.updatedAt=new Date,Z.summary=Q,this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"blocked",summary:Q}),{...Z}}completeTask($,J,Q){let Z=this.requireTask($);if(Z.status="completed",Z.updatedAt=new Date,Z.summary=Q,!Z.assignee)Z.assignee=J;return this.emitEvent({type:I.TeamTaskUpdated,task:{...Z}}),this.appendMissionLog({agentId:J,taskId:$,kind:"done",summary:Q}),{...Z}}async routeToTeammate($,J,Q){let Z=this.members.get($);if(!Z||Z.role!=="teammate"||!Z.agent)throw Error(`Teammate "${$}" was not found`);if(!Z.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Z.runningCount++,Z.status="running",this.emitEvent({type:I.TaskStart,agentId:$,message:J});try{let W=this.listMailbox($,{unreadOnly:!0,markRead:!0}),j=W.length>0?`${this.buildMailboxNotification(W)}
512
512
 
513
- ${J}`:J,f=Q?.continueConversation?await Z.agent.continue(j):await Z.agent.run(j);return this.emitEvent({type:I.TaskEnd,agentId:$,result:f}),this.recordProgressStep($,`Completed a delegated run (${f.iterations} iterations)`,Q?.taskId,!0),f}catch(W){let j=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:I.TaskEnd,agentId:$,error:j,messages:Z.agent.getMessages()}),!KA(Z,j))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:j.message});throw j}finally{if(Z.runningCount--,Z.runningCount<=0&&this.members.get($)?.status!=="stopped")Z.status="idle"}}startTeammateRun($,J,Q){let Z=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:Z,agentId:$,taskId:Q?.taskId,status:"queued",message:J,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Z,W),this.runQueue.push(Z),this.emitEvent({type:I.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let J=this.selectNextDispatchableQueuedRun();$=J.nextDelayedAttemptAt;let Q=J.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[Z]=this.runQueue.splice(Q,1),W=Z?this.runs.get(Z):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,J=Number.NEGATIVE_INFINITY,Q,Z=Date.now();for(let W=0;W<this.runQueue.length;W++){let j=this.runs.get(this.runQueue[W]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Z){if(!Q||j.nextAttemptAt<Q)Q=j.nextAttemptAt;continue}if(j.priority>J)J=j.priority,$=W}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let J=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},J)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let J of this.runs.values())if(J.status==="running")$++;return $}async executeQueuedRun($){let J=$.currentActivity===GA;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:I.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Z=J?IN($):$.message,W=await this.routeToTeammate($.agentId,Z,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=W,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:I.RunCompleted,run:{...$}})}catch(Z){let W=Z instanceof Error?Z.message:String(Z??"Unknown error");$.error=W,$.endedAt=new Date;let j=this.members.get($.agentId);if(KA(j,Z))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:I.RunCancelled,run:{...$},reason:W});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:I.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let J=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!J&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let J=this.runs.get($);return J?{...J}:void 0}async awaitRun($,J=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await FA(J);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((J)=>["queued","running"].includes(J.status)))await FA($);return this.listRuns()}cancelRun($,J){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=J,Q.endedAt=new Date,Q.currentActivity="cancelled";let Z=this.runQueue.indexOf($);if(Z>=0)this.runQueue.splice(Z,1);return this.emitEvent({type:I.RunCancelled,run:{...Q},reason:J}),{...Q}}recoverActiveRuns($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let Z=this.members.get(Q.agentId);if(!Z||Z.role!=="teammate"||!Z.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:Q.error});continue}let W=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=W,Q.lastProgressAt=W,Q.lastProgressMessage=$,Q.currentActivity=GA,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);J.push({...Q}),this.emitEvent({type:I.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),J}markStaleRunsInterrupted($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",J.push({...Q}),this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),J}sendMessage($,J,Q,Z,W){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(J);if(!j)throw Error(`Unknown recipient "${J}"`);let f={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:J,subject:Q,body:Z,taskId:W,sentAt:new Date};if(this.mailbox.push(f),this.emitEvent({type:I.TeamMessage,message:{...f}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...f}}broadcast($,J,Q,Z){let W=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;W.push(this.sendMessage($,j.agentId,J,Q,Z?.taskId))}return W}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let J={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(J);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:I.TeamMissionLog,entry:{...J}}),{...J}}createOutcome($){let J={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(J.id,J),this.emitEvent({type:I.OutcomeCreated,outcome:{...J}}),{...J}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let J=this.outcomes.get($.outcomeId);if(!J)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!J.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Q.id,Q),J.status==="draft")J.status="in_review";return this.emitEvent({type:I.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let J=this.outcomeFragments.get($.fragmentId);if(!J)throw Error(`Fragment "${$.fragmentId}" was not found`);return J.status=$.approved?"reviewed":"rejected",J.reviewedBy=$.reviewedBy,J.reviewedAt=new Date,this.emitEvent({type:I.OutcomeFragmentReviewed,fragment:{...J}}),{...J}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((J)=>J.outcomeId===$).map((J)=>({...J}))}finalizeOutcome($){let J=this.outcomes.get($);if(!J)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let Z of J.requiredSections)if(!Q.some((j)=>j.section===Z&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Z}" is missing a reviewed fragment.`);return J.status="finalized",J.finalizedAt=new Date,this.emitEvent({type:I.OutcomeFinalized,outcome:{...J}}),{...J}}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(J){if(!dW(J))throw J}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[$,J]of this.members.entries())if(J.role==="teammate")this.members.delete($)}requireTask($){let J=this.tasks.get($);if(!J)throw Error(`Task "${$}" was not found`);return J}assertDependenciesResolved($){let J=this.getUnresolvedDependencies($);if(J.length>0)throw Error(`Task "${$.id}" is blocked by "${J[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((J)=>{let Q=this.tasks.get(J);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,J){if(this.recordRunActivityFromAgentEvent($,J),J.type==="iteration_end"&&J.hadToolCalls){this.recordProgressStep($,`Completed iteration ${J.iteration} with ${J.toolCallCount} tool call(s)`);return}if(J.type==="content_end"&&J.contentType==="tool"&&!J.error){this.recordProgressStep($,`Finished tool "${J.toolName??"unknown"}"`);return}if(J.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${J.iterations} iterations)`});return}if(J.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:J.error.message})}recordRunActivityFromAgentEvent($,J){let Q;switch(J.type){case"iteration_start":Q=`iteration_${J.iteration}_started`;break;case"content_start":if(J.contentType==="tool")Q=`running_tool_${J.toolName??"unknown"}`;break;case"content_end":if(J.contentType==="tool")Q=J.error?this.formatProgressErrorActivity(`tool_${J.toolName??"unknown"}_error`,J.error):`finished_tool_${J.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",J.error.message);break;default:break}if(!Q)return;for(let Z of this.runs.values()){if(Z.agentId!==$||Z.status!=="running")continue;this.recordRunProgress(Z,Q)}}recordRunProgress($,J){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=J,$.currentActivity=J,this.emitEvent({type:I.RunProgress,run:{...$},message:J})}formatProgressErrorActivity($,J){let Q=J.replace(/\s+/g," ").trim();if(Q.length===0)return $;let Z=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${Z}`}recordProgressStep($,J,Q,Z=!1){this.missionStepCounter++;let W=this.members.get($);if(!W)return;let j=this.missionStepCounter-W.lastMissionStep,f=Date.now()-W.lastMissionAt;if(!Z&&j<this.missionLogIntervalSteps&&f<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:J})}buildMailboxNotification($){if($.length===0)return"";let J=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)J.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),J.push(Q.body);return J.push("---"),J.join(`
514
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function FA($){return new Promise((J)=>setTimeout(J,$))}function d8($,J){let Q=0;for(let Z of $){if(!Z.startsWith(J))continue;let W=Number.parseInt(Z.slice(J.length),10);if(Number.isFinite(W))Q=Math.max(Q,W)}return Q}function pW($,J){switch(J.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(J.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(J.type==="run_failed")Q=J.run.error;else if(J.type==="run_cancelled"||J.type==="run_interrupted")Q=J.run.error??J.reason;$.activeTeamRunIds.delete(J.run.id),$.pendingTeamRunUpdates.push({runId:J.run.id,agentId:J.run.agentId,taskId:J.run.taskId,status:J.type.replace("run_",""),error:Q,iterations:J.run.result?.iterations}),Q9($);break}default:break}}async function rW($,J,Q){switch(J.type){case"run_progress":await Q("onTeamTaskProgress",$,J.run.agentId,J.message,{kind:J.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(J.event.type==="content_start"&&J.event.contentType==="text"&&typeof J.event.text==="string"){let Z=J.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Z)await Q("onTeamTaskProgress",$,J.agentId,Z,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,J.agentId,J.message);break;case"task_end":{if(J.error)await Q("onTeamTaskEnd",$,J.agentId,"failed",`[error] ${J.error.message}`,void 0,J.messages);else if(J.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,J.agentId,"cancelled","[done] aborted",J.result,J.result.messages);else await Q("onTeamTaskEnd",$,J.agentId,"completed",`[done] ${J.result?.finishReason??"completed"}`,J.result,J.result?.messages);break}default:break}}function iW($,J,Q,Z){if(!$.runtime.teamRuntime)return;let W=$.runtime.teamRuntime.getTeamName();Z({type:"team_progress",payload:{sessionId:J,teamName:W,lifecycle:u8({teamName:W,sessionId:J,event:Q}),summary:c8(W,$.runtime.teamRuntime.exportState())}})}function VJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function nW($,J){if($.aborting)return!1;if(!(J==="completed"||J==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&VJ($)}function Q9($){let J=$.teamRunWaiters.splice(0);for(let Q of J)Q()}async function aW($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let J=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,J}if($.activeTeamRunIds.size===0)return[];await new Promise((J)=>{$.teamRunWaiters.push(J)})}}function sW($,J){let Q=J.map((j)=>{let f=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)f.push(` task=${j.taskId}`);if(typeof j.iterations==="number")f.push(` iterations=${j.iterations}`);if(j.error)f.push(` error=${j.error}`);return f.join("")}),Z=$.activeTeamRunIds.size,W=Z>0?`There are still ${Z} 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 HJ(`System-delivered teammate async run updates:
513
+ ${J}`:J,f=Q?.continueConversation?await Z.agent.continue(j):await Z.agent.run(j);return this.emitEvent({type:I.TaskEnd,agentId:$,result:f}),this.recordProgressStep($,`Completed a delegated run (${f.iterations} iterations)`,Q?.taskId,!0),f}catch(W){let j=W instanceof Error?W:Error(String(W));if(this.emitEvent({type:I.TaskEnd,agentId:$,error:j,messages:Z.agent.getMessages()}),!AA(Z,j))this.appendMissionLog({agentId:$,taskId:Q?.taskId,kind:"error",summary:j.message});throw j}finally{if(Z.runningCount--,Z.runningCount<=0&&this.members.get($)?.status!=="stopped")Z.status="idle"}}startTeammateRun($,J,Q){let Z=`run_${String(++this.runCounter).padStart(5,"0")}`,W={id:Z,agentId:$,taskId:Q?.taskId,status:"queued",message:J,priority:Q?.priority??0,retryCount:0,maxRetries:Math.max(0,Q?.maxRetries??0),continueConversation:Q?.continueConversation,startedAt:new Date(0),leaseOwner:Q?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Z,W),this.runQueue.push(Z),this.emitEvent({type:I.RunQueued,run:{...W}}),this.dispatchQueuedRuns(),{...W}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let J=this.selectNextDispatchableQueuedRun();$=J.nextDelayedAttemptAt;let Q=J.index;if(Q<0){this.scheduleQueuedRunDispatch($);return}let[Z]=this.runQueue.splice(Q,1),W=Z?this.runs.get(Z):void 0;if(!W||W.status!=="queued")continue;this.executeQueuedRun(W)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,J=Number.NEGATIVE_INFINITY,Q,Z=Date.now();for(let W=0;W<this.runQueue.length;W++){let j=this.runs.get(this.runQueue[W]);if(!j||j.status!=="queued")continue;if(j.nextAttemptAt&&j.nextAttemptAt.getTime()>Z){if(!Q||j.nextAttemptAt<Q)Q=j.nextAttemptAt;continue}if(j.priority>J)J=j.priority,$=W}return{index:$,nextDelayedAttemptAt:Q}}scheduleQueuedRunDispatch($){if(!$)return;let J=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},J)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let J of this.runs.values())if(J.status==="running")$++;return $}async executeQueuedRun($){let J=$.currentActivity===KA;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:I.RunStarted,run:{...$}});let Q=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Z=J?IN($):$.message,W=await this.routeToTeammate($.agentId,Z,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=W,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:I.RunCompleted,run:{...$}})}catch(Z){let W=Z instanceof Error?Z.message:String(Z??"Unknown error");$.error=W,$.endedAt=new Date;let j=this.members.get($.agentId);if(AA(j,Z))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:I.RunCancelled,run:{...$},reason:W});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:I.RunFailed,run:{...$}})}finally{clearInterval(Q),this.dispatchQueuedRuns()}}listRuns($){let J=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((Q)=>{if(!J&&!["running","queued"].includes(Q.status))return!1;if($?.status&&Q.status!==$.status)return!1;if($?.agentId&&Q.agentId!==$.agentId)return!1;return!0}).map((Q)=>({...Q}))}getRun($){let J=this.runs.get($);return J?{...J}:void 0}async awaitRun($,J=250){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);while(Q.status==="queued"||Q.status==="running")await GA(J);return{...Q}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((J)=>["queued","running"].includes(J.status)))await GA($);return this.listRuns()}cancelRun($,J){let Q=this.runs.get($);if(!Q)throw Error(`Run "${$}" was not found`);if(Q.status==="completed"||Q.status==="failed")return{...Q};Q.status="cancelled",Q.error=J,Q.endedAt=new Date,Q.currentActivity="cancelled";let Z=this.runQueue.indexOf($);if(Z>=0)this.runQueue.splice(Z,1);return this.emitEvent({type:I.RunCancelled,run:{...Q},reason:J}),{...Q}}recoverActiveRuns($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;let Z=this.members.get(Q.agentId);if(!Z||Z.role!=="teammate"||!Z.agent){Q.status="interrupted",Q.error="teammate_unavailable_after_recovery",Q.endedAt=new Date,Q.currentActivity="interrupted",this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:Q.error});continue}let W=new Date;if(Q.status="queued",Q.error=void 0,Q.endedAt=void 0,Q.heartbeatAt=W,Q.lastProgressAt=W,Q.lastProgressMessage=$,Q.currentActivity=KA,!this.runQueue.includes(Q.id))this.runQueue.push(Q.id);J.push({...Q}),this.emitEvent({type:I.RunQueued,run:{...Q}})}return this.dispatchQueuedRuns(),J}markStaleRunsInterrupted($="runtime_recovered"){let J=[];for(let Q of this.runs.values()){if(!["queued","running"].includes(Q.status))continue;Q.status="interrupted",Q.error=$,Q.endedAt=new Date,Q.currentActivity="interrupted",J.push({...Q}),this.emitEvent({type:I.RunInterrupted,run:{...Q},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),J}sendMessage($,J,Q,Z,W){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let j=this.members.get(J);if(!j)throw Error(`Unknown recipient "${J}"`);let f={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:J,subject:Q,body:Z,taskId:W,sentAt:new Date};if(this.mailbox.push(f),this.emitEvent({type:I.TeamMessage,message:{...f}}),j.role==="teammate"&&j.runningCount>0&&j.agent)j.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${Q}". Use the team_read_mailbox tool to read it at your convenience.`;return{...f}}broadcast($,J,Q,Z){let W=[];for(let j of this.members.values()){if(j.agentId===$)continue;if(j.role==="lead")continue;W.push(this.sendMessage($,j.agentId,J,Q,Z?.taskId))}return W}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let J={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(J);let Q=this.members.get($.agentId);if(Q)Q.lastMissionAt=Date.now(),Q.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:I.TeamMissionLog,entry:{...J}}),{...J}}createOutcome($){let J={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(J.id,J),this.emitEvent({type:I.OutcomeCreated,outcome:{...J}}),{...J}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let J=this.outcomes.get($.outcomeId);if(!J)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!J.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let Q={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(Q.id,Q),J.status==="draft")J.status="in_review";return this.emitEvent({type:I.OutcomeFragmentAttached,fragment:{...Q}}),{...Q}}reviewOutcomeFragment($){let J=this.outcomeFragments.get($.fragmentId);if(!J)throw Error(`Fragment "${$.fragmentId}" was not found`);return J.status=$.approved?"reviewed":"rejected",J.reviewedBy=$.reviewedBy,J.reviewedAt=new Date,this.emitEvent({type:I.OutcomeFragmentReviewed,fragment:{...J}}),{...J}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((J)=>J.outcomeId===$).map((J)=>({...J}))}finalizeOutcome($){let J=this.outcomes.get($);if(!J)throw Error(`Outcome "${$}" was not found`);let Q=this.listOutcomeFragments($);for(let Z of J.requiredSections)if(!Q.some((j)=>j.section===Z&&j.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Z}" is missing a reviewed fragment.`);return J.status="finalized",J.finalizedAt=new Date,this.emitEvent({type:I.OutcomeFinalized,outcome:{...J}}),{...J}}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(J){if(!dW(J))throw J}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[$,J]of this.members.entries())if(J.role==="teammate")this.members.delete($)}requireTask($){let J=this.tasks.get($);if(!J)throw Error(`Task "${$}" was not found`);return J}assertDependenciesResolved($){let J=this.getUnresolvedDependencies($);if(J.length>0)throw Error(`Task "${$.id}" is blocked by "${J[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((J)=>{let Q=this.tasks.get(J);return!Q||Q.status!=="completed"})}trackMeaningfulEvent($,J){if(this.recordRunActivityFromAgentEvent($,J),J.type==="iteration_end"&&J.hadToolCalls){this.recordProgressStep($,`Completed iteration ${J.iteration} with ${J.toolCallCount} tool call(s)`);return}if(J.type==="content_end"&&J.contentType==="tool"&&!J.error){this.recordProgressStep($,`Finished tool "${J.toolName??"unknown"}"`);return}if(J.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${J.iterations} iterations)`});return}if(J.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:J.error.message})}recordRunActivityFromAgentEvent($,J){let Q;switch(J.type){case"iteration_start":Q=`iteration_${J.iteration}_started`;break;case"content_start":if(J.contentType==="tool")Q=`running_tool_${J.toolName??"unknown"}`;break;case"content_end":if(J.contentType==="tool")Q=J.error?this.formatProgressErrorActivity(`tool_${J.toolName??"unknown"}_error`,J.error):`finished_tool_${J.toolName??"unknown"}`;break;case"done":Q="finalizing_response";break;case"error":Q=this.formatProgressErrorActivity("run_error",J.error.message);break;default:break}if(!Q)return;for(let Z of this.runs.values()){if(Z.agentId!==$||Z.status!=="running")continue;this.recordRunProgress(Z,Q)}}recordRunProgress($,J){let Q=new Date;$.heartbeatAt=Q,$.lastProgressAt=Q,$.lastProgressMessage=J,$.currentActivity=J,this.emitEvent({type:I.RunProgress,run:{...$},message:J})}formatProgressErrorActivity($,J){let Q=J.replace(/\s+/g," ").trim();if(Q.length===0)return $;let Z=Q.length>240?`${Q.slice(0,237).trimEnd()}...`:Q;return`${$}: ${Z}`}recordProgressStep($,J,Q,Z=!1){this.missionStepCounter++;let W=this.members.get($);if(!W)return;let j=this.missionStepCounter-W.lastMissionStep,f=Date.now()-W.lastMissionAt;if(!Z&&j<this.missionLogIntervalSteps&&f<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:Q,kind:"progress",summary:J})}buildMailboxNotification($){if($.length===0)return"";let J=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let Q of $)J.push(`--- Message from ${Q.fromAgentId} | subject: ${Q.subject} ---`),J.push(Q.body);return J.push("---"),J.join(`
514
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function GA($){return new Promise((J)=>setTimeout(J,$))}function d8($,J){let Q=0;for(let Z of $){if(!Z.startsWith(J))continue;let W=Number.parseInt(Z.slice(J.length),10);if(Number.isFinite(W))Q=Math.max(Q,W)}return Q}function pW($,J){switch(J.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(J.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let Q;if(J.type==="run_failed")Q=J.run.error;else if(J.type==="run_cancelled"||J.type==="run_interrupted")Q=J.run.error??J.reason;$.activeTeamRunIds.delete(J.run.id),$.pendingTeamRunUpdates.push({runId:J.run.id,agentId:J.run.agentId,taskId:J.run.taskId,status:J.type.replace("run_",""),error:Q,iterations:J.run.result?.iterations}),QQ($);break}default:break}}async function rW($,J,Q){switch(J.type){case"run_progress":await Q("onTeamTaskProgress",$,J.run.agentId,J.message,{kind:J.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(J.event.type==="content_start"&&J.event.contentType==="text"&&typeof J.event.text==="string"){let Z=J.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Z)await Q("onTeamTaskProgress",$,J.agentId,Z,{kind:"text"})}break;case"task_start":await Q("onTeamTaskStart",$,J.agentId,J.message);break;case"task_end":{if(J.error)await Q("onTeamTaskEnd",$,J.agentId,"failed",`[error] ${J.error.message}`,void 0,J.messages);else if(J.result?.finishReason==="aborted")await Q("onTeamTaskEnd",$,J.agentId,"cancelled","[done] aborted",J.result,J.result.messages);else await Q("onTeamTaskEnd",$,J.agentId,"completed",`[done] ${J.result?.finishReason??"completed"}`,J.result,J.result?.messages);break}default:break}}function iW($,J,Q,Z){if(!$.runtime.teamRuntime)return;let W=$.runtime.teamRuntime.getTeamName();Z({type:"team_progress",payload:{sessionId:J,teamName:W,lifecycle:u8({teamName:W,sessionId:J,event:Q}),summary:c8(W,$.runtime.teamRuntime.exportState())}})}function VJ($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function nW($,J){if($.aborting)return!1;if(!(J==="completed"||J==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&VJ($)}function QQ($){let J=$.teamRunWaiters.splice(0);for(let Q of J)Q()}async function aW($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let J=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,J}if($.activeTeamRunIds.size===0)return[];await new Promise((J)=>{$.teamRunWaiters.push(J)})}}function sW($,J){let Q=J.map((j)=>{let f=[`- ${j.runId} (${j.agentId}) -> ${j.status}`];if(j.taskId)f.push(` task=${j.taskId}`);if(typeof j.iterations==="number")f.push(` iterations=${j.iterations}`);if(j.error)f.push(` error=${j.error}`);return f.join("")}),Z=$.activeTeamRunIds.size,W=Z>0?`There are still ${Z} 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 HJ(`System-delivered teammate async run updates:
515
515
  ${Q.join(`
516
516
  `)}
517
517
 
518
- ${W}`,$.config.mode)}function HJ($,J){return xN($,J==="plan"?"plan":J==="yolo"?"yolo":"act")}var oW=4;class n1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,J={}){this.adapter=$;this.manifestStore=new vW($,J.messagesArtifactUploader,J.logger),this.teamChildren=new $9($,this.manifestStore,(Q,Z,W)=>this.toPersistedMessages(Q,Z,W),n1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,J,Q){if(!$)return;return J?y5(J.messages,J,Q):C5($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,J){this.manifestStore.writeSessionManifest($,J)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let J=$.startedAt??e(),Q=$.sessionId.trim(),Z=Q.length>0?Q:`${Date.now()}_${mN(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(Z),j=this.manifestStore.artifacts.sessionManifestPath(Z),f=J6({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Z,source:$.source,pid:$.pid,started_at:J,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:f,messages_path:W};return await this.adapter.upsertSession({sessionId:Z,source:$.source,pid:$.pid,startedAt:J,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:K$(X.metadata),hookPath:"",messagesPath:W,updatedAt:e()}),this.manifestStore.initializeMessagesFile(Z,W,J),this.manifestStore.writeSessionManifest(j,X),{manifestPath:j,messagesPath:W,manifest:X}}async updateSessionStatus($,J,Q){let Z;if((await xY(()=>this.adapter.getSession($),async(j)=>{return Z=j0(J)?void 0:e(),this.adapter.updateSession({sessionId:$,status:J,endedAt:Z??null,exitCode:j0(J)?null:typeof Q==="number"?Q:null,expectedStatusLock:j.statusLock})},oW)).updated){if(J==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}return{updated:!1}}async updateSession($){for(let J=0;J<oW;J++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let Z=Q.metadata??void 0,W=$.metadata!==void 0?K$($.metadata)??{}:K$(Z)??{},j=s$(typeof Z?.title==="string"?Z.title:void 0),f=$.title!==void 0?s$($.title):j??Q7($.prompt);if(f)W.title=f;else delete W.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(W).length>0?W:null:void 0,title:f,expectedStatusLock:Q.statusLock})).updated)continue;let{path:V,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let B=$.metadata!==void 0?K$($.metadata)??{}:K$(H.metadata)??{};if(f)B.title=f;H.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(V,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,J){return this.teamChildren.appendSubagentHookAudit(J),Promise.resolve()}persistSessionMessages($,J,Q){let Z=C5(J);return this.manifestStore.persistSessionMessages($,Z,Q)}applySubagentStatus($,J){return this.teamChildren.applySubagentStatus($,J)}applySubagentStatusBySessionId($,J){return this.teamChildren.applySubagentStatusBySessionId($,J)}applyStatusToRunningChildSessions($,J){return this.teamChildren.applyStatusToRunningChildSessions($,J)}onTeamTaskStart($,J,Q){return this.teamChildren.onTeamTaskStart($,J,Q)}onTeamTaskEnd($,J,Q,Z,W,j){return this.teamChildren.onTeamTaskEnd($,J,Q,Z,W,j)}onTeamTaskProgress($,J,Q,Z){return this.teamChildren.onTeamTaskProgress($,J,Q,Z)}handleSubAgentStart($,J){return this.teamChildren.handleSubAgentStart($,J)}handleSubAgentEnd($,J){return this.teamChildren.handleSubAgentEnd($,J)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(J){return typeof J==="object"&&J!==null&&"code"in J&&J.code==="EPERM"}}async reconcileDeadRunningSession($){if(j0($.status)===!1||this.isPidAlive($.pid))return $;let J=e(),Q=n1.STALE_REASON;for(let Z=0;Z<oW;Z++){let W=await this.adapter.getSession($.sessionId);if(!W)return;if(j0(W.status)===!1)return W;let j={...W.metadata??{},terminal_marker:Q,terminal_marker_at:J,terminal_marker_pid:W.pid,terminal_marker_source:n1.STALE_SOURCE},f=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:J,exitCode:1,metadata:j,expectedStatusLock:W.statusLock});if(!f.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let X=IY(W,{status:"failed",endedAt:J,exitCode:1,metadata:j}),{path:Y}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(J,W.sessionId,W.pid,Q,n1.STALE_SOURCE),{...W,status:"failed",endedAt:J,exitCode:1,metadata:j,statusLock:f.statusLock,updatedAt:J}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let J=Math.max(1,Math.floor($)),Q=Math.min(J*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,J).map((W)=>{let j=K$(W.metadata??void 0),f=this.manifestStore.readSessionManifest(W.sessionId),X=s$(typeof f?.metadata?.title==="string"?f.metadata.title:void 0),Y=X?{...j??{},title:X}:j;return{...W,metadata:Y}})}async reconcileDeadSessions($=2000){let J=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((W)=>this.adapter.listSessions({limit:J,status:W})))).flat(),Z=0;for(let W of Q){let j=await this.reconcileDeadRunningSession(W);if(j&&j.status!==W.status)Z++}return Z}async deleteSession($){let J=$.trim();if(!J)throw Error("session id is required");let Q=await this.adapter.getSession(J);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(J,!1),!Q.isSubagent){let Z=await this.adapter.listSessions({limit:2000,parentSessionId:J});await this.adapter.deleteSession(J,!0),await Promise.allSettled(Z.map(async(W)=>{await T7(W.cwd,W.sessionId),L6(W.messagesPath),L6(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await T7(Q.cwd,J),L6(Q.messagesPath),L6(this.manifestStore.artifacts.sessionManifestPath(J,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(J);else{let Z=new Set([this.manifestStore.artifacts.sessionArtifactsDir(J)]);for(let W of[Q.messagesPath])if(typeof W==="string"&&W.trim().length>0)Z.add(gN(W));for(let W of Z)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function eW(){return new Date().toISOString()}function LA($,J){let Q=`${$}.tmp`;uN(Q,`${JSON.stringify(J,null,2)}
519
- `,"utf8"),cN(Q,$)}class _A{sessionsDirPath;constructor($=dN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!tW(this.sessionsDirPath))vN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return zA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return zA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!tW($))return{version:1,sessions:{}};try{let J=JSON.parse(RA($,"utf8"));if(J?.version===1&&J.sessions)return J}catch{}return{version:1,sessions:{}}}writeIndex($){LA(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!tW($))return{version:1,nextId:1,requests:[]};try{let J=JSON.parse(RA($,"utf8"));if(J?.version===1&&typeof J.nextId==="number"&&Array.isArray(J.requests))return J}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){LA(this.spawnQueuePath(),$)}async upsertSession($){let J=this.readIndex();J.sessions[$.sessionId]=$,this.writeIndex(J)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((J)=>$.parentSessionId!==void 0?J.parentSessionId===$.parentSessionId:!0).filter((J)=>$.status!==void 0?J.status===$.status:!0).sort((J,Q)=>Q.startedAt.localeCompare(J.startedAt)).slice(0,$.limit)}async updateSession($){let J=this.readIndex(),Q=J.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let Z=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,W={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:Z,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:eW()};if($.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return J.sessions[$.sessionId]=W,this.writeIndex(J),{updated:!0,statusLock:W.statusLock}}async deleteSession($,J){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],J){for(let W of Object.values(Q.sessions))if(W.parentSessionId===$)delete Q.sessions[W.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let J=this.readQueue();J.requests.push({id:J.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:eW()}),J.nextId+=1,this.writeQueue(J)}async claimSpawnRequest($,J){let Q=this.readQueue(),Z=Q.requests.find((W)=>W.rootSessionId===$&&W.parentAgentId===J&&!W.consumedAt);if(!Z)return;return Z.consumedAt=eW(),this.writeQueue(Q),Z.task}}class $3 extends n1{constructor($,J={}){super(new _A($),J)}ensureSessionsDir(){return super.ensureSessionsDir()}}var MA={};w(MA,{CoreSessionService:()=>z1});import{existsSync as lN,mkdirSync as pN}from"node:fs";import{resolveSessionDataDir as rN}from"@cline/shared/storage";var J3=`
518
+ ${W}`,$.config.mode)}function HJ($,J){return xN($,J==="plan"?"plan":J==="yolo"?"yolo":"act")}var oW=4;class n1{adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,J={}){this.adapter=$;this.manifestStore=new vW($,J.messagesArtifactUploader,J.logger),this.teamChildren=new $Q($,this.manifestStore,(Q,Z,W)=>this.toPersistedMessages(Q,Z,W),n1.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,J,Q){if(!$)return;return J?y5(J.messages,J,Q):C5($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,J){this.manifestStore.writeSessionManifest($,J)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let J=$.startedAt??e(),Q=$.sessionId.trim(),Z=Q.length>0?Q:`${Date.now()}_${mN(5)}`,W=this.manifestStore.artifacts.sessionMessagesPath(Z),j=this.manifestStore.artifacts.sessionManifestPath(Z),f=J6({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Z,source:$.source,pid:$.pid,started_at:J,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:f,messages_path:W};return await this.adapter.upsertSession({sessionId:Z,source:$.source,pid:$.pid,startedAt:J,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:K$(X.metadata),hookPath:"",messagesPath:W,updatedAt:e()}),this.manifestStore.initializeMessagesFile(Z,W,J),this.manifestStore.writeSessionManifest(j,X),{manifestPath:j,messagesPath:W,manifest:X}}async updateSessionStatus($,J,Q){let Z;if((await IY(()=>this.adapter.getSession($),async(j)=>{return Z=j0(J)?void 0:e(),this.adapter.updateSession({sessionId:$,status:J,endedAt:Z??null,exitCode:j0(J)?null:typeof Q==="number"?Q:null,expectedStatusLock:j.statusLock})},oW)).updated){if(J==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Z}}return{updated:!1}}async updateSession($){for(let J=0;J<oW;J++){let Q=await this.adapter.getSession($.sessionId);if(!Q)return{updated:!1};let Z=Q.metadata??void 0,W=$.metadata!==void 0?K$($.metadata)??{}:K$(Z)??{},j=s$(typeof Z?.title==="string"?Z.title:void 0),f=$.title!==void 0?s$($.title):j??Q7($.prompt);if(f)W.title=f;else delete W.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(W).length>0?W:null:void 0,title:f,expectedStatusLock:Q.statusLock})).updated)continue;let{path:V,manifest:H}=this.manifestStore.readManifestFile($.sessionId);if(H){if($.prompt!==void 0)H.prompt=$.prompt??void 0;let B=$.metadata!==void 0?K$($.metadata)??{}:K$(H.metadata)??{};if(f)B.title=f;H.metadata=Object.keys(B).length>0?B:void 0,this.manifestStore.writeSessionManifest(V,H)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,J){return this.teamChildren.appendSubagentHookAudit(J),Promise.resolve()}persistSessionMessages($,J,Q){let Z=C5(J);return this.manifestStore.persistSessionMessages($,Z,Q)}applySubagentStatus($,J){return this.teamChildren.applySubagentStatus($,J)}applySubagentStatusBySessionId($,J){return this.teamChildren.applySubagentStatusBySessionId($,J)}applyStatusToRunningChildSessions($,J){return this.teamChildren.applyStatusToRunningChildSessions($,J)}onTeamTaskStart($,J,Q){return this.teamChildren.onTeamTaskStart($,J,Q)}onTeamTaskEnd($,J,Q,Z,W,j){return this.teamChildren.onTeamTaskEnd($,J,Q,Z,W,j)}onTeamTaskProgress($,J,Q,Z){return this.teamChildren.onTeamTaskProgress($,J,Q,Z)}handleSubAgentStart($,J){return this.teamChildren.handleSubAgentStart($,J)}handleSubAgentEnd($,J){return this.teamChildren.handleSubAgentEnd($,J)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(J){return typeof J==="object"&&J!==null&&"code"in J&&J.code==="EPERM"}}async reconcileDeadRunningSession($){if(j0($.status)===!1||this.isPidAlive($.pid))return $;let J=e(),Q=n1.STALE_REASON;for(let Z=0;Z<oW;Z++){let W=await this.adapter.getSession($.sessionId);if(!W)return;if(j0(W.status)===!1)return W;let j={...W.metadata??{},terminal_marker:Q,terminal_marker_at:J,terminal_marker_pid:W.pid,terminal_marker_source:n1.STALE_SOURCE},f=await this.adapter.updateSession({sessionId:W.sessionId,status:"failed",endedAt:J,exitCode:1,metadata:j,expectedStatusLock:W.statusLock});if(!f.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(W.sessionId,"failed");let X=kY(W,{status:"failed",endedAt:J,exitCode:1,metadata:j}),{path:Y}=this.manifestStore.readManifestFile(W.sessionId);return this.manifestStore.writeSessionManifest(Y,X),this.manifestStore.appendStaleSessionHookLog(J,W.sessionId,W.pid,Q,n1.STALE_SOURCE),{...W,status:"failed",endedAt:J,exitCode:1,metadata:j,statusLock:f.statusLock,updatedAt:J}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let J=Math.max(1,Math.floor($)),Q=Math.min(J*5,2000);return await this.reconcileDeadSessions(Q),(await this.adapter.listSessions({limit:Q})).slice(0,J).map((W)=>{let j=K$(W.metadata??void 0),f=this.manifestStore.readSessionManifest(W.sessionId),X=s$(typeof f?.metadata?.title==="string"?f.metadata.title:void 0),Y=X?{...j??{},title:X}:j;return{...W,metadata:Y}})}async reconcileDeadSessions($=2000){let J=Math.max(1,Math.floor($)),Q=(await Promise.all(["idle","running","pending"].map((W)=>this.adapter.listSessions({limit:J,status:W})))).flat(),Z=0;for(let W of Q){let j=await this.reconcileDeadRunningSession(W);if(j&&j.status!==W.status)Z++}return Z}async deleteSession($){let J=$.trim();if(!J)throw Error("session id is required");let Q=await this.adapter.getSession(J);if(!Q)return{deleted:!1};if(await this.adapter.deleteSession(J,!1),!Q.isSubagent){let Z=await this.adapter.listSessions({limit:2000,parentSessionId:J});await this.adapter.deleteSession(J,!0),await Promise.allSettled(Z.map(async(W)=>{await T7(W.cwd,W.sessionId),L6(W.messagesPath),L6(this.manifestStore.artifacts.sessionManifestPath(W.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(W.sessionId)}))}if(await T7(Q.cwd,J),L6(Q.messagesPath),L6(this.manifestStore.artifacts.sessionManifestPath(J,!1)),Q.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(J);else{let Z=new Set([this.manifestStore.artifacts.sessionArtifactsDir(J)]);for(let W of[Q.messagesPath])if(typeof W==="string"&&W.trim().length>0)Z.add(gN(W));for(let W of Z)this.manifestStore.artifacts.removeDir(W)}return{deleted:!0}}}function eW(){return new Date().toISOString()}function zA($,J){let Q=`${$}.tmp`;uN(Q,`${JSON.stringify(J,null,2)}
519
+ `,"utf8"),cN(Q,$)}class LA{sessionsDirPath;constructor($=dN()){this.sessionsDirPath=$}ensureSessionsDir(){if(!tW(this.sessionsDirPath))vN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return RA(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return RA(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!tW($))return{version:1,sessions:{}};try{let J=JSON.parse(UA($,"utf8"));if(J?.version===1&&J.sessions)return J}catch{}return{version:1,sessions:{}}}writeIndex($){zA(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!tW($))return{version:1,nextId:1,requests:[]};try{let J=JSON.parse(UA($,"utf8"));if(J?.version===1&&typeof J.nextId==="number"&&Array.isArray(J.requests))return J}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){zA(this.spawnQueuePath(),$)}async upsertSession($){let J=this.readIndex();J.sessions[$.sessionId]=$,this.writeIndex(J)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((J)=>$.parentSessionId!==void 0?J.parentSessionId===$.parentSessionId:!0).filter((J)=>$.status!==void 0?J.status===$.status:!0).sort((J,Q)=>Q.startedAt.localeCompare(J.startedAt)).slice(0,$.limit)}async updateSession($){let J=this.readIndex(),Q=J.sessions[$.sessionId];if(!Q)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&Q.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:Q.statusLock};let Z=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:Q.statusLock,W={...Q,status:$.status??Q.status,endedAt:$.endedAt!==void 0?$.endedAt:Q.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:Q.exitCode??null,prompt:$.prompt!==void 0?$.prompt:Q.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:Q.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:Q.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:Q.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:Q.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:Q.conversationId??null,statusLock:Z,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:Q.isSubagent,updatedAt:eW()};if($.setRunning)W.status="running",W.endedAt=null,W.exitCode=null;return J.sessions[$.sessionId]=W,this.writeIndex(J),{updated:!0,statusLock:W.statusLock}}async deleteSession($,J){let Q=this.readIndex();if(!Q.sessions[$])return!1;if(delete Q.sessions[$],J){for(let W of Object.values(Q.sessions))if(W.parentSessionId===$)delete Q.sessions[W.sessionId]}return this.writeIndex(Q),!0}async enqueueSpawnRequest($){let J=this.readQueue();J.requests.push({id:J.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:eW()}),J.nextId+=1,this.writeQueue(J)}async claimSpawnRequest($,J){let Q=this.readQueue(),Z=Q.requests.find((W)=>W.rootSessionId===$&&W.parentAgentId===J&&!W.consumedAt);if(!Z)return;return Z.consumedAt=eW(),this.writeQueue(Q),Z.task}}class $3 extends n1{constructor($,J={}){super(new LA($),J)}ensureSessionsDir(){return super.ensureSessionsDir()}}var TA={};w(TA,{CoreSessionService:()=>z1});import{existsSync as lN,mkdirSync as pN}from"node:fs";import{resolveSessionDataDir as rN}from"@cline/shared/storage";var J3=`
520
520
  session_id AS sessionId,
521
521
  source,
522
522
  pid,
@@ -543,7 +543,7 @@ ${W}`,$.config.mode)}function HJ($,J){return xN($,J==="plan"?"plan":J==="yolo"?"
543
543
  metadata_json AS metadata,
544
544
  hook_path AS hookPath,
545
545
  messages_path AS messagesPath,
546
- updated_at AS updatedAt`;function Q3($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let J=$.metadata;if(typeof J==="string"&&J.trim())try{let Q=JSON.parse(J);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function Z3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function OA($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class TA{store;sessionsDirPath;constructor($,J=rN()){this.store=$;this.sessionsDirPath=J}ensureSessionsDir(){if(!lN(this.sessionsDirPath))pN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
546
+ updated_at AS updatedAt`;function Q3($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let J=$.metadata;if(typeof J==="string"&&J.trim())try{let Q=JSON.parse(J);$.metadata=Q&&typeof Q==="object"&&!Array.isArray(Q)?Q:null}catch{$.metadata=null}else $.metadata=null;return $}function Z3($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function _A($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class OA{store;sessionsDirPath;constructor($,J=rN()){this.store=$;this.sessionsDirPath=J}ensureSessionsDir(){if(!lN(this.sessionsDirPath))pN(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
547
547
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
548
548
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
549
549
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
@@ -559,23 +559,23 @@ ${W}`,$.config.mode)}function HJ($,J){return xN($,J==="plan"?"plan":J==="yolo"?"
559
559
  WHERE session_id = ? AND status_lock = ?`,[e(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let J=[],Q=[];if($.status!==void 0)J.push("status = ?"),Q.push($.status);if($.endedAt!==void 0)J.push("ended_at = ?"),Q.push($.endedAt);if($.exitCode!==void 0)J.push("exit_code = ?"),Q.push($.exitCode);if($.prompt!==void 0)J.push("prompt = ?"),Q.push($.prompt??null);if($.metadata!==void 0)J.push("metadata_json = ?"),Q.push(Z3($.metadata));if($.parentSessionId!==void 0)J.push("parent_session_id = ?"),Q.push($.parentSessionId??null);if($.parentAgentId!==void 0)J.push("parent_agent_id = ?"),Q.push($.parentAgentId??null);if($.agentId!==void 0)J.push("agent_id = ?"),Q.push($.agentId??null);if($.conversationId!==void 0)J.push("conversation_id = ?"),Q.push($.conversationId??null);if(J.length===0){let f=await this.getSession($.sessionId);return{updated:!!f,statusLock:f?.statusLock??0}}let Z=0;if($.expectedStatusLock!==void 0)Z=$.expectedStatusLock+1,J.push("status_lock = ?"),Q.push(Z);J.push("updated_at = ?"),Q.push(e());let W=`UPDATE sessions SET ${J.join(", ")} WHERE session_id = ?`;if(Q.push($.sessionId),$.expectedStatusLock!==void 0)W+=" AND status_lock = ?",Q.push($.expectedStatusLock);if((this.store.run(W,Q).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Z=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Z}}async deleteSession($,J){let Q=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(J)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return Q>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
560
560
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,e()])}async claimSpawnRequest($,J){let Q=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
561
561
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
562
- ORDER BY id ASC LIMIT 1`,[$,J]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[e(),Q.id]),Q.task??void 0}}class z1 extends n1{store;constructor($,J={}){super(new TA($,J.sessionArtifactsDir),J);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
562
+ ORDER BY id ASC LIMIT 1`,[$,J]);if(!Q||typeof Q.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[e(),Q.id]),Q.task??void 0}}class z1 extends n1{store;constructor($,J={}){super(new OA($,J.sessionArtifactsDir),J);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
563
563
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
564
564
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
565
565
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
566
566
  metadata_json, transcript_path, hook_path, messages_path, updated_at
567
- ) 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,e()])}}function iN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let J=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(J==="local"||J==="hub"||J==="remote")return J;return"auto"}var BJ,AJ;function nN($,J){if($!=="auto"&&$!=="hub")return;if(J.hub?.endpoint?.trim())return;iQ(J.hub?.workspaceRoot?.trim()||J.hub?.cwd?.trim()||process.cwd())}async function aN($){await $.reconcileDeadSessions?.().catch(()=>{})}function NA($){try{let J=new U1;return J.init(),new z1(J,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(J){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),PA($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:J,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new $3(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function qA($,J,Q){return new L1({sessionService:Q??$.sessionService??NA($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:J,fetch:$.fetch})}async function W3($){if(BJ)return BJ;if(AJ)return await AJ;return AJ=(async()=>{return BJ=NA($),await aN(BJ),BJ})().finally(()=>{AJ=void 0}),await AJ}async function p8($){let J=b0($.distinctId);$.telemetry?.setDistinctId(J);let Q=iN($);if(nN(Q,$),Q==="remote"){let Z=$.remote?.endpoint?.trim();if(!Z)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Z}),new x8({endpoint:Z,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let Z=$.hub?.endpoint?.trim(),W=Z||await _2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:Z||void 0}),new r1({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let Z=await QJ({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Z){$.logger?.log("Using discovered local hub runtime host",{url:Z});let W=new r1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await W.connect(),W}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),PA($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),qA($,J)}return qA($,J)}var yA={};w(yA,{NoOpFeatureFlagsProvider:()=>q2,FeatureFlagsService:()=>M2});import{existsSync as sN,mkdirSync as oN,readFileSync as tN,writeFileSync as eN}from"node:fs";import{dirname as $w}from"node:path";import{FEATURE_FLAGS as SA,FeatureFlagDefaultValue as j3}from"@cline/shared";var Jw=3600000,Qw=604800000,CA=1;class M2{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Jw,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Qw,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let J=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===J)return}let Z=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:J||null};try{let W=await this.provider.getAllFlagsAndPayloads({flagKeys:SA.length>0?SA:void 0,context:{...this.context,userId:J}});if(this.cacheInfo.userId!==J)return;this.cacheInfo.flagsPayload=W,this.rebuildCacheFromSnapshot(W),this.writePersistentCache()}catch(W){if(this.cacheInfo.userId!==J)return;throw this.cacheInfo=Z.updateTime?Z:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:W}),W}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>this.isFeatureFlagPayload(J));if(typeof $==="object")return Object.values($).every((J)=>this.isFeatureFlagPayload(J));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=Object.entries($).filter(([,Z])=>this.isFeatureFlagPayload(Z));if(J.length===0)return;let Q={};for(let[Z,W]of J)Q[Z]=W;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!sN(this.cacheFilePath))return;let $=JSON.parse(tN(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let J=$;if(J.version!==CA||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||Date.now()-J.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:J.updatedAt,userId:J.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(J.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(J.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;oN($w(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),J={version:CA,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};eN(this.cacheFilePath,`${JSON.stringify(J,null,2)}
568
- `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let J=new Map;for(let Q of this.getReturnedFlagKeys($)){let Z=this.getFeatureFlag(Q);J.set(Q,Z??!1)}this.cache=J}getFeatureFlag($){try{let J=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],Z=J??Q??j3[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Z)this.telemetry?.capture({event:x.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return Z}catch(J){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:J}),j3[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??j3[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,J){if(process.env.IS_TEST==="true")this.cache.set($,J)}async dispose(){await this.provider.dispose()}}class q2{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}g8();class KJ{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,J,Q,Z,W,j,f,X,Y,V){this.clientName=J,this.runtimeAddress=Q,this.host=$,this.prepare=Z,this.capabilities=W,this.logger=j,this.telemetry=f,this.distinctId=X,this.featureFlags=Y,this.settings=gH($),this.pendingPrompts=mH($),this.automation=new v7(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new s6({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:rV(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:iV({host:$,getExtensionContext:()=>DQ({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let J=b0($.distinctId),Q=L0($.capabilities),Z={...$,capabilities:Q,distinctId:J},W=await p8(Z),j=pV($.automation),f=$.featureFlags||new M2({provider:new q2,telemetry:$.telemetry,logger:$.logger,context:{distinctId:J,clientName:$.clientName}}),X=new KJ(W,$.clientName,W.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,J,f,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let J=this.activeSessionBootstraps.get($);if(!J)return;this.activeSessionBootstraps.delete($),await Promise.resolve(J.dispose?.())}async start($){let J=cH($),Q=await this.prepare?.(J);try{let Z=Q?await Q.applyToStartSessionInput(J):J,W=await this.host.startSession($W(Z,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>DQ({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,Q);else await Promise.resolve(Q.dispose?.());return uH({input:Z,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(Z){throw await Promise.resolve(Q?.dispose?.()),Z}}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 J=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(J.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await vQ(this.host,$);list=async($=200,J={})=>await this.listHistory({...J,limit:$});delete=async($)=>{let J=await this.host.deleteSession($);if(J)await this.disposeSessionBootstrap($);return J};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let J=$.start?$W($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>DQ({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:J})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,J){return this.host.subscribe($,J)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var bA={};w(bA,{resolvePluginSkillDirectoriesFromPaths:()=>$2,resolvePluginConfigSearchPaths:()=>X6,resolveAndLoadAgentPlugins:()=>A8,resolveAgentPluginPaths:()=>e$,loadAgentPluginsFromPathsWithDiagnostics:()=>t$,loadAgentPluginsFromPaths:()=>b5,loadAgentPluginFromPath:()=>j6,discoverPluginModulePaths:()=>Y6});var IA={};w(IA,{toHookConfigFileName:()=>B6,runSubprocessEvent:()=>r8,runHook:()=>n8,resolveHooksConfigSearchPaths:()=>V6,parseHookEventPayload:()=>i8,mergeAgentHooks:()=>W2,listHookConfigFiles:()=>D$,createSubprocessHooks:()=>j9,createHookConfigFileHooks:()=>A6,createHookConfigFileExtension:()=>D8,createHookAuditHooks:()=>F8,createAgentHooksExtension:()=>K8,HookEventPayloadSchema:()=>W9,HookEventNameSchema:()=>Z9,HookConfigFileName:()=>G8,HOOK_CONFIG_FILE_EVENT_MAP:()=>H6,HOOKS_CONFIG_DIRECTORY_NAME:()=>m5});import{HookEventNameSchema as Z9,HookEventPayloadSchema as W9,parseHookEventPayload as i8,resolveHookSessionContext as Vw}from"@cline/shared";import{z as P2}from"zod";import{spawn as Zw}from"node:child_process";import{augmentNodeCommandForDebug as Ww,withResolvedClineBuildEnv as jw}from"@cline/shared";function fw($){let J=$.trim();if(!J)return{};let Z=J.split(`
569
- `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function Xw($,J){let Q=$ instanceof Error?$:Error(String($)),Z=Q,W=J.join(" ");if(Z.code==="EACCES")return Error(`Failed to execute hook command "${W}" (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 "${W}": ${Q.message}`)}async function Yw($,J){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Z,W)=>{let j=(f)=>{Q.off("error",j);let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f)};Q.once("error",j),Q.end(J,(f)=>{if(Q.off("error",j),f){let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f);return}Z()})})}async function r8($,J){let Q=Ww(J.command,{env:J.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Z=!!J.detached,W=Zw(Q[0],Q.slice(1),{cwd:J.cwd,env:jw(J.env),stdio:Z?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z,windowsHide:!0}),j=new Promise((A)=>{W.once("spawn",()=>{try{J.onSpawn?.({command:Q,pid:W.pid??void 0,detached:Z})}catch{}A()})}),f=new Promise((A,K)=>{W.once("error",(G)=>{K(Xw(G,Q))})});if(await Yw(W,JSON.stringify($)),Z){await Promise.race([j,f]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,H;W.stdout.on("data",(A)=>{X+=A.toString()}),W.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,W.kill("SIGKILL")},J.timeoutMs);W.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=fw(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,f])}var Hw=P2.object({contextModification:P2.string().optional(),cancel:P2.boolean().optional(),review:P2.boolean().optional(),errorMessage:P2.string().optional(),context:P2.string().optional(),overrideInput:P2.unknown().optional()}).passthrough();var Bw=["agent","hook"];async function n8($,J={}){let Q=J.command??Bw;return await r8($,{command:Q,cwd:J.cwd,env:J.env,detached:J.detached,timeoutMs:J.timeoutMs,onSpawn:J.onSpawn})}function kA($){return $ instanceof Error?$:Error(String($))}function Aw($){if(!$||typeof $!=="object")return;let J=Hw.safeParse($);if(!J.success)return;let Q=J.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let W=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:W,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function hA($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))if(typeof Z==="string")J[Q]=Z;else J[Q]=JSON.stringify(Z);return J}function a1($,J,Q){let Z=Q.env??process.env,W=Z.CLINE_USER_ID?.trim()||Z.USER?.trim()||"unknown",j=Q.cwd||process.cwd();return{clineVersion:Z.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:J.conversationId,sessionContext:Vw(Q.sessionContext,{hookName:$,conversationId:J.conversationId,agentId:J.agentId,parentAgentId:J.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Q.workspaceInfo,userId:W,agent_id:J.agentId,parent_agent_id:J.parentAgentId}}function Kw($){return{name:$.name,message:$.message,stack:$.stack}}function Gw($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function Fw($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function Dw($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function Uw($){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 Rw($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}async function N2($,J){try{let Q=await n8($,{command:J.command,cwd:J.cwd,env:J.env,detached:!0,onSpawn:J.onSpawn});J.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){J.onDispatchError?.(kA(Q),$)}}function j9($={}){return{hooks:{beforeRun:async(X)=>{let Y=Fw(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...a1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await N2(H,$)}else{let H={...a1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await N2(H,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...a1("tool_call",Y,$),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:hA(X.input)}};try{let H=await n8(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return Rw(Aw(H?.parsedJson))}catch(H){$.onDispatchError?.(kA(H),V);return}},afterTool:async(X)=>{let Y=Uw(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},H={...a1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:hA(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await N2(H,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={...a1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await N2(A,$);return}let H=Y.status==="aborted"||Gw(Y.error?.message)?"agent_abort":"agent_error",B=H==="agent_error"?{...a1(H,V,$),hookName:H,iteration:Y.iterations,error:Kw(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...a1(H,V,$),hookName:H,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await N2(B,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...a1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Dw(X.message.content),attachments:[]}};await N2(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:H})=>{let B={...a1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:H};await N2(B,$)}}}var pK={};w(pK,{writeHubDiscovery:()=>dQ,withHubStartupLock:()=>lQ,verifyHubConnection:()=>G1,truncateNotificationBody:()=>UJ,toHubStatusUrl:()=>PW,toHubHealthUrl:()=>pQ,stopLocalHubServerGracefully:()=>gW,startHubWebSocketServer:()=>C2,startHubServer:()=>dK,spawnDetachedHubServerWithRetry:()=>h8,spawnDetachedHubServer:()=>EW,sendHubCommand:()=>uA,restartLocalHubIfIdleAfterStartupTimeout:()=>sQ,resolveWorkspaceHubOwnerContext:()=>NB,resolveSharedHubOwnerContext:()=>E0,resolveProductionHubOwnerContext:()=>n0,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>l1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>uQ,resolveDefaultHubPort:()=>b8,resolveDefaultHubPathname:()=>yW,resolveDefaultHubHost:()=>CW,resolveCompatibleLocalHubUrl:()=>QJ,resolveClineDir:()=>TB,resolveClineDataDir:()=>R2,requestHubShutdown:()=>JJ,rememberRecoverableLocalHubUrl:()=>P$,readHubDiscovery:()=>A0,readBearerToken:()=>F9,probeHubServer:()=>p1,probeHubConnection:()=>cA,prewarmDetachedHubServer:()=>iQ,normalizeHubWebSocketUrl:()=>N$,isHubReconnectableTransportError:()=>IW,isHubCommandTimeoutError:()=>aQ,isDiscoveryFilePresent:()=>qB,ensureHubWebSocketServer:()=>D9,ensureHubServer:()=>lK,ensureDetachedHubServer:()=>bB,ensureCompatibleLocalHubUrl:()=>_2,createLocalHubScheduleRuntimeHandlers:()=>U9,createInMemoryHubOwnerContext:()=>MB,createHubServerUrl:()=>j1,createHubAuthToken:()=>cQ,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,connectToHub:()=>V9,clearHubDiscovery:()=>y0,NodeHubClient:()=>f1,NativeHubTransportAdapter:()=>OJ,HubUIClient:()=>K3,HubTransportError:()=>q0,HubSessionClient:()=>A3,HubServerTransport:()=>J4,HubScheduleService:()=>s8,HubScheduleCommandService:()=>a8,HubCommandError:()=>k8,DEFAULT_HUB_PORT:()=>wW,DEFAULT_HUB_PATHNAME:()=>SW,DEFAULT_HUB_HOST:()=>NW,BrowserWebSocketHubAdapter:()=>_J});import{createSessionId as zw}from"@cline/shared";function a0($,J){return{version:$.version,requestId:$.requestId,ok:!0,payload:J}}function xA($,J,Q){return{version:$.version,requestId:$.requestId??zw("hubreq_"),ok:!1,error:{code:J,message:Q}}}class a8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return a0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return a0($,{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 a0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return a0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return a0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return a0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return a0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return a0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return a0($,{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 a0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return a0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return a0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return xA($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(J){return xA($,"schedule_command_failed",J instanceof Error?J.message:String(J))}}toCreateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:J}}toUpdateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:J}}}function X9($){return $?new Date($).getTime():void 0}function Lw($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function f9($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:X9($.nextRunAt),lastRunAt:X9($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:Lw($)}}function _w($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function f3($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:X9($.startedAt),endedAt:X9($.completedAt),status:_w($.status),errorMessage:$.error}}class s8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a6({dbPath:$.dbPath}),this.materializer=new l6({store:this.store}),this.runner=new p6({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(VW($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return f9(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?f9(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>f9(J))}updateSchedule($,J){if(J.cronPattern!==void 0)VW(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?f9(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return f3(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),f3(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return f3(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}Y9();import{resolveClineBuildEnv as lw}from"@cline/shared";function pw($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var rw="cline-hub-auth.";function iw($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function nw($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function vA(){return lw()==="production"?n0():E0()}async function aw($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=vA(),Z=await A0(Q.discoveryPath);if(Z?.url&&nw($.toString(),Z.url))return Z.authToken;return}async function H3($={}){let J=i0($);if(!iw($)){let Q=vA(),Z=await A0(Q.discoveryPath);if(Z?.url)return Z.url}return j1(J.host,J.port,J.pathname)}async function V9($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await aw(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${rw}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,B)=>{f.set(V,{resolve:H,reject:B});let A={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(A))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q(pw(Y,$))})})().catch(Q)})}async function cA($){try{return(await V9($)).close(),!0}catch{return!1}}async function uA($,J){let Q=await H3($),Z=await V9(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function B3($){return $?JSON.parse(JSON.stringify($)):{}}function H9($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?B3(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function dA($,J){return $.error?.message??`hub command failed: ${J}`}function sw($){let J=B3($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function lA($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function ow($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function tw($){let J=B3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||lA(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||lA(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:sw($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class A3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new f1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let J=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=H9(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(d1(Q))return;throw Q}return H9(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(dA(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(dA(W,"session.restore"));let j=H9(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=ow(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>H9({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=tw(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class K3{client;constructor($){this.client=new f1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{resolveClineBuildEnv as cK}from"@cline/shared";function ew($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
570
- `).trim()||void 0}var pA=120,G3="...";function UJ($){let J=$.trim();if(!J)return"";if(Buffer.byteLength(J,"utf8")<=pA)return J;let Q=pA-Buffer.byteLength(G3,"utf8");if(Q<=0)return G3;let Z="";for(let W of J){if(Buffer.byteLength(Z+W,"utf8")>Q)break;Z+=W}return`${Z}${G3}`}async function rA($){let J=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,W=[...await q$(Q)].reverse().find((Y)=>Y.role==="assistant"),j=W?ew(W.content):void 0,f=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():f;return{title:`Task completed (${J})`,body:UJ(j&&j.length>0?j:X.length>0?X:f),severity:"info"}}import{captureSdkError as G9,createSessionId as ES}from"@cline/shared";import{createSessionId as ZS}from"@cline/shared";import{createSessionId as QS}from"@cline/shared";function $S($){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 JS($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())J.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())J.parentAgentId=$.parentAgentId;if($.agentId?.trim())J.agentId=$.agentId;if($.conversationId?.trim())J.conversationId=$.conversationId;if($.messagesPath?.trim())J.messagesPath=$.messagesPath;if($.prompt?.trim())J.prompt=$.prompt;if($.provider?.trim())J.provider=$.provider;if($.model?.trim())J.model=$.model;if($.source?.trim())J.source=$.source;if(typeof $.pid==="number")J.pid=$.pid;return Object.keys(J).length>0?J:void 0}function B9($,J,Q,Z){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:J?.createdByClientId??"hub",status:$S($.status),participants:J?[...J.participants.values()]:[],metadata:JS($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Q?{usage:{...Q}}:{},...Z?{aggregateUsage:{...Z}}:{}}}function l($,J){return{version:$.version,requestId:$.requestId,ok:!0,...J!==void 0?{payload:J}:{}}}function v($,J,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:J,message:Q}}}function A9($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function h0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function w2($,J,Q){return{version:"v1",event:$,eventId:QS("hevt_"),sessionId:Q,timestamp:Date.now(),payload:J}}async function s0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let Z=await $.sessionHost.getAccumulatedUsage?.(J);return B9(Q,$.sessionState.get(J),Z?.usage,Z?.aggregateUsage)}async function o0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let[Z,W]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(J):[],$.sessionHost.getAccumulatedUsage?.(J)]);return F1({session:Q,messages:Z,usage:W?.usage,aggregateUsage:W?.aggregateUsage})}function K9($,J,Q,Z,W={}){let j=$.sessionState.get(J);if(j){if(W.interactive!==void 0)j.interactive=W.interactive;if(!j.participants.has(Q))j.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:Z});return j}let f={createdByClientId:Q,interactive:W.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:Z}]])};return $.sessionState.set(J,f),f}async function F3($,J){let Q=ZS("approval_"),Z=J.sessionId;if($.sessionState.get(Z)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Q,{sessionId:Z,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:J.sessionId,agentId:J.agentId,conversationId:J.conversationId,iteration:J.iteration,toolCallId:J.toolCallId,toolName:J.toolName,inputJson:JSON.stringify(J.input??null),policy:J.policy},Z))})}function D3($,J,Q){let Z=$.pendingApprovals.get(J);if(!Z)return;return $.pendingApprovals.delete(J),Z.resolve(Q),{sessionId:Z.sessionId}}function U3($,J,Q){let Z=0;for(let[W,j]of[...$.pendingApprovals.entries()]){if(!J({approvalId:W,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(W),j.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:Q},j.sessionId)),Z+=1}return Z}async function iA($,J){let Q=typeof J.payload?.approvalId==="string"?J.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return v(J,"approval_not_found",`Unknown approval: ${Q}`);let W=typeof J.payload?.reason==="string"?J.payload.reason:J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)&&typeof J.payload.payload.reason==="string"?J.payload.payload.reason:void 0,j=J.payload?.approved===!0,f=D3($,Q,{approved:j,reason:W});if(!f)return v(J,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:j,reason:W},f.sessionId)),l(J,{approvalId:Q,approved:j})}import{createSessionId as fS}from"@cline/shared";function WS($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var nA={debug:10,info:20,warn:30,error:40,silent:50};function jS(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function c($,J,Q={}){if(nA[$]<nA[jS()])return;let Z=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:J,...Object.fromEntries(Object.entries(Q).map(([W,j])=>[W,WS(j)]).filter(([,W])=>W!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Z}`);return}console.log(`[hub] ${Z}`)}function R3($,J){let Q=J instanceof Error?J.stack||J.message:String(J);c("error",$,{error:Q})}async function aA($,J,Q,Z,W,j){let f=fS("capreq_"),X=performance.now();return c("info","capability.request.start",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(f,{sessionId:J,targetClientId:W,capabilityName:Q,onProgress:j,resolve:(H)=>{if(c(H.ok?"info":"warn","capability.request.end",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-X)}),!H.ok){V(Error(H.error||`Capability ${Q} was rejected by ${W}.`));return}Y(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:f,targetClientId:W,capabilityName:Q,payload:Z},J)),c("info","capability.request.published",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W})})}function sA($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);if((J.clientId?.trim()||"")!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{};return Z.onProgress?.(j),l(J,{requestId:Q})}function C$($,J,Q){let Z=0;for(let[W,j]of[...$.pendingCapabilityRequests.entries()]){if(!J({requestId:W,...j}))continue;$.pendingCapabilityRequests.delete(W),c("warn","capability.request.cancelled",{requestId:W,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Q}),j.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:W,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Q},j.sessionId)),Z+=1}return Z}async function oA($,J){let Q=typeof J.payload?.sessionId==="string"?J.payload.sessionId.trim():J.sessionId?.trim()||"",Z=typeof J.payload?.capabilityName==="string"?J.payload.capabilityName.trim():"",W=typeof J.payload?.targetClientId==="string"?J.payload.targetClientId.trim():"";if(!Q||!Z||!W)return v(J,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{},f=await $.requestCapability(Q,Z,j,W);return l(J,f)}catch(j){return v(J,"capability_request_failed",j instanceof Error?j.message:String(j))}}function tA($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);let W=J.clientId?.trim()||"";if(W!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);$.pendingCapabilityRequests.delete(Q);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:void 0,f=typeof J.payload?.error==="string"?J.payload.error:void 0,X=J.payload?.ok===!0;return c(X?"info":"warn","capability.respond",{requestId:Q,sessionId:Z.sessionId,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,error:f}),Z.resolve({ok:X,payload:j,error:f}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,payload:j,error:f},Z.sessionId)),l(J,{requestId:Q,ok:X})}import{createSessionId as XS}from"@cline/shared";function eA($,J){let Q=J.payload,Z=Q?.clientId?.trim()||J.clientId?.trim()||XS("client_");return $.clients.set(Z,{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),l(J,{clientId:Z})}function $K($,J){let Q=J.clientId?.trim(),Z=Q?$.clients.get(Q):void 0;if(!Q||!Z)return v(J,"client_not_found","Client is not registered with this hub.");let W=A9(J.payload?.metadata);if(Z.lastSeenAt=Date.now(),W)Z.metadata=JSON.parse(JSON.stringify(W));return l(J)}function JK($,J,Q){let Z=J.clientId?.trim();if(Z)$.clients.delete(Z),Q(Z),$.publish($.buildEvent("hub.client.disconnected",{clientId:Z}));return l(J)}function QK($,J){return l(J,{clients:[...$.clients.values()]})}var YS=30000;function VS($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function HS($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function BS($,J,Q){let Z=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${J}`;return v($,G2,Z)}function AS($){return $?$:void 0}function KS($){let J=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function GS($,J,Q,Z){let W=performance.now(),j=!1,f={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q.sessionId,timeoutMs:Z},X=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-W);c("warn","run.heartbeat",{...f,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:J.requestId,elapsedMs:H,...Z?{timeoutMs:Z}:{}},Q.sessionId))},YS),Y=$.sessionHost.runTurn(Q);Y.then((H)=>{if(!j)return;c("warn","run.late_end",{...f,elapsedMs:Math.round(performance.now()-W),finishReason:H?.finishReason})},(H)=>{if(!j)return;c("error","run.late_error",{...f,elapsedMs:Math.round(performance.now()-W),error:H})});let V;try{if(!Z)return await Y;return await Promise.race([Y,new Promise((H,B)=>{V=setTimeout(()=>{let A=`Hub run ${J.command} timed out after ${Z}ms.`;j=!0,clearInterval(X),B(Error(A)),c("error","run.timeout",{...f,elapsedMs:Math.round(performance.now()-W)}),U3($,(K)=>K.sessionId===Q.sessionId,A),C$($,(K)=>K.sessionId===Q.sessionId,A),$.sessionHost.abort(Q.sessionId,A).catch((K)=>{c("error","run.timeout_abort_failed",{...f,error:K})})},Z)})])}finally{if(j=!0,clearInterval(X),V)clearTimeout(V)}}async function ZK($,J){let Q=h0(J),Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.prompt==="string"?Z.prompt:typeof Z.input==="string"?Z.input:"";if(!W.trim())return v(J,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let j=Z.attachments&&typeof Z.attachments==="object"&&!Array.isArray(Z.attachments)?Z.attachments:void 0,f=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,X=KS(Z);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let Y;try{Y=await GS($,J,{sessionId:Q,prompt:W,mode:AS(Z.mode),delivery:Z.delivery==="queue"||Z.delivery==="steer"?Z.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:f,timeoutMs:X},X)}catch(H){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(d1(H))return BS(J,Q,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Q)),H}if(Y){let H=await o0($,Q),B=HS(Y);if($.publish($.buildEvent(VS(Y.finishReason),{reason:Y.finishReason,...B?{error:B}:{},result:Y,...H?{snapshot:H}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let V=await o0($,Q);return l(J,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function WK($,J){let Q=h0(J),Z=typeof J.payload?.reason==="string"?J.payload.reason:"Run was aborted before pending approval or capability request was resolved.";U3($,(W)=>W.sessionId===Q,Z);try{await $.sessionHost.abort(Q,J.payload?.reason)}catch(W){c("warn","run.abort_failed",{command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q,error:W})}finally{C$($,(W)=>W.sessionId===Q,Z)}return l(J,{applied:!0})}async function jK($,J){let Q=i8(J.payload?.payload);if(!Q)return v(J,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),l(J,{applied:!0})}async function fK($,J){switch(J.type){case"chunk":return;case"agent_event":await FS($,J);return;case"hook":if(J.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:J.payload.toolName},J.payload.sessionId));else if(J.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:J.payload.toolName},J.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:J.payload.sessionId,summary:J.payload.summary,lastEvent:J.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,J.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:J.payload.sessionId,prompts:J.payload.prompts},J.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:J.payload.id,prompt:J.payload.prompt,delivery:J.payload.delivery,attachmentCount:J.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:J.payload.sessionId,prompt:Q},J.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:J.payload.sessionId,snapshot:J.payload.snapshot},J.payload.sessionId));return;case"status":{let[Q,Z]=await Promise.all([s0($,J.payload.sessionId),o0($,J.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J.payload.sessionId));return}case"ended":await DS($,J);return;default:return}}async function FS($,J){let{sessionId:Q,event:Z}=J.payload;if(Z.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Z.iteration},Q));return}if(Z.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Z.iteration,hadToolCalls:Z.hadToolCalls,toolCallCount:Z.toolCallCount},Q));return}if(Z.type==="content_start"){if(Z.contentType==="text"&&typeof Z.text==="string"&&Z.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Z.text},Q));return}if(Z.contentType==="reasoning"){if(Z.redacted&&!Z.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof Z.reasoning==="string"&&Z.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Z.reasoning,redacted:Z.redacted===!0},Q));return}if(Z.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Z.toolCallId,toolName:Z.toolName,input:Z.input},Q));return}}if(Z.type==="content_end"){switch(Z.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Z.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Z.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,error:Z.error},Q));break}return}if(Z.type==="usage"){let W;try{W=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{W=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadTokens:Z.cacheReadTokens??0,cacheWriteTokens:Z.cacheWriteTokens??0,totalCost:Z.cost??0},totals:{inputTokens:Z.totalInputTokens,outputTokens:Z.totalOutputTokens,cacheReadTokens:Z.totalCacheReadTokens??0,cacheWriteTokens:Z.totalCacheWriteTokens??0,totalCost:Z.totalCost??0},usage:W?.usage,aggregateUsage:W?.aggregateUsage,agent:{kind:J.payload.teamRole==="teammate"?"teammate":Z.parentAgentId?"subagent":"lead",agentId:Z.agentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamAgentId:J.payload.teamAgentId,teamRole:J.payload.teamRole}},Q));return}if(Z.type==="done")$.publish($.buildEvent("agent.done",{reason:Z.reason,text:Z.text,iterations:Z.iterations,usage:Z.usage},Q))}async function DS($,J){let Q=$.suppressNextTerminalEventBySession.get(J.payload.sessionId),Z=Q===J.payload.reason||Q==="run.start.reply";if(Z)$.suppressNextTerminalEventBySession.delete(J.payload.sessionId);let[W,j]=await Promise.all([s0($,J.payload.sessionId),o0($,J.payload.sessionId)]);if(J.payload.reason==="completed"){let f=await rA(W);$.publish($.buildEvent("ui.notify",f,J.payload.sessionId))}if(Z)return;$.publish($.buildEvent(J.payload.reason==="aborted"?"run.aborted":J.payload.reason==="error"||J.payload.reason==="failed"?"run.failed":"run.completed",{reason:J.payload.reason,...j?{snapshot:j}:{}},J.payload.sessionId))}import{createSessionId as KK,parseRuntimeConfigExtensions as GK}from"@cline/shared";var HK={};w(HK,{SessionVersioningService:()=>y$,SessionVersioningError:()=>k0});var VK={};w(VK,{trimMessagesToCheckpoint:()=>YK,trimMessagesBeforeCheckpoint:()=>L3,readSessionCheckpointHistory:()=>RJ,createRestoredCheckpointMetadata:()=>z3,createCheckpointRestorePlan:()=>_3,applyCheckpointToWorktree:()=>O3});import{execFile as US}from"node:child_process";import{promisify as RS}from"node:util";var $4=RS(US);function RJ($){let J=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(J?.history)?J.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let W=String(Z.ref??"").trim(),j=Number(Z.createdAt??0),f=Number(Z.runCount??0);if(W.length===0||!Number.isFinite(j)||!Number.isInteger(f)||f<1)return[];let X=Z.kind==="stash"||Z.kind==="commit"?Z.kind:void 0;return[{ref:W,createdAt:j,runCount:f,...X?{kind:X}:{}}]})}function z3($,J){let Q=RJ($).filter((W)=>W.runCount<=J),Z=Q.at(-1);return Z?{latest:Z,history:Q}:void 0}function zS($,J){return $.reduce((Q,Z)=>{if(Z.runCount>J)return Q;if(!Q||Z.runCount>Q.runCount)return Z;return Q},void 0)}function XK($,J){let Q=0;for(let Z=0;Z<$.length;Z+=1){let W=$[Z];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===J)return Z}throw Error(`Could not find user message for checkpoint run ${J}`)}function YK($,J){let Q=XK($,J);return $.slice(0,Q+1)}function L3($,J){let Q=XK($,J);return $.slice(0,Q)}function _3($){let J=$.checkpointRunCount;if(!Number.isInteger(J)||J<1)throw Error("checkpointRunCount must be a positive integer");let Q=zS(RJ($.session),J);if(!Q)throw Error(`No checkpoint found at or before run ${J} in session ${$.session.sessionId}`);let Z=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Z)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:Z,...$.restoreMessages!==!1?{messages:YK($.messages??[],J)}:{}}}async function O3($,J){if((await $4("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await $4("git",["-C",$,"cat-file","-e",`${J.ref}^{commit}`],{windowsHide:!0}),await $4("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await $4("git",["-C",$,"clean","-fd"],{windowsHide:!0}),J.kind==="commit"){await $4("git",["-C",$,"reset","--hard",J.ref],{windowsHide:!0});return}await $4("git",["-C",$,"stash","apply",J.ref],{windowsHide:!0})}class k0 extends Error{code;constructor($,J){super(J);this.code=$;this.name="SessionVersioningError"}}function LS($){let J=$.sessionId.trim();if(!J)throw new k0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new k0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new k0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new k0("invalid_restore","checkpointRunCount must be a positive integer");return J}class y${async restoreCheckpoint($){let J=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,Z=LS({sessionId:$.sessionId,restoreMessages:J,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),W=await $.getSession(Z);if(!W)throw new k0("session_not_found",`Session ${Z} not found`);let j=J?await $.readMessages(Z):void 0;if(J&&j?.length===0)throw new k0("session_messages_not_found",`No messages found for session ${Z}`);let f=_3({session:W,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:J});if(Q)await($.applyWorkspaceCheckpoint??O3)(f.cwd,f.checkpoint);let X=F1({session:W,messages:j});if(!J)return{checkpoint:f.checkpoint,sourceSnapshot:X};let Y=z3(W,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?L3(j??[],$.checkpointRunCount):f.messages??[],H={sourceSession:W,sourceMessages:j,sourceSnapshot:X,plan:f,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:J,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new k0("invalid_restore","start is required when restore.messages is true");let B=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,A=await $.startSession(B),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??HV)(f.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:f.messages,checkpoint:f.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:F1({session:G,messages:V})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as bp,HUB_COMPACTION_CAPABILITY as hp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as kp,HUB_HOOK_CAPABILITY_PREFIX as Ip,HUB_MISTAKE_LIMIT_CAPABILITY as xp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as mp,isHubToolExecutorName as _S}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as lp,HUB_COMPACTION_CAPABILITY as pp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as rp,HUB_HOOK_CAPABILITY_PREFIX as ip,HUB_MISTAKE_LIMIT_CAPABILITY as np,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ap,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as sp}from"@cline/shared";var OS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function S2($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function TS($,J){let Q=typeof $.name==="string"?$.name.trim():"",Z=typeof $.description==="string"?$.description:"",W=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=S2($.inputSchema);if(!Q||!Z||!j||!W||J.has(W))return;return J.add(W),{kind:"tool",capabilityName:W,name:Q,description:Z,inputSchema:j,...S2($.lifecycle)?{lifecycle:S2($.lifecycle)}:{}}}function M3($){if(!Array.isArray($))return[];let J=[],Q=new Set;for(let Z of $){if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let W=Z,j=W.kind,f=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!f||Q.has(f))continue;if(j==="tool"){let X=TS(W,Q);if(X)J.push(X);continue}if(j==="toolExecutor"){let X=W.executor;if(!_S(X))continue;Q.add(f),J.push({kind:"toolExecutor",capabilityName:f,executor:X});continue}if(j==="hook"){let X=typeof W.name==="string"?W.name.trim():"";if(!X)continue;Q.add(f),J.push({kind:"hook",capabilityName:f,name:X});continue}if(j==="compaction"){Q.add(f),J.push({kind:"compaction",capabilityName:f,...S2(W.config)?{config:S2(W.config)}:{}});continue}if(j==="checkpoint"){Q.add(f),J.push({kind:"checkpoint",capabilityName:f,...S2(W.config)?{config:S2(W.config)}:{}});continue}if(j==="mistakeLimit"){Q.add(f),J.push({kind:"mistakeLimit",capabilityName:f});continue}if(j==="userInstructionService")Q.add(f),J.push({kind:"userInstructionService",capabilityName:f})}return J}function AK($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function MS($){return Object.hasOwn($,"update")?$.update:$}function zJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function qS($){let J=($??[]).map(zJ).filter(Boolean);return J.length>0?new Set(J):void 0}function PS($,J,Q){if(!Q)return!0;let Z=zJ($),W=zJ(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function T3($,J){let Q=qS(J);return $.records.skill.map((Z)=>({id:Z.id,name:Z.item.name,description:"description"in Z.item&&typeof Z.item.description==="string"?Z.item.description:void 0,disabled:Z.item.disabled===!0,skill:Z.item})).filter((Z)=>PS(Z.id,Z.name,Q))}function BK($,J){let Q=async(Z,W)=>{let j=zJ(Z),X=T3($,J).filter((A)=>A.id===j||zJ(A.name)===j||A.id.endsWith(`:${j}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Z}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Z}" not found.`;let Y=X[0].skill,V=W?.trim(),H=V?`
567
+ ) 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,e()])}}function iN($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let J=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(J==="local"||J==="hub"||J==="remote")return J;return"auto"}var BJ,AJ;function nN($,J){if($!=="auto"&&$!=="hub")return;if(J.hub?.endpoint?.trim())return;i9(J.hub?.workspaceRoot?.trim()||J.hub?.cwd?.trim()||process.cwd())}async function aN($){await $.reconcileDeadSessions?.().catch(()=>{})}function PA($){try{let J=new U1;return J.init(),new z1(J,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(J){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),qA($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:J,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new $3(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function MA($,J,Q){return new L1({sessionService:Q??$.sessionService??PA($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:J,fetch:$.fetch})}async function W3($){if(BJ)return BJ;if(AJ)return await AJ;return AJ=(async()=>{return BJ=PA($),await aN(BJ),BJ})().finally(()=>{AJ=void 0}),await AJ}async function p8($){let J=b0($.distinctId);$.telemetry?.setDistinctId(J);let Q=iN($);if(nN(Q,$),Q==="remote"){let Z=$.remote?.endpoint?.trim();if(!Z)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Z}),new x8({endpoint:Z,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(Q==="hub"){let Z=$.hub?.endpoint?.trim(),W=Z||await _2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!W)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:W,explicitEndpoint:Z||void 0}),new r1({url:W,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(Q==="auto"){let Z=await QJ({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Z){$.logger?.log("Using discovered local hub runtime host",{url:Z});let W=new r1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await W.connect(),W}catch(j){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:j}),qA($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:j,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),MA($,J)}return MA($,J)}var CA={};w(CA,{NoOpFeatureFlagsProvider:()=>q2,FeatureFlagsService:()=>M2});import{existsSync as sN,mkdirSync as oN,readFileSync as tN,writeFileSync as eN}from"node:fs";import{dirname as $w}from"node:path";import{FEATURE_FLAGS as wA,FeatureFlagDefaultValue as j3}from"@cline/shared";var Jw=3600000,Qw=604800000,SA=1;class M2{provider;telemetry;logger;cacheTtlMs;cacheFilePath;persistentCacheMaxAgeMs;context;cache=new Map;cacheInfo={updateTime:0,userId:null};constructor($){this.provider=$.provider,this.telemetry=$.telemetry,this.logger=$.logger,this.cacheTtlMs=$.cacheTtlMs??Jw,this.cacheFilePath=$.cacheFilePath,this.persistentCacheMaxAgeMs=$.persistentCacheMaxAgeMs??Qw,this.context={...$.context??{}},this.hydrateFromPersistentCache()}setContext($){this.context={...$}}hydrateCache($){this.cacheInfo={updateTime:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload},this.rebuildCacheFromSnapshot($.flagsPayload)}getCacheSnapshot(){return{updateTime:this.cacheInfo.updateTime,userId:this.cacheInfo.userId,flagsPayload:this.cacheInfo.flagsPayload}}async poll($){let J=$??this.context.userId??null,Q=Date.now();if(Q-this.cacheInfo.updateTime<this.cacheTtlMs){if(this.cacheInfo.userId===J)return}let Z=this.cacheInfo;this.cacheInfo={updateTime:Q,userId:J||null};try{let W=await this.provider.getAllFlagsAndPayloads({flagKeys:wA.length>0?wA:void 0,context:{...this.context,userId:J}});if(this.cacheInfo.userId!==J)return;this.cacheInfo.flagsPayload=W,this.rebuildCacheFromSnapshot(W),this.writePersistentCache()}catch(W){if(this.cacheInfo.userId!==J)return;throw this.cacheInfo=Z.updateTime?Z:{updateTime:0,userId:null},this.logger?.error?.("Error polling SDK feature flags",{error:W}),W}}hydrateFromPersistentCache(){let $=this.readPersistentCache();if($)this.hydrateCache($)}isFeatureFlagPayload($){if($===null||typeof $==="string"||typeof $==="number"||typeof $==="boolean")return!0;if(Array.isArray($))return $.every((J)=>this.isFeatureFlagPayload(J));if(typeof $==="object")return Object.values($).every((J)=>this.isFeatureFlagPayload(J));return!1}readPayloadRecord($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=Object.entries($).filter(([,Z])=>this.isFeatureFlagPayload(Z));if(J.length===0)return;let Q={};for(let[Z,W]of J)Q[Z]=W;return Q}readPersistentCache(){try{if(!this.cacheFilePath||!sN(this.cacheFilePath))return;let $=JSON.parse(tN(this.cacheFilePath,"utf8"));if(!$||typeof $!=="object")return;let J=$;if(J.version!==SA||typeof J.updatedAt!=="number"||!Number.isFinite(J.updatedAt)||Date.now()-J.updatedAt>this.persistentCacheMaxAgeMs)return;return{updateTime:J.updatedAt,userId:J.userId??null,flagsPayload:{featureFlags:this.readPayloadRecord(J.flagsPayload?.featureFlags),featureFlagPayloads:this.readPayloadRecord(J.flagsPayload?.featureFlagPayloads)}}}catch($){this.logger?.error?.("Error reading SDK feature flags cache",{error:$});return}}writePersistentCache(){try{if(!this.cacheFilePath)return;oN($w(this.cacheFilePath),{recursive:!0,mode:448});let $=this.getCacheSnapshot(),J={version:SA,updatedAt:$.updateTime,userId:$.userId,flagsPayload:$.flagsPayload};eN(this.cacheFilePath,`${JSON.stringify(J,null,2)}
568
+ `,"utf8")}catch($){this.logger?.error?.("Error writing SDK feature flags cache",{error:$})}}getReturnedFlagKeys($){return[...new Set([...Object.keys($?.featureFlags??{}),...Object.keys($?.featureFlagPayloads??{})])]}rebuildCacheFromSnapshot($){let J=new Map;for(let Q of this.getReturnedFlagKeys($)){let Z=this.getFeatureFlag(Q);J.set(Q,Z??!1)}this.cache=J}getFeatureFlag($){try{let J=this.cacheInfo.flagsPayload?.featureFlagPayloads?.[$],Q=this.cacheInfo.flagsPayload?.featureFlags?.[$],Z=J??Q??j3[$]??void 0;if(!this.cache.has($)||this.cache.get($)!==Z)this.telemetry?.capture({event:x.FEATURE_FLAGS.FLAG_CALLED,properties:{$feature_flag:$,$feature_flag_response:Q}});return Z}catch(J){return this.logger?.error?.(`Error checking SDK feature flag ${$}`,{error:J}),j3[$]??!1}}getBooleanFlagEnabled($){return this.cache.get($)===!0}getFlagPayload($){return this.cache.get($)??j3[$]}getProvider(){return this.provider}get enabled(){return this.provider.enabled}getSettings(){return this.provider.getSettings()}test($,J){if(process.env.IS_TEST==="true")this.cache.set($,J)}async dispose(){await this.provider.dispose()}}class q2{async getAllFlagsAndPayloads(){return{}}enabled=!1;getSettings(){return{enabled:!1,timeoutMs:1000}}async dispose(){}}g8();class KJ{clientName;runtimeAddress;automation;settings;featureFlags;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,J,Q,Z,W,j,f,X,Y,V){this.clientName=J,this.runtimeAddress=Q,this.host=$,this.prepare=Z,this.capabilities=W,this.logger=j,this.telemetry=f,this.distinctId=X,this.featureFlags=Y,this.settings=xH($),this.pendingPrompts=gH($),this.automation=new v7(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=V?new s6({workspaceRoot:V.workspaceRoot??process.cwd(),specs:{cronSpecsDir:V.cronSpecsDir??V.cronDir,scope:pV(V.cronScope),workspaceRoot:V.workspaceRoot},runtimeHandlers:rV({host:$,getExtensionContext:()=>D9({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:V.dbPath,logger:V.logger,pollIntervalMs:V.pollIntervalMs,claimLeaseSeconds:V.claimLeaseSeconds,globalMaxConcurrency:V.globalMaxConcurrency,watcherDebounceMs:V.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((H)=>{if(H.type!=="ended")return;this.disposeSessionBootstrap(H.payload.sessionId)})}static async create($={}){let J=b0($.distinctId),Q=L0($.capabilities),Z={...$,capabilities:Q,distinctId:J},W=await p8(Z),j=lV($.automation),f=$.featureFlags||new M2({provider:new q2,telemetry:$.telemetry,logger:$.logger,context:{distinctId:J,clientName:$.clientName}}),X=new KJ(W,$.clientName,W.runtimeAddress,$.prepare,Q,$.logger,$.telemetry,J,f,j?{...j,logger:$.logger}:void 0);if(j&&j.autoStart!==!1)await X.automation.start();return X}async disposeSessionBootstrap($){let J=this.activeSessionBootstraps.get($);if(!J)return;this.activeSessionBootstraps.delete($),await Promise.resolve(J.dispose?.())}async start($){let J=vH($),Q=await this.prepare?.(J);try{let Z=Q?await Q.applyToStartSessionInput(J):J,W=await this.host.startSession($W(Z,{defaultCapabilities:this.capabilities,withExtensionContext:(j)=>D9({automationService:this.automationService,automation:this.automation,context:j,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(Q)if(await this.host.getSession(W.sessionId))this.activeSessionBootstraps.set(W.sessionId,Q);else await Promise.resolve(Q.dispose?.());return cH({input:Z,sessionId:W.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),W}catch(Z){throw await Promise.resolve(Q?.dispose?.()),Z}}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 J=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(J.map((Q)=>this.disposeSessionBootstrap(Q)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await v9(this.host,$);list=async($=200,J={})=>await this.listHistory({...J,limit:$});delete=async($)=>{let J=await this.host.deleteSession($);if(J)await this.disposeSessionBootstrap($);return J};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let J=$.start?$W($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(Q)=>D9({automationService:this.automationService,automation:this.automation,context:Q,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:J})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,J){return this.host.subscribe($,J)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}var EA={};w(EA,{resolvePluginSkillDirectoriesFromPaths:()=>$2,resolvePluginConfigSearchPaths:()=>X6,resolveAndLoadAgentPlugins:()=>A8,resolveAgentPluginPaths:()=>e$,loadAgentPluginsFromPathsWithDiagnostics:()=>t$,loadAgentPluginsFromPaths:()=>b5,loadAgentPluginFromPath:()=>j6,discoverPluginModulePaths:()=>Y6});var kA={};w(kA,{toHookConfigFileName:()=>B6,runSubprocessEvent:()=>r8,runHook:()=>n8,resolveHooksConfigSearchPaths:()=>V6,parseHookEventPayload:()=>i8,mergeAgentHooks:()=>W2,listHookConfigFiles:()=>D$,createSubprocessHooks:()=>jQ,createHookConfigFileHooks:()=>A6,createHookConfigFileExtension:()=>D8,createHookAuditHooks:()=>F8,createAgentHooksExtension:()=>K8,HookEventPayloadSchema:()=>WQ,HookEventNameSchema:()=>ZQ,HookConfigFileName:()=>G8,HOOK_CONFIG_FILE_EVENT_MAP:()=>H6,HOOKS_CONFIG_DIRECTORY_NAME:()=>m5});import{HookEventNameSchema as ZQ,HookEventPayloadSchema as WQ,parseHookEventPayload as i8,resolveHookSessionContext as Vw}from"@cline/shared";import{z as P2}from"zod";import{spawn as Zw}from"node:child_process";import{augmentNodeCommandForDebug as Ww,withResolvedClineBuildEnv as jw}from"@cline/shared";function fw($){let J=$.trim();if(!J)return{};let Z=J.split(`
569
+ `).map((j)=>j.trim()).filter(Boolean).filter((j)=>j.startsWith("HOOK_CONTROL\t")).map((j)=>j.slice(13)),W=Z.length>0?Z[Z.length-1]:J;try{return{parsedJson:JSON.parse(W)}}catch(j){return{parseError:j instanceof Error?j.message:"Failed to parse subprocess stdout JSON"}}}function Xw($,J){let Q=$ instanceof Error?$:Error(String($)),Z=Q,W=J.join(" ");if(Z.code==="EACCES")return Error(`Failed to execute hook command "${W}" (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 "${W}": ${Q.message}`)}async function Yw($,J){let Q=$.stdin;if(!Q)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Z,W)=>{let j=(f)=>{Q.off("error",j);let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f)};Q.once("error",j),Q.end(J,(f)=>{if(Q.off("error",j),f){let X=f.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Z();return}W(f);return}Z()})})}async function r8($,J){let Q=Ww(J.command,{env:J.env,debugRole:"hook"});if(!Array.isArray(Q)||Q.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Z=!!J.detached,W=Zw(Q[0],Q.slice(1),{cwd:J.cwd,env:jw(J.env),stdio:Z?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Z,windowsHide:!0}),j=new Promise((A)=>{W.once("spawn",()=>{try{J.onSpawn?.({command:Q,pid:W.pid??void 0,detached:Z})}catch{}A()})}),f=new Promise((A,K)=>{W.once("error",(G)=>{K(Xw(G,Q))})});if(await Yw(W,JSON.stringify($)),Z){await Promise.race([j,f]),W.unref();return}if(!W.stdout||!W.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",Y="",V=!1,H;W.stdout.on("data",(A)=>{X+=A.toString()}),W.stderr.on("data",(A)=>{Y+=A.toString()});let B=new Promise((A)=>{if((J.timeoutMs??0)>0)H=setTimeout(()=>{V=!0,W.kill("SIGKILL")},J.timeoutMs);W.once("close",(K)=>{if(H)clearTimeout(H);let{parsedJson:G,parseError:R}=fw(X);A({exitCode:K,stdout:X,stderr:Y,parsedJson:G,parseError:R,timedOut:V})})});return await Promise.race([B,f])}var Hw=P2.object({contextModification:P2.string().optional(),cancel:P2.boolean().optional(),review:P2.boolean().optional(),errorMessage:P2.string().optional(),context:P2.string().optional(),overrideInput:P2.unknown().optional()}).passthrough();var Bw=["agent","hook"];async function n8($,J={}){let Q=J.command??Bw;return await r8($,{command:Q,cwd:J.cwd,env:J.env,detached:J.detached,timeoutMs:J.timeoutMs,onSpawn:J.onSpawn})}function hA($){return $ instanceof Error?$:Error(String($))}function Aw($){if(!$||typeof $!=="object")return;let J=Hw.safeParse($);if(!J.success)return;let Q=J.data;if(!(("cancel"in Q)||("review"in Q)||("context"in Q)||("contextModification"in Q)||("overrideInput"in Q)||("errorMessage"in Q)))return;let W=typeof Q.context==="string"?Q.context:typeof Q.contextModification==="string"?Q.contextModification:typeof Q.errorMessage==="string"&&Q.errorMessage.length>0?Q.errorMessage:void 0;return{cancel:typeof Q.cancel==="boolean"?Q.cancel:void 0,review:typeof Q.review==="boolean"?Q.review:void 0,context:W,overrideInput:Object.hasOwn(Q,"overrideInput")?Q.overrideInput:void 0}}function bA($){if(!$||typeof $!=="object")return{};let J={};for(let[Q,Z]of Object.entries($))if(typeof Z==="string")J[Q]=Z;else J[Q]=JSON.stringify(Z);return J}function a1($,J,Q){let Z=Q.env??process.env,W=Z.CLINE_USER_ID?.trim()||Z.USER?.trim()||"unknown",j=Q.cwd||process.cwd();return{clineVersion:Z.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:J.conversationId,sessionContext:Vw(Q.sessionContext,{hookName:$,conversationId:J.conversationId,agentId:J.agentId,parentAgentId:J.parentAgentId}),workspaceRoots:j?[j]:[],workspaceInfo:Q.workspaceInfo,userId:W,agent_id:J.agentId,parent_agent_id:J.parentAgentId}}function Kw($){return{name:$.name,message:$.message,stack:$.stack}}function Gw($){let J=String($??"").toLowerCase();return J.includes("cancel")||J.includes("abort")||J.includes("interrupt")}function Fw($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function Dw($){return $.filter((J)=>J.type==="text"&&typeof J.text==="string").map((J)=>J.text).join("")}function Uw($){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 Rw($){if(!$)return;let J={};if($.cancel===!0)J.stop=!0;if($.overrideInput!==void 0)J.input=$.overrideInput;return Object.keys(J).length>0?J:void 0}async function N2($,J){try{let Q=await n8($,{command:J.command,cwd:J.cwd,env:J.env,detached:!0,onSpawn:J.onSpawn});J.onDispatch?.({payload:$,result:Q,detached:!0})}catch(Q){J.onDispatchError?.(hA(Q),$)}}function jQ($={}){return{hooks:{beforeRun:async(X)=>{let Y=Fw(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let H={...a1("agent_resume",Y,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await N2(H,$)}else{let H={...a1("agent_start",Y,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await N2(H,$)}return},beforeTool:async(X)=>{let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...a1("tool_call",Y,$),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:bA(X.input)}};try{let H=await n8(V,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:V,result:H,detached:!1}),H?.timedOut)throw Error("tool_call hook command timed out");if(H?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${H.parseError}`);return Rw(Aw(H?.parsedJson))}catch(H){$.onDispatchError?.(hA(H),V);return}},afterTool:async(X)=>{let Y=Uw(X),V={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},H={...a1("tool_result",V,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:Y,postToolUse:{toolName:Y.name,parameters:bA(Y.input),result:typeof Y.output==="string"?Y.output:JSON.stringify(Y.output),success:!Y.error,executionTimeMs:Y.durationMs}};await N2(H,$);return},afterRun:async({snapshot:X,result:Y})=>{let V={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(Y.status==="completed"){let A={...a1("agent_end",V,$),hookName:"agent_end",iteration:Y.iterations,turn:{outputText:Y.outputText,status:Y.status},taskComplete:{taskMetadata:{}}};await N2(A,$);return}let H=Y.status==="aborted"||Gw(Y.error?.message)?"agent_abort":"agent_error",B=H==="agent_error"?{...a1(H,V,$),hookName:H,iteration:Y.iterations,error:Kw(Y.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...a1(H,V,$),hookName:H,reason:Y.error?.message,taskCancel:{taskMetadata:{}}};await N2(B,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...a1("prompt_submit",Y,$),hookName:"prompt_submit",userPromptSubmit:{prompt:Dw(X.message.content),attachments:[]}};await N2(V,$)}},shutdown:async({agentId:X,conversationId:Y,parentAgentId:V,reason:H})=>{let B={...a1("session_shutdown",{agentId:X,conversationId:Y,parentAgentId:V},$),hookName:"session_shutdown",reason:H};await N2(B,$)}}}var lK={};w(lK,{writeHubDiscovery:()=>d9,withHubStartupLock:()=>l9,verifyHubConnection:()=>G1,truncateNotificationBody:()=>UJ,toHubStatusUrl:()=>PW,toHubHealthUrl:()=>p9,stopLocalHubServerGracefully:()=>gW,startHubWebSocketServer:()=>C2,startHubServer:()=>uK,spawnDetachedHubServerWithRetry:()=>h8,spawnDetachedHubServer:()=>EW,sendHubCommand:()=>cA,restartLocalHubIfIdleAfterStartupTimeout:()=>s9,resolveWorkspaceHubOwnerContext:()=>PB,resolveSharedHubOwnerContext:()=>E0,resolveProductionHubOwnerContext:()=>n0,resolveHubUrl:()=>H3,resolveHubOwnerContext:()=>l1,resolveHubEndpointOptions:()=>i0,resolveHubBuildId:()=>u9,resolveDefaultHubPort:()=>b8,resolveDefaultHubPathname:()=>yW,resolveDefaultHubHost:()=>CW,resolveCompatibleLocalHubUrl:()=>QJ,resolveClineDir:()=>OB,resolveClineDataDir:()=>R2,requestHubShutdown:()=>JJ,rememberRecoverableLocalHubUrl:()=>P$,readHubDiscovery:()=>A0,readBearerToken:()=>FQ,probeHubServer:()=>p1,probeHubConnection:()=>vA,prewarmDetachedHubServer:()=>i9,normalizeHubWebSocketUrl:()=>N$,isHubReconnectableTransportError:()=>IW,isHubCommandTimeoutError:()=>a9,isDiscoveryFilePresent:()=>MB,ensureHubWebSocketServer:()=>DQ,ensureHubServer:()=>dK,ensureDetachedHubServer:()=>EB,ensureCompatibleLocalHubUrl:()=>_2,createLocalHubScheduleRuntimeHandlers:()=>UQ,createInMemoryHubOwnerContext:()=>TB,createHubServerUrl:()=>j1,createHubAuthToken:()=>c9,createConfiguredTelemetryService:()=>s1,createConfiguredTelemetryHandle:()=>e8,connectToHub:()=>VQ,clearHubDiscovery:()=>y0,NodeHubClient:()=>f1,NativeHubTransportAdapter:()=>OJ,HubUIClient:()=>K3,HubTransportError:()=>q0,HubSessionClient:()=>A3,HubServerTransport:()=>J4,HubScheduleService:()=>s8,HubScheduleCommandService:()=>a8,HubCommandError:()=>k8,DEFAULT_HUB_PORT:()=>wW,DEFAULT_HUB_PATHNAME:()=>SW,DEFAULT_HUB_HOST:()=>NW,BrowserWebSocketHubAdapter:()=>_J});import{createSessionId as zw}from"@cline/shared";function a0($,J){return{version:$.version,requestId:$.requestId,ok:!0,payload:J}}function IA($,J,Q){return{version:$.version,requestId:$.requestId??zw("hubreq_"),ok:!1,error:{code:J,message:Q}}}class a8{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return a0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return a0($,{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 a0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return a0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return a0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return a0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return a0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return a0($,{execution:$.payload?.wait===!1?this.schedules.triggerScheduleNowDetached(String($.payload?.scheduleId??"")):await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return a0($,{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 a0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return a0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return a0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return IA($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(J){return IA($,"schedule_command_failed",J instanceof Error?J.message:String(J))}}toCreateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:J}}toUpdateInput($){let J=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:J}}}function XQ($){return $?new Date($).getTime():void 0}function Lw($){let J=$.metadata?{...$.metadata}:void 0;if(J)delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions;return J}function fQ($){let J=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof J?.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:XQ($.nextRunAt),lastRunAt:XQ($.lastRunAt),createdBy:typeof J?.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:J?.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0,metadata:Lw($)}}function _w($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function f3($,J){return{executionId:$.runId,scheduleId:J,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:XQ($.startedAt),endedAt:XQ($.completedAt),status:_w($.status),errorMessage:$.error}}class s8{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a6({dbPath:$.dbPath}),this.materializer=new l6({store:this.store}),this.runner=new p6({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(VW($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return fQ(this.store.createHubSchedule($))}getSchedule($){let J=this.store.getHubSchedule($);return J?fQ(J):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((J)=>fQ(J))}updateSchedule($,J){if(J.cronPattern!==void 0)VW(J.cronPattern);let Q=this.store.getHubSchedule($);if(!Q)return;let Z=J.workspaceRoot!==void 0?J.workspaceRoot.trim():Q.workspaceRoot;if((J.enabled??Q.enabled)&&!Z)throw Error("workspaceRoot is required for enabled schedules");let j=this.store.updateHubSchedule($,{...J,scheduleId:$});return j?fQ(j):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;await this.runner.tick();let Q=this.store.getRun(J.runId)??J;return f3(Q,$)}triggerScheduleNowDetached($){let J=this.store.enqueueHubScheduleRun($,"manual");if(!J)return;return this.runner.tick().catch(()=>{return}),f3(J,$)}listScheduleExecutions($){let J=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,Q={specId:J?.specId,limit:$.limit};return this.store.listRuns(Q).map((W)=>{let j=J??this.store.getSpec(W.specId);if(!j||j.source!=="hub-schedule")return;return f3(W,j.externalId)}).filter((W)=>{if(!W)return!1;return!$.status||W.status===$.status})}getScheduleStats($){let J=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(J.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let Q=0,Z=0,W=0,j;for(let f of J){if(f.status==="success"||f.status==="completed")Q+=1;if(!j&&f.status!=="success"&&f.status!=="completed")j=f;if(f.startedAt&&f.endedAt)W+=f.endedAt-f.startedAt,Z+=1}return{totalRuns:J.length,successRate:Q/J.length,avgDurationSeconds:Z>0?W/Z/1000:0,lastFailure:j}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let J=this.store.getSpec($.specId);if(!J||J.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:J.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:J.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+J.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let J={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(J).flatMap((Q)=>Q.source==="hub-schedule"&&Q.nextRunAt?[{spec:Q,nextRunAt:Q.nextRunAt}]:[]).sort((Q,Z)=>String(Q.nextRunAt).localeCompare(String(Z.nextRunAt))).slice(0,$).map(({spec:Q,nextRunAt:Z})=>({scheduleId:Q.externalId,name:Q.title,nextRunAt:Z}))}}YQ();import{resolveClineBuildEnv as lw}from"@cline/shared";function pw($,J){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(Q?`Failed to connect to hub at ${J} (${Q} event before socket open).`:`Failed to connect to hub at ${J}.`)}var rw="cline-hub-auth.";function iw($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function nw($,J){let Q=new URL($),Z=new URL(J);return Q.search="",Q.hash="",Z.search="",Z.hash="",Q.toString()===Z.toString()}function mA(){return lw()==="production"?n0():E0()}async function aw($){let J=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),J)return J;let Q=mA(),Z=await A0(Q.discoveryPath);if(Z?.url&&nw($.toString(),Z.url))return Z.authToken;return}async function H3($={}){let J=i0($);if(!iw($)){let Q=mA(),Z=await A0(Q.discoveryPath);if(Z?.url)return Z.url}return j1(J.host,J.port,J.pathname)}async function VQ($){return await new Promise((J,Q)=>{(async()=>{let Z=new URL($),W=await aw(Z);Z.hash="";let j=new WebSocket(Z.toString(),W?[`${rw}${W}`]:void 0),f=new Map,X=0;j.addEventListener("open",()=>{J({send(Y){let V=Y.requestId??`hub-client-${++X}`;return new Promise((H,B)=>{f.set(V,{resolve:H,reject:B});let A={kind:"command",envelope:{...Y,requestId:V}};j.send(JSON.stringify(A))})},close(){j.close()}})}),j.addEventListener("message",(Y)=>{let V=JSON.parse(String(Y.data));if(V.kind==="reply"&&V.envelope.requestId){let H=f.get(V.envelope.requestId);if(H)f.delete(V.envelope.requestId),H.resolve(V.envelope)}}),j.addEventListener("close",()=>{for(let Y of f.values())Y.reject(Error("Hub connection closed"));f.clear()}),j.addEventListener("error",(Y)=>{Q(pw(Y,$))})})().catch(Q)})}async function vA($){try{return(await VQ($)).close(),!0}catch{return!1}}async function cA($,J){let Q=await H3($),Z=await VQ(Q);try{return await Z.send({version:J.version??"v1",clientId:J.clientId??"hub-client",...J})}finally{Z.close()}}function B3($){return $?JSON.parse(JSON.stringify($)):{}}function HQ($){let J=$?.session&&typeof $.session==="object"?$.session:void 0;if(!J)return;let Q=J.metadata&&typeof J.metadata==="object"?B3(J.metadata):void 0;return{sessionId:typeof J.sessionId==="string"?J.sessionId:"",parentSessionId:typeof Q?.parentSessionId==="string"?Q.parentSessionId:void 0,messagesPath:typeof Q?.messagesPath==="string"?Q.messagesPath:void 0,metadata:Q}}function uA($,J){return $.error?.message??`hub command failed: ${J}`}function sw($){let J=B3($);if(typeof J.error==="string"&&J.error.trim())return{...J,error:J.error.trim()};let Q=J.result&&typeof J.result==="object"?J.result:void 0;if(typeof Q?.text==="string"&&Q.text.trim())return{...J,error:Q.text.trim()};let Z=Q?.error&&typeof Q.error==="object"?Q.error:void 0;if(typeof Z?.message==="string"&&Z.message.trim())return{...J,error:Z.message.trim()};return J}function dA($){let J=$?.sessionId;return typeof J==="string"&&J.trim()?J.trim():void 0}function ow($){let J=$?.checkpoint;if(!J||typeof J!=="object"||Array.isArray(J))throw Error("hub checkpoint restore returned no checkpoint");let Q=J;if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return Q}function tw($){let J=B3($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||dA(J)||"",eventType:"schedule.execution.completed",payload:J};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||dA(J)||"",eventType:"schedule.execution.failed",payload:J};let Q=$.sessionId?.trim();if(!Q)return;switch($.event){case"iteration.started":return{sessionId:Q,eventType:"runtime.chat.iteration_start",payload:J};case"iteration.finished":return{sessionId:Q,eventType:"runtime.chat.iteration_end",payload:J};case"assistant.delta":return{sessionId:Q,eventType:"runtime.chat.text_delta",payload:J};case"usage.updated":return{sessionId:Q,eventType:"runtime.chat.usage",payload:J};case"tool.started":return{sessionId:Q,eventType:"runtime.chat.tool_call_start",payload:J};case"tool.finished":return{sessionId:Q,eventType:"runtime.chat.tool_call_end",payload:J};case"approval.requested":return{sessionId:Q,eventType:"approval.requested",payload:J};case"run.aborted":return{sessionId:Q,eventType:"runtime.chat.aborted",payload:J};case"run.failed":return{sessionId:Q,eventType:"runtime.chat.failed",payload:sw($.payload)};case"run.completed":return{sessionId:Q,eventType:"runtime.chat.completed",payload:J};default:return}}class A3{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new f1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let J=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),Q=HQ(J.payload);if(!Q?.sessionId)throw Error("hub session create returned no session id");return{sessionId:Q.sessionId,startResult:{sessionId:Q.sessionId,manifestPath:"",messagesPath:Q.messagesPath??""}}}async sendRuntimeSession($,J,Q){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:J.prompt,mode:J.config.mode,attachments:J.attachments,delivery:J.delivery,timeoutSeconds:J.config.timeoutSeconds},$,Q)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let J;try{J=await this.client.command("session.get",void 0,$)}catch(Q){if(d1(Q))return;throw Q}return HQ(J.payload)}async readMessages($){let J=$.trim();if(!J)return[];await this.ensureMetadataApplied();let Q=await this.client.command("session.messages",{sessionId:J},J);if(!Q.ok)throw Error(uA(Q,"session.messages"));let Z=Q.payload?.messages;return Array.isArray(Z)?Z:[]}async restore($){let J=$.sessionId.trim();if(!J)throw Error("sessionId is required");let Q=$.restore?.messages!==!1;if(Q&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Z=$.config,W=await this.client.command("session.restore",{sessionId:J,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Z?{workspaceRoot:Z.workspaceRoot,cwd:Z.cwd,sessionConfig:{providerId:Z.provider,modelId:Z.model,apiKey:Z.apiKey,cwd:Z.cwd??Z.workspaceRoot,workspaceRoot:Z.workspaceRoot,systemPrompt:Z.systemPrompt??"",mode:Z.mode??"act",rules:Z.rules,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawnAgent:Z.enableSpawn!==!1,enableAgentTeams:Z.enableTeams!==!1,disableMcpSettingsTools:Z.disableMcpSettingsTools,missionLogIntervalSteps:Z.missionStepInterval,missionLogIntervalMs:Z.missionTimeIntervalMs},metadata:{source:Z.source??"cli",provider:Z.provider,model:Z.model,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,prompt:void 0,interactive:Z.interactive!==!1},runtimeOptions:{mode:Z.mode,systemPrompt:Z.systemPrompt,maxIterations:Z.maxIterations,enableTools:Z.enableTools,enableSpawn:Z.enableSpawn,enableTeams:Z.enableTeams,autoApproveTools:Z.autoApproveTools,configExtensions:Z.configExtensions},modelSelection:{provider:Z.provider,model:Z.model,apiKey:Z.apiKey},toolPolicies:Z.toolPolicies}:{}},J);if(!W.ok)throw Error(uA(W,"session.restore"));let j=HQ(W.payload);if(Q&&!j?.sessionId)throw Error("hub checkpoint restore returned no session id");let f=Array.isArray(W.payload?.messages)?W.payload.messages:void 0,X=ow(W.payload);return{sessionId:j?.sessionId,startResult:j?.sessionId?{sessionId:j.sessionId,manifestPath:"",messagesPath:j.messagesPath??""}:void 0,...f?{messages:f}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let J=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(J.payload?.sessions)?J.payload?.sessions:[]).map((Z)=>HQ({session:Z})).filter((Z)=>Boolean(Z?.sessionId))}async deleteSession($,J=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:J})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,J){let Q=new Set(($.sessionIds??[]).map((W)=>W.trim()).filter(Boolean)),Z=this.client.subscribe((W)=>{let j=tw(W);if(!j)return;if(Q.size>0&&!Q.has(j.sessionId))return;J.onEvent?.(j)});return this.ensureMetadataApplied().catch((W)=>{J.onError?.(W instanceof Error?W:Error(String(W)))}),Z}streamTeamProgress($,J){let Q=this.client.subscribe((Z)=>{if(Z.event!=="team.progress"||!Z.payload)return;J.onProjection?.(Z.payload)});return this.ensureMetadataApplied().catch((Z)=>{J.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list");return Array.isArray(J.payload?.schedules)?J.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,J){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...J})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,J){await this.ensureMetadataApplied();let Q=await this.client.command("schedule.list_executions",{scheduleId:$,limit:J});return Array.isArray(Q.payload?.executions)?Q.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let J=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(J.payload?.upcoming)?J.payload?.upcoming:[]}}class K3{client;constructor($){this.client=new f1({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let J=await this.client.command("session.list",{limit:$});return Array.isArray(J.payload?.sessions)?J.payload.sessions:[]}subscribeUI($){return this.client.subscribe((J)=>{switch(J.event){case"ui.notify":$.onNotify?.(J.payload);break;case"ui.show_window":$.onShowWindow?.(J.payload);break;case"hub.client.registered":$.onClientRegistered?.(J.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(J.payload??{});break;case"session.created":$.onSessionCreated?.(J.payload??{});break;case"session.updated":$.onSessionUpdated?.(J.payload??{});break;case"session.detached":$.onSessionDetached?.(J.payload??{});break}})}}import{resolveClineBuildEnv as vK}from"@cline/shared";function ew($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((Q)=>{if(Q&&typeof Q==="object"&&"type"in Q&&Q.type==="text"&&"text"in Q&&typeof Q.text==="string")return Q.text.trim();return""}).filter(Boolean).join(`
570
+ `).trim()||void 0}var lA=120,G3="...";function UJ($){let J=$.trim();if(!J)return"";if(Buffer.byteLength(J,"utf8")<=lA)return J;let Q=lA-Buffer.byteLength(G3,"utf8");if(Q<=0)return G3;let Z="";for(let W of J){if(Buffer.byteLength(Z+W,"utf8")>Q)break;Z+=W}return`${Z}${G3}`}async function pA($){let J=$?.sessionId?.trim()||"unknown",Q=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,W=[...await q$(Q)].reverse().find((Y)=>Y.role==="assistant"),j=W?ew(W.content):void 0,f=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():f;return{title:`Task completed (${J})`,body:UJ(j&&j.length>0?j:X.length>0?X:f),severity:"info"}}import{captureSdkError as GQ,createSessionId as ES}from"@cline/shared";import{createSessionId as ZS}from"@cline/shared";import{createSessionId as QS}from"@cline/shared";function $S($){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 JS($){let J=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())J.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())J.parentAgentId=$.parentAgentId;if($.agentId?.trim())J.agentId=$.agentId;if($.conversationId?.trim())J.conversationId=$.conversationId;if($.messagesPath?.trim())J.messagesPath=$.messagesPath;if($.prompt?.trim())J.prompt=$.prompt;if($.provider?.trim())J.provider=$.provider;if($.model?.trim())J.model=$.model;if($.source?.trim())J.source=$.source;if(typeof $.pid==="number")J.pid=$.pid;return Object.keys(J).length>0?J:void 0}function BQ($,J,Q,Z){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:J?.createdByClientId??"hub",status:$S($.status),participants:J?[...J.participants.values()]:[],metadata:JS($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...Q?{usage:{...Q}}:{},...Z?{aggregateUsage:{...Z}}:{}}}function l($,J){return{version:$.version,requestId:$.requestId,ok:!0,...J!==void 0?{payload:J}:{}}}function v($,J,Q){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:J,message:Q}}}function AQ($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function h0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function w2($,J,Q){return{version:"v1",event:$,eventId:QS("hevt_"),sessionId:Q,timestamp:Date.now(),payload:J}}async function s0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let Z=await $.sessionHost.getAccumulatedUsage?.(J);return BQ(Q,$.sessionState.get(J),Z?.usage,Z?.aggregateUsage)}async function o0($,J){let Q=await $.sessionHost.getSession(J);if(!Q)return;let[Z,W]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(J):[],$.sessionHost.getAccumulatedUsage?.(J)]);return F1({session:Q,messages:Z,usage:W?.usage,aggregateUsage:W?.aggregateUsage})}function KQ($,J,Q,Z,W={}){let j=$.sessionState.get(J);if(j){if(W.interactive!==void 0)j.interactive=W.interactive;if(!j.participants.has(Q))j.participants.set(Q,{clientId:Q,attachedAt:Date.now(),role:Z});return j}let f={createdByClientId:Q,interactive:W.interactive??!0,participants:new Map([[Q,{clientId:Q,attachedAt:Date.now(),role:Z}]])};return $.sessionState.set(J,f),f}async function F3($,J){let Q=ZS("approval_"),Z=J.sessionId;if($.sessionState.get(Z)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((j)=>{$.pendingApprovals.set(Q,{sessionId:Z,resolve:j}),$.publish($.buildEvent("approval.requested",{approvalId:Q,sessionId:J.sessionId,agentId:J.agentId,conversationId:J.conversationId,iteration:J.iteration,toolCallId:J.toolCallId,toolName:J.toolName,inputJson:JSON.stringify(J.input??null),policy:J.policy},Z))})}function D3($,J,Q){let Z=$.pendingApprovals.get(J);if(!Z)return;return $.pendingApprovals.delete(J),Z.resolve(Q),{sessionId:Z.sessionId}}function U3($,J,Q){let Z=0;for(let[W,j]of[...$.pendingApprovals.entries()]){if(!J({approvalId:W,sessionId:j.sessionId}))continue;$.pendingApprovals.delete(W),j.resolve({approved:!1,reason:Q}),$.publish($.buildEvent("approval.resolved",{approvalId:W,approved:!1,cancelled:!0,reason:Q},j.sessionId)),Z+=1}return Z}async function rA($,J){let Q=typeof J.payload?.approvalId==="string"?J.payload.approvalId.trim():"";if(!$.pendingApprovals.get(Q))return v(J,"approval_not_found",`Unknown approval: ${Q}`);let W=typeof J.payload?.reason==="string"?J.payload.reason:J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)&&typeof J.payload.payload.reason==="string"?J.payload.payload.reason:void 0,j=J.payload?.approved===!0,f=D3($,Q,{approved:j,reason:W});if(!f)return v(J,"approval_not_found",`Unknown approval: ${Q}`);return $.publish($.buildEvent("approval.resolved",{approvalId:Q,approved:j,reason:W},f.sessionId)),l(J,{approvalId:Q,approved:j})}import{createSessionId as fS}from"@cline/shared";function WS($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var iA={debug:10,info:20,warn:30,error:40,silent:50};function jS(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function c($,J,Q={}){if(iA[$]<iA[jS()])return;let Z=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:J,...Object.fromEntries(Object.entries(Q).map(([W,j])=>[W,WS(j)]).filter(([,W])=>W!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Z}`);return}console.log(`[hub] ${Z}`)}function R3($,J){let Q=J instanceof Error?J.stack||J.message:String(J);c("error",$,{error:Q})}async function nA($,J,Q,Z,W,j){let f=fS("capreq_"),X=performance.now();return c("info","capability.request.start",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W}),await new Promise((Y,V)=>{$.pendingCapabilityRequests.set(f,{sessionId:J,targetClientId:W,capabilityName:Q,onProgress:j,resolve:(H)=>{if(c(H.ok?"info":"warn","capability.request.end",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W,ok:H.ok,error:H.error,durationMs:Math.round(performance.now()-X)}),!H.ok){V(Error(H.error||`Capability ${Q} was rejected by ${W}.`));return}Y(H.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:f,targetClientId:W,capabilityName:Q,payload:Z},J)),c("info","capability.request.published",{requestId:f,sessionId:J,capabilityName:Q,targetClientId:W})})}function aA($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);if((J.clientId?.trim()||"")!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{};return Z.onProgress?.(j),l(J,{requestId:Q})}function C$($,J,Q){let Z=0;for(let[W,j]of[...$.pendingCapabilityRequests.entries()]){if(!J({requestId:W,...j}))continue;$.pendingCapabilityRequests.delete(W),c("warn","capability.request.cancelled",{requestId:W,sessionId:j.sessionId,capabilityName:j.capabilityName,targetClientId:j.targetClientId,reason:Q}),j.resolve({ok:!1,error:Q}),$.publish($.buildEvent("capability.resolved",{requestId:W,capabilityName:j.capabilityName,targetClientId:j.targetClientId,ok:!1,cancelled:!0,error:Q},j.sessionId)),Z+=1}return Z}async function sA($,J){let Q=typeof J.payload?.sessionId==="string"?J.payload.sessionId.trim():J.sessionId?.trim()||"",Z=typeof J.payload?.capabilityName==="string"?J.payload.capabilityName.trim():"",W=typeof J.payload?.targetClientId==="string"?J.payload.targetClientId.trim():"";if(!Q||!Z||!W)return v(J,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:{},f=await $.requestCapability(Q,Z,j,W);return l(J,f)}catch(j){return v(J,"capability_request_failed",j instanceof Error?j.message:String(j))}}function oA($,J){let Q=typeof J.payload?.requestId==="string"?J.payload.requestId.trim():"",Z=$.pendingCapabilityRequests.get(Q);if(!Z)return v(J,"capability_not_found",`Unknown capability request: ${Q}`);let W=J.clientId?.trim()||"";if(W!==Z.targetClientId)return v(J,"capability_wrong_client",`Capability request ${Q} is owned by ${Z.targetClientId}`);if(J.sessionId?.trim()&&J.sessionId.trim()!==Z.sessionId)return v(J,"capability_wrong_session",`Capability request ${Q} belongs to session ${Z.sessionId}`);$.pendingCapabilityRequests.delete(Q);let j=J.payload?.payload&&typeof J.payload.payload==="object"&&!Array.isArray(J.payload.payload)?J.payload.payload:void 0,f=typeof J.payload?.error==="string"?J.payload.error:void 0,X=J.payload?.ok===!0;return c(X?"info":"warn","capability.respond",{requestId:Q,sessionId:Z.sessionId,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,error:f}),Z.resolve({ok:X,payload:j,error:f}),$.publish($.buildEvent("capability.resolved",{requestId:Q,capabilityName:Z.capabilityName,targetClientId:Z.targetClientId,respondedByClientId:W,ok:X,payload:j,error:f},Z.sessionId)),l(J,{requestId:Q,ok:X})}import{createSessionId as XS}from"@cline/shared";function tA($,J){let Q=J.payload,Z=Q?.clientId?.trim()||J.clientId?.trim()||XS("client_");return $.clients.set(Z,{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,actorKind:Q?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:Q?.transport??"native",capabilities:Q?.capabilities??[],metadata:Q?.metadata,workspaceContext:Q?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Z,clientType:Q?.clientType??"unknown",displayName:Q?.displayName,connectedAt:Date.now()})),l(J,{clientId:Z})}function eA($,J){let Q=J.clientId?.trim(),Z=Q?$.clients.get(Q):void 0;if(!Q||!Z)return v(J,"client_not_found","Client is not registered with this hub.");let W=AQ(J.payload?.metadata);if(Z.lastSeenAt=Date.now(),W)Z.metadata=JSON.parse(JSON.stringify(W));return l(J)}function $K($,J,Q){let Z=J.clientId?.trim();if(Z)$.clients.delete(Z),Q(Z),$.publish($.buildEvent("hub.client.disconnected",{clientId:Z}));return l(J)}function JK($,J){return l(J,{clients:[...$.clients.values()]})}var YS=30000;function VS($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function HS($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function BS($,J,Q){let Z=Q instanceof Error&&Q.message.trim()?Q.message:`Unknown session: ${J}`;return v($,G2,Z)}function AS($){return $?$:void 0}function KS($){let J=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J);let Q=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(Q&&Number.isFinite(Q)&&Q>0)return Math.floor(Q*1000);return}async function GS($,J,Q,Z){let W=performance.now(),j=!1,f={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q.sessionId,timeoutMs:Z},X=setInterval(()=>{if(j)return;let H=Math.round(performance.now()-W);c("warn","run.heartbeat",{...f,elapsedMs:H}),$.publish($.buildEvent("run.heartbeat",{requestId:J.requestId,elapsedMs:H,...Z?{timeoutMs:Z}:{}},Q.sessionId))},YS),Y=$.sessionHost.runTurn(Q);Y.then((H)=>{if(!j)return;c("warn","run.late_end",{...f,elapsedMs:Math.round(performance.now()-W),finishReason:H?.finishReason})},(H)=>{if(!j)return;c("error","run.late_error",{...f,elapsedMs:Math.round(performance.now()-W),error:H})});let V;try{if(!Z)return await Y;return await Promise.race([Y,new Promise((H,B)=>{V=setTimeout(()=>{let A=`Hub run ${J.command} timed out after ${Z}ms.`;j=!0,clearInterval(X),B(Error(A)),c("error","run.timeout",{...f,elapsedMs:Math.round(performance.now()-W)}),U3($,(K)=>K.sessionId===Q.sessionId,A),C$($,(K)=>K.sessionId===Q.sessionId,A),$.sessionHost.abort(Q.sessionId,A).catch((K)=>{c("error","run.timeout_abort_failed",{...f,error:K})})},Z)})])}finally{if(j=!0,clearInterval(X),V)clearTimeout(V)}}async function QK($,J){let Q=h0(J),Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.prompt==="string"?Z.prompt:typeof Z.input==="string"?Z.input:"";if(!W.trim())return v(J,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,Q));let j=Z.attachments&&typeof Z.attachments==="object"&&!Array.isArray(Z.attachments)?Z.attachments:void 0,f=Array.isArray(j?.userFiles)?j.userFiles.filter((H)=>typeof H==="string"):void 0,X=KS(Z);$.suppressNextTerminalEventBySession.set(Q,"run.start.reply");let Y;try{Y=await GS($,J,{sessionId:Q,prompt:W,mode:AS(Z.mode),delivery:Z.delivery==="queue"||Z.delivery==="steer"?Z.delivery:void 0,userImages:Array.isArray(j?.userImages)?j.userImages:void 0,userFiles:f,timeoutMs:X},X)}catch(H){if($.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q);if(d1(H))return BS(J,Q,H);throw $.publish($.buildEvent("run.failed",{reason:"error",error:H instanceof Error?H.message:String(H)},Q)),H}if(Y){let H=await o0($,Q),B=HS(Y);if($.publish($.buildEvent(VS(Y.finishReason),{reason:Y.finishReason,...B?{error:B}:{},result:Y,...H?{snapshot:H}:{}},Q)),$.suppressNextTerminalEventBySession.get(Q)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(Q)}else $.suppressNextTerminalEventBySession.delete(Q);let V=await o0($,Q);return l(J,Y||V?{...Y?{result:Y}:{},...V?{snapshot:V}:{}}:void 0)}async function ZK($,J){let Q=h0(J),Z=typeof J.payload?.reason==="string"?J.payload.reason:"Run was aborted before pending approval or capability request was resolved.";U3($,(W)=>W.sessionId===Q,Z);try{await $.sessionHost.abort(Q,J.payload?.reason)}catch(W){c("warn","run.abort_failed",{command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:Q,error:W})}finally{C$($,(W)=>W.sessionId===Q,Z)}return l(J,{applied:!0})}async function WK($,J){let Q=i8(J.payload?.payload);if(!Q)return v(J,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(Q),l(J,{applied:!0})}async function jK($,J){switch(J.type){case"chunk":return;case"agent_event":await FS($,J);return;case"hook":if(J.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:J.payload.toolName},J.payload.sessionId));else if(J.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:J.payload.toolName},J.payload.sessionId));return;case"team_progress":{let Q={type:"team_progress_projection",version:1,sessionId:J.payload.sessionId,summary:J.payload.summary,lastEvent:J.payload.lifecycle};$.publish($.buildEvent("team.progress",Q,J.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:J.payload.sessionId,prompts:J.payload.prompts},J.payload.sessionId));return;case"pending_prompt_submitted":{let Q={id:J.payload.id,prompt:J.payload.prompt,delivery:J.payload.delivery,attachmentCount:J.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:J.payload.sessionId,prompt:Q},J.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:J.payload.sessionId,snapshot:J.payload.snapshot},J.payload.sessionId));return;case"status":{let[Q,Z]=await Promise.all([s0($,J.payload.sessionId),o0($,J.payload.sessionId)]);if(Q)$.publish($.buildEvent("session.updated",{session:Q,...Z?{snapshot:Z}:{}},J.payload.sessionId));return}case"ended":await DS($,J);return;default:return}}async function FS($,J){let{sessionId:Q,event:Z}=J.payload;if(Z.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Z.iteration},Q));return}if(Z.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Z.iteration,hadToolCalls:Z.hadToolCalls,toolCallCount:Z.toolCallCount},Q));return}if(Z.type==="content_start"){if(Z.contentType==="text"&&typeof Z.text==="string"&&Z.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Z.text},Q));return}if(Z.contentType==="reasoning"){if(Z.redacted&&!Z.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},Q));return}if(typeof Z.reasoning==="string"&&Z.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Z.reasoning,redacted:Z.redacted===!0},Q));return}if(Z.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Z.toolCallId,toolName:Z.toolName,input:Z.input},Q));return}}if(Z.type==="content_end"){switch(Z.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Z.text},Q));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Z.reasoning},Q));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Z.toolCallId,toolName:Z.toolName,output:Z.output,error:Z.error},Q));break}return}if(Z.type==="usage"){let W;try{W=await $.sessionHost.getAccumulatedUsage?.(Q)}catch{W=void 0}$.publish($.buildEvent("usage.updated",{sessionId:Q,delta:{inputTokens:Z.inputTokens,outputTokens:Z.outputTokens,cacheReadTokens:Z.cacheReadTokens??0,cacheWriteTokens:Z.cacheWriteTokens??0,totalCost:Z.cost??0},totals:{inputTokens:Z.totalInputTokens,outputTokens:Z.totalOutputTokens,cacheReadTokens:Z.totalCacheReadTokens??0,cacheWriteTokens:Z.totalCacheWriteTokens??0,totalCost:Z.totalCost??0},usage:W?.usage,aggregateUsage:W?.aggregateUsage,agent:{kind:J.payload.teamRole==="teammate"?"teammate":Z.parentAgentId?"subagent":"lead",agentId:Z.agentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamAgentId:J.payload.teamAgentId,teamRole:J.payload.teamRole}},Q));return}if(Z.type==="done")$.publish($.buildEvent("agent.done",{reason:Z.reason,text:Z.text,iterations:Z.iterations,usage:Z.usage},Q))}async function DS($,J){let Q=$.suppressNextTerminalEventBySession.get(J.payload.sessionId),Z=Q===J.payload.reason||Q==="run.start.reply";if(Z)$.suppressNextTerminalEventBySession.delete(J.payload.sessionId);let[W,j]=await Promise.all([s0($,J.payload.sessionId),o0($,J.payload.sessionId)]);if(J.payload.reason==="completed"){let f=await pA(W);$.publish($.buildEvent("ui.notify",f,J.payload.sessionId))}if(Z)return;$.publish($.buildEvent(J.payload.reason==="aborted"?"run.aborted":J.payload.reason==="error"||J.payload.reason==="failed"?"run.failed":"run.completed",{reason:J.payload.reason,...j?{snapshot:j}:{}},J.payload.sessionId))}import{createSessionId as AK,parseRuntimeConfigExtensions as KK}from"@cline/shared";var VK={};w(VK,{SessionVersioningService:()=>y$,SessionVersioningError:()=>k0});var YK={};w(YK,{trimMessagesToCheckpoint:()=>XK,trimMessagesBeforeCheckpoint:()=>L3,readSessionCheckpointHistory:()=>RJ,createRestoredCheckpointMetadata:()=>z3,createCheckpointRestorePlan:()=>_3,applyCheckpointToWorktree:()=>O3});import{execFile as US}from"node:child_process";import{promisify as RS}from"node:util";var $4=RS(US);function RJ($){let J=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(J?.history)?J.history:[]).filter((Z)=>!!Z&&typeof Z==="object"&&!Array.isArray(Z)).flatMap((Z)=>{let W=String(Z.ref??"").trim(),j=Number(Z.createdAt??0),f=Number(Z.runCount??0);if(W.length===0||!Number.isFinite(j)||!Number.isInteger(f)||f<1)return[];let X=Z.kind==="stash"||Z.kind==="commit"?Z.kind:void 0;return[{ref:W,createdAt:j,runCount:f,...X?{kind:X}:{}}]})}function z3($,J){let Q=RJ($).filter((W)=>W.runCount<=J),Z=Q.at(-1);return Z?{latest:Z,history:Q}:void 0}function zS($,J){return $.reduce((Q,Z)=>{if(Z.runCount>J)return Q;if(!Q||Z.runCount>Q.runCount)return Z;return Q},void 0)}function fK($,J){let Q=0;for(let Z=0;Z<$.length;Z+=1){let W=$[Z];if(W?.role!=="user")continue;if(("metadata"in W&&W.metadata&&typeof W.metadata==="object"?W.metadata:void 0)?.kind==="recovery_notice")continue;if(Q+=1,Q===J)return Z}throw Error(`Could not find user message for checkpoint run ${J}`)}function XK($,J){let Q=fK($,J);return $.slice(0,Q+1)}function L3($,J){let Q=fK($,J);return $.slice(0,Q)}function _3($){let J=$.checkpointRunCount;if(!Number.isInteger(J)||J<1)throw Error("checkpointRunCount must be a positive integer");let Q=zS(RJ($.session),J);if(!Q)throw Error(`No checkpoint found at or before run ${J} in session ${$.session.sessionId}`);let Z=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Z)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:Q,cwd:Z,...$.restoreMessages!==!1?{messages:XK($.messages??[],J)}:{}}}async function O3($,J){if((await $4("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await $4("git",["-C",$,"cat-file","-e",`${J.ref}^{commit}`],{windowsHide:!0}),await $4("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await $4("git",["-C",$,"clean","-fd"],{windowsHide:!0}),J.kind==="commit"){await $4("git",["-C",$,"reset","--hard",J.ref],{windowsHide:!0});return}await $4("git",["-C",$,"stash","apply",J.ref],{windowsHide:!0})}class k0 extends Error{code;constructor($,J){super(J);this.code=$;this.name="SessionVersioningError"}}function LS($){let J=$.sessionId.trim();if(!J)throw new k0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new k0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new k0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new k0("invalid_restore","checkpointRunCount must be a positive integer");return J}class y${async restoreCheckpoint($){let J=$.restore?.messages!==!1,Q=$.restore?.workspace!==!1,Z=LS({sessionId:$.sessionId,restoreMessages:J,restoreWorkspace:Q,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),W=await $.getSession(Z);if(!W)throw new k0("session_not_found",`Session ${Z} not found`);let j=J?await $.readMessages(Z):void 0;if(J&&j?.length===0)throw new k0("session_messages_not_found",`No messages found for session ${Z}`);let f=_3({session:W,messages:j,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:J});if(Q)await($.applyWorkspaceCheckpoint??O3)(f.cwd,f.checkpoint);let X=F1({session:W,messages:j});if(!J)return{checkpoint:f.checkpoint,sourceSnapshot:X};let Y=z3(W,$.checkpointRunCount),V=$.restore?.omitCheckpointMessageFromSession?L3(j??[],$.checkpointRunCount):f.messages??[],H={sourceSession:W,sourceMessages:j,sourceSnapshot:X,plan:f,restoredCheckpointMetadata:Y,initialMessages:V,restoreMessages:J,restoreWorkspace:Q,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new k0("invalid_restore","start is required when restore.messages is true");let B=$.buildStartInput?await $.buildStartInput(H,$.start):$.start,A=await $.startSession(B),K=$.getStartedSessionId?.(A);if(K)await($.retainCheckpointRefs??VV)(f.cwd,K,Y?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:A,messages:f.messages,checkpoint:f.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:F1({session:G,messages:V})}:{}}}}import{HUB_CHECKPOINT_CAPABILITY as bp,HUB_COMPACTION_CAPABILITY as hp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as kp,HUB_HOOK_CAPABILITY_PREFIX as Ip,HUB_MISTAKE_LIMIT_CAPABILITY as xp,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as gp,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as mp,isHubToolExecutorName as _S}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as lp,HUB_COMPACTION_CAPABILITY as pp,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as rp,HUB_HOOK_CAPABILITY_PREFIX as ip,HUB_MISTAKE_LIMIT_CAPABILITY as np,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as ap,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as sp}from"@cline/shared";var OS=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function S2($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function TS($,J){let Q=typeof $.name==="string"?$.name.trim():"",Z=typeof $.description==="string"?$.description:"",W=typeof $.capabilityName==="string"?$.capabilityName.trim():"",j=S2($.inputSchema);if(!Q||!Z||!j||!W||J.has(W))return;return J.add(W),{kind:"tool",capabilityName:W,name:Q,description:Z,inputSchema:j,...S2($.lifecycle)?{lifecycle:S2($.lifecycle)}:{}}}function M3($){if(!Array.isArray($))return[];let J=[],Q=new Set;for(let Z of $){if(!Z||typeof Z!=="object"||Array.isArray(Z))continue;let W=Z,j=W.kind,f=typeof W.capabilityName==="string"?W.capabilityName.trim():"";if(!f||Q.has(f))continue;if(j==="tool"){let X=TS(W,Q);if(X)J.push(X);continue}if(j==="toolExecutor"){let X=W.executor;if(!_S(X))continue;Q.add(f),J.push({kind:"toolExecutor",capabilityName:f,executor:X});continue}if(j==="hook"){let X=typeof W.name==="string"?W.name.trim():"";if(!X)continue;Q.add(f),J.push({kind:"hook",capabilityName:f,name:X});continue}if(j==="compaction"){Q.add(f),J.push({kind:"compaction",capabilityName:f,...S2(W.config)?{config:S2(W.config)}:{}});continue}if(j==="checkpoint"){Q.add(f),J.push({kind:"checkpoint",capabilityName:f,...S2(W.config)?{config:S2(W.config)}:{}});continue}if(j==="mistakeLimit"){Q.add(f),J.push({kind:"mistakeLimit",capabilityName:f});continue}if(j==="userInstructionService")Q.add(f),J.push({kind:"userInstructionService",capabilityName:f})}return J}function BK($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function MS($){return Object.hasOwn($,"update")?$.update:$}function zJ($){return $.trim().replace(/^\/+/,"").toLowerCase()}function qS($){let J=($??[]).map(zJ).filter(Boolean);return J.length>0?new Set(J):void 0}function PS($,J,Q){if(!Q)return!0;let Z=zJ($),W=zJ(J),j=Z.includes(":")?Z.split(":").at(-1)??Z:Z,f=W.includes(":")?W.split(":").at(-1)??W:W;return Q.has(Z)||Q.has(W)||Q.has(j)||Q.has(f)}function T3($,J){let Q=qS(J);return $.records.skill.map((Z)=>({id:Z.id,name:Z.item.name,description:"description"in Z.item&&typeof Z.item.description==="string"?Z.item.description:void 0,disabled:Z.item.disabled===!0,skill:Z.item})).filter((Z)=>PS(Z.id,Z.name,Q))}function HK($,J){let Q=async(Z,W)=>{let j=zJ(Z),X=T3($,J).filter((A)=>A.id===j||zJ(A.name)===j||A.id.endsWith(`:${j}`)).filter((A)=>!A.disabled);if(X.length!==1)return X.length>1?`Skill "${Z}" is ambiguous. Use one of: ${X.map((A)=>A.id).join(", ")}`:`Skill "${Z}" not found.`;let Y=X[0].skill,V=W?.trim(),H=V?`
571
571
  <command-args>${V}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
572
572
 
573
573
  `:"";return`<command-name>${Y.name}</command-name>${H}
574
574
  <command-instructions>
575
575
  ${B}${Y.instructions}
576
- </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>T3($,J).map(({skill:Z,...W})=>W),enumerable:!0}),Q}function NS($,J,Q,Z){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let f=await Z($,Q.capabilityName,{},J);if(f?.snapshot)W=f.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(f)=>[...W.records[f]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(f)=>{if(!f.startsWith("/")||f.length<2)return f;let Y=f.match(/^\/(\S+)/)?.[1];if(!Y)return f;let V=W.runtimeCommands.find((H)=>H.name===Y);return V?`${V.instructions}${f.slice(Y.length+1)}`:f},hasConfiguredSkills:(f)=>T3(W,f).some((X)=>!X.disabled),createSkillsExecutor:(f)=>BK(W,f),createExtension:(f)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(f.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>P8(W.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(f.registerSkillsTool)X.registerTool(v$(BK(W,f.allowedSkillNames)));for(let Y of W.runtimeCommands.filter((V)=>V.kind==="skill"&&f.includeSkills||V.kind==="workflow"&&f.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let H=V.trim();return H?`${Y.instructions}
576
+ </command-instructions>`};return Object.defineProperty(Q,"configuredSkills",{get:()=>T3($,J).map(({skill:Z,...W})=>W),enumerable:!0}),Q}function NS($,J,Q,Z){let W={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},j=async()=>{let f=await Z($,Q.capabilityName,{},J);if(f?.snapshot)W=f.snapshot};return{start:j,stop:()=>{},refreshType:async()=>{await j()},listRecords:(f)=>[...W.records[f]],listRuntimeCommands:()=>[...W.runtimeCommands],resolveRuntimeSlashCommand:(f)=>{if(!f.startsWith("/")||f.length<2)return f;let Y=f.match(/^\/(\S+)/)?.[1];if(!Y)return f;let V=W.runtimeCommands.find((H)=>H.name===Y);return V?`${V.instructions}${f.slice(Y.length+1)}`:f},hasConfiguredSkills:(f)=>T3(W,f).some((X)=>!X.disabled),createSkillsExecutor:(f)=>HK(W,f),createExtension:(f)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[f.includeRules?"rules":void 0,f.registerSkillsTool?"tools":void 0,f.includeSkills||f.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(f.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>P8(W.records.rule.map((Y)=>Y.item).filter((Y)=>Y.disabled!==!0))});if(f.registerSkillsTool)X.registerTool(v$(HK(W,f.allowedSkillNames)));for(let Y of W.runtimeCommands.filter((V)=>V.kind==="skill"&&f.includeSkills||V.kind==="workflow"&&f.includeWorkflows))X.registerCommand({name:Y.name,description:Y.description,handler:(V)=>{let H=V.trim();return H?`${Y.instructions}
577
577
 
578
- ${H}`:Y.instructions}})}})}}function wS($,J,Q,Z){let W=Q.map((j)=>[j.executor,async(...f)=>{let X=f.at(-1),Y=f.slice(0,-1);return(await Z($,j.capabilityName,{executor:j.executor,args:Y,context:AK(X)},J))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function SS($,J,Q,Z){if(Q.length===0)return;return Q.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(j,f){return(await Z($,W.capabilityName,{toolName:W.name,input:j,context:AK(f)},J,f.emitUpdate?(Y)=>{f.emitUpdate?.(MS(Y))}:void 0))?.result}}))}function CS($,J,Q,Z){let W=new Map(Q.map((f)=>[f.name,f])),j={};for(let f of OS){let X=W.get(f);if(!X)continue;j[f]=async(Y)=>{return(await Z($,X.capabilityName,{context:Y},J))?.control}}return Object.keys(j).length>0?j:void 0}function q3($){let J=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),Q=$.contributions.filter((Y)=>Y.kind==="tool"),Z=$.contributions.filter((Y)=>Y.kind==="hook"),W=$.contributions.find((Y)=>Y.kind==="compaction"),j=$.contributions.find((Y)=>Y.kind==="checkpoint"),f=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:wS($.sessionId,$.targetClientId,J,$.requestCapability),localRuntime:{...Z.length>0?{hooks:CS($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...Q.length>0?{extraTools:SS($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...W?{compaction:{...$.sessionConfig?.compaction??{},...W.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...f?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,f.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:NS($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var FK="hubCapabilityOwnerClientId";function DK($,J){$[FK]=J}function yS($){let J=$?.[FK];return typeof J==="string"&&J.trim()?J.trim():void 0}async function UK($,J,Q){let Z=performance.now(),W={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:J.sessionId};c("info","session.create.begin",W);let j=J.payload&&typeof J.payload==="object"?J.payload:{},f=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},X=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,Y=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{};if(typeof X?.mode==="string")f.mode=X.mode;else if(typeof Y.mode==="string")f.mode=Y.mode;if(typeof X?.systemPrompt==="string")f.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")f.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)f.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)f.checkpointEnabled=!0;let V=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},H=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!H)return c("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),v(J,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=J.clientId?.trim()||"hub-client",A=M3(Y.clientContributions);if(c("info","session.create.contributions_parsed",{...W,clientId:B,workspaceRoot:H,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:A.length}),A.length>0)DK(f,B);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||KK(),R=GK(Y.configExtensions);c("info","session.create.runtime_build.begin",{...W,sessionId:G,configExtensionCount:R?.length??0});let D=q3({sessionId:G,targetClientId:B,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});c("info","session.create.start_session.begin",{...W,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub")});let U=await $.sessionHost.startSession({source:typeof f.source==="string"?f.source:void 0,interactive:f.interactive!==!1,sessionMetadata:Object.keys(f).length>0?f:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():H),workspaceRoot:X?.workspaceRoot??H,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof f.teamName==="string"?f.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z),hasImmediateResult:!!U.result}),K9($,U.sessionId,B,"creator",{interactive:f.interactive!==!1}),c("info","session.create.read_records.begin",{...W,sessionId:U.sessionId});let[F,O]=await Promise.all([s0($,U.sessionId),o0($,U.sessionId)]);if(c("info","session.create.read_records.end",{...W,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Z)}),F)$.publish($.buildEvent("session.created",{session:F,...O?{snapshot:O}:{}},U.sessionId));return c("info","session.create.reply",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z)}),l(J,{session:F,...O?{snapshot:O}:{}})}async function RK($,J,Q){let Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.sessionId==="string"?Z.sessionId.trim():J.sessionId?.trim()||"",j=Z.checkpointRunCount;if(!W)return v(J,"invalid_restore","session.restore requires a session id");let f=Z.restore&&typeof Z.restore==="object"?Z.restore:{},X=f.messages!==!1;if(typeof j!=="number")return v(J,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Z.sessionConfig&&typeof Z.sessionConfig==="object"?JSON.parse(JSON.stringify(Z.sessionConfig)):void 0;if(X&&!Y)return v(J,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Z.runtimeOptions&&typeof Z.runtimeOptions==="object"?Z.runtimeOptions:{},H=Z.metadata&&typeof Z.metadata==="object"?JSON.parse(JSON.stringify(Z.metadata)):{};if(typeof Y?.mode==="string")H.mode=Y.mode;else if(typeof V.mode==="string")H.mode=V.mode;if(typeof Y?.systemPrompt==="string")H.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")H.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)H.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)H.checkpointEnabled=!0;let B=Z.modelSelection&&typeof Z.modelSelection==="object"?Z.modelSelection:{},A=J.clientId?.trim()||"hub-client",K=M3(V.clientContributions);if(K.length>0)DK(H,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||KK(),D=GK(V.configExtensions),U=q3({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),O=await new y$().restoreCheckpoint({sessionId:W,checkpointRunCount:j,restore:{messages:f.messages,workspace:f.workspace,omitCheckpointMessageFromSession:f.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(P)=>$.sessionHost.getSession(P),readMessages:(P)=>$.sessionHost.readSessionMessages(P),buildStartInput:(P)=>{if(P.restoredCheckpointMetadata)H.checkpoint=P.restoredCheckpointMetadata;let S=typeof Z.workspaceRoot==="string"&&Z.workspaceRoot.trim()?Z.workspaceRoot.trim():typeof Z.cwd==="string"&&Z.cwd.trim()?Z.cwd.trim():P.sourceSession.workspaceRoot||P.sourceSession.cwd;return{source:typeof H.source==="string"?H.source:void 0,interactive:H.interactive!==!1,sessionMetadata:{...H,restoredFromSessionId:W,restoredCheckpointRunCount:j},initialMessages:P.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:Q},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof B.provider==="string"?B.provider:P.sourceSession.provider),modelId:Y?.modelId??(typeof B.model==="string"?B.model:P.sourceSession.model),apiKey:Y?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:Y?.cwd??P.plan.cwd,workspaceRoot:Y?.workspaceRoot??S,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof H.teamName==="string"?H.teamName:void 0)},toolPolicies:Z.toolPolicies&&typeof Z.toolPolicies==="object"&&!Array.isArray(Z.toolPolicies)?JSON.parse(JSON.stringify(Z.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(P)=>$.sessionHost.startSession(P),getStartedSessionId:(P)=>P.sessionId,readRestoredSession:(P)=>$.sessionHost.getSession(P)});if(!X)return l(J,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return v(J,"restore_failed","Checkpoint restore did not start a session");K9($,T.sessionId,A,"creator",{interactive:H.interactive!==!1});let[L,z]=await Promise.all([s0($,T.sessionId),o0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},T.sessionId));return l(J,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(Y){if(Y instanceof k0)return v(J,Y.code,Y.code==="session_not_found"?`Unknown session: ${W}`:Y.message);return v(J,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function zK($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_attach","session.attach requires a session id");K9($,Q,J.clientId?.trim()||"hub-client","participant");let Z=await s0($,Q);if(Z)$.publish($.buildEvent("session.attached",{session:Z},Q));return Z?l(J,{session:Z}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function LK($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_detach","session.detach requires a session id");let Z=J.clientId?.trim()||"hub-client",[W]=await Promise.all([s0($,Q)]),j=yS(W?.metadata)??Z,f=$.sessionState.get(Q);if(f){if(f.participants.delete(Z),f.createdByClientId===Z)f.createdByClientId=j;if(f.participants.size===0)$.sessionState.delete(Q)}C$($,(V)=>V.sessionId===Q&&V.targetClientId===Z,`Capability owner client ${Z} detached before request was resolved.`);let[X,Y]=await Promise.all([s0($,Q),o0($,Q)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Z}:{clientId:Z},Q)),l(J)}async function _K($,J){let Q=h0(J),Z=J.payload?.includeSnapshot===!0,[W,j]=await Promise.all([s0($,Q),Z?o0($,Q):Promise.resolve(void 0)]);return W?l(J,{session:W,...j?{snapshot:j}:{}}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function OK($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_id","session.messages requires a session id");if(!await s0($,Q))return v(J,"session_not_found",`Unknown session: ${Q}`);let W=await $.sessionHost.readSessionMessages(Q);return l(J,{sessionId:Q,messages:W})}async function TK($,J){let Q=typeof J.payload?.limit==="number"?J.payload.limit:200,W=(await $.sessionHost.listSessions(Q)).map((j)=>B9(j,$.sessionState.get(j.sessionId)));return l(J,{sessions:W})}async function MK($,J){let Q=h0(J),Z=A9(J.payload?.metadata),W=await $.sessionHost.updateSession(Q,{metadata:Z}),[j,f]=await Promise.all([s0($,Q),o0($,Q)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...f?{snapshot:f}:{}},Q));return{version:J.version,requestId:J.requestId,ok:W.updated,payload:{updated:W.updated,session:j,...f?{snapshot:f}:{}}}}async function qK($,J){let Q=h0(J),Z=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),l(J,{deleted:Z})}async function PK($,J){let Q=h0(J),Z=$.sessionHost.pendingPrompts;if(!Z)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.list({sessionId:Q});return l(J,{sessionId:Q,prompts:W})}async function NK($,J){let Q=h0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=typeof J.payload?.prompt==="string"?J.payload.prompt:void 0,j=J.payload?.delivery==="queue"||J.payload?.delivery==="steer"?J.payload.delivery:void 0,f=$.sessionHost.pendingPrompts;if(!f)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await f.update({sessionId:Q,promptId:Z,prompt:W,delivery:j});return l(J,X)}async function wK($,J){let Q=h0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=$.sessionHost.pendingPrompts;if(!W)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await W.delete({sessionId:Q,promptId:Z});return l(J,j)}function SK($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var bS=new Set(["skills","workflows","rules","tools","mcp"]);function P3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function LJ($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${J}' must be a string.`);return Q}function hS($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${J}' must be a boolean.`);return Q}function CK($){if($===void 0)return{};if(!P3($))throw Error("settings.list payload must be an object.");return{cwd:LJ($,"cwd"),workspaceRoot:LJ($,"workspaceRoot"),availabilityContext:P3($.availabilityContext)?$.availabilityContext:void 0}}function kS($){if(!P3($))throw Error("settings.toggle payload must be an object.");let{type:J}=$;if(typeof J!=="string"||!bS.has(J))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...CK($),type:J,id:LJ($,"id"),path:LJ($,"path"),name:LJ($,"name"),enabled:hS($,"enabled")}}class J4{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=ES("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(J)=>this.publish(J),buildEvent:w2,requestCapability:(J,Q,Z,W,j)=>aA(this.ctx,J,Q,Z,W,j)},this.schedules=new s8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(J,Q)=>{let Z=J==="schedule.execution.completed"?"schedule.execution_completed":J==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Z)return;this.publish(w2(Z,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new a8(this.schedules),this.settings=$.settingsService??new O$,$.cronOptions)this.cronService=new s6({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((J)=>{fK(this.ctx,J).catch((Q)=>{R3("session event handling failed",Q),G9(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:J.type,sessionId:J.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())D3(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(C$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let J=await this.dispatchCommand($);return this.captureFailedReply($,J),J}catch(J){throw G9(this.options.telemetry,{component:"core",operation:"hub.command",error:J,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),J}}async dispatchCommand($){switch($.command){case"client.register":return eA(this.ctx,$);case"client.update":return $K(this.ctx,$);case"client.unregister":return JK(this.ctx,$,(J)=>{this.listeners.delete(J),this.detachClientFromSessions(J)});case"client.list":return QK(this.ctx,$);case"session.create":return await UK(this.ctx,$,(J)=>F3(this.ctx,J));case"session.restore":return await RK(this.ctx,$,(J)=>F3(this.ctx,J));case"session.attach":return await zK(this.ctx,$);case"session.detach":return await LK(this.ctx,$);case"session.get":return await _K(this.ctx,$);case"session.messages":return await OK(this.ctx,$);case"session.list":return await TK(this.ctx,$);case"session.update":return await MK(this.ctx,$);case"session.pending_prompts":return await PK(this.ctx,$);case"session.update_pending_prompt":return await NK(this.ctx,$);case"session.remove_pending_prompt":return await wK(this.ctx,$);case"session.delete":return await qK(this.ctx,$);case"session.hook":return await jK(this.ctx,$);case"run.start":case"session.send_input":return await ZK(this.ctx,$);case"run.abort":return await WK(this.ctx,$);case"capability.request":return await oA(this.ctx,$);case"approval.respond":return await iA(this.ctx,$);case"capability.respond":return tA(this.ctx,$);case"capability.progress":return sA(this.ctx,$);case"ui.notify":return this.publish(w2("ui.notify",$.payload??{})),l($);case"ui.show_window":return this.publish(w2("ui.show_window",$.payload??{})),l($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let J=await this.scheduleCommands.handleCommand($);if(J.ok){let Q=SK($.command);if(Q)this.publish(w2(Q,J.payload))}return J}}}captureFailedReply($,J){if(J.ok||!J.error||!IS(J.error.code))return;G9(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(J.error.message),severity:J.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:J.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let J=await this.settings.list(CK($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:J instanceof Error?J.message:String(J)}}}}async handleSettingsToggle($){try{let J=await this.settings.toggle(kS($.payload));return this.publish(w2("settings.changed",{types:J.changedTypes,snapshot:J.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J.snapshot,changedTypes:J.changedTypes}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:J instanceof Error?J.message:String(J)}}}}subscribe($,J,Q){let Z=this.listeners.get($)??new Set,W={sessionId:Q?.sessionId,listener:J};return Z.add(W),this.listeners.set($,Z),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(W),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[J,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(J);C$(this.ctx,(J)=>J.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let J of this.listeners.values())for(let Q of J){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(Z){R3(`listener threw while publishing ${$.event}`,Z),G9(this.options.telemetry,{component:"core",operation:"hub.publish",error:Z,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function IS($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as vS}from"node:crypto";import cS from"node:http";import uS from"node:net";import{URL as bK}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as hK,HUB_CAPABILITIES as dS,isHubProtocolCompatible as lS,MAX_CLIENT_HUB_PROTOCOL_VERSION as kK,MIN_CLIENT_HUB_PROTOCOL_VERSION as IK}from"@cline/shared";import{WebSocketServer as pS}from"ws";import{captureSdkError as yK,HUB_COMMAND_SLOW_LOG_MS as xS,resolveHubCommandTimeoutMs as gS,safeJsonParse as mS}from"@cline/shared";function N3($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function EK($,J,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:J,message:Q}}}class _J{transport;telemetry;constructor($,J){this.transport=$;this.telemetry=J}attach($){let J=new Map,Q=new Set,Z=!1,W=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},j=(Y)=>{W({kind:"event",envelope:Y})},f=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let H=performance.now(),B=!1,A=N3(V);c("info","command.start",A);let K=setTimeout(()=>{if(B)return;c("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-H)})},xS),G=this.transport.command(V.envelope);G.then((T)=>{if(!B)return;c(T.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!B)return;c("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-H),error:T})});let R=!1,D,U,F=gS(V.envelope.command,V.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((T)=>{D=setTimeout(()=>{R=!0,yK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:F}}),T(EK(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},F)})])}catch(T){if(clearTimeout(K),D)clearTimeout(D);throw T}if(B=R,clearTimeout(K),D)clearTimeout(D);let O=Math.round(performance.now()-H);if(R)c("error","command.timeout",{...A,durationMs:O,timeoutMs:F});else c(U.ok?"info":"warn","command.end",{...A,durationMs:O,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(V.envelope.command==="client.register"&&U.ok){let L=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(L)Q.add(L)}else if(V.envelope.command==="client.unregister"&&U.ok){let T=V.envelope.clientId?.trim();if(T)Q.delete(T)}W({kind:"reply",envelope:U});break}case"stream.subscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;if(J.has(H))break;let B=await this.transport.subscribe(V.clientId,j,{sessionId:V.sessionId});J.set(H,B);break}case"stream.unsubscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;J.get(H)?.(),J.delete(H);break}case"reply":case"event":break}}catch(V){let H=typeof Y.data==="string"?mS(Y.data):void 0;if(!H||H.kind!=="command"){c("error","rejected malformed websocket frame",{error:V});return}c("error","command.error",{...N3(H),error:V}),yK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:N3(H)}),W({kind:"reply",envelope:EK(H,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Z)return;Z=!0;for(let Y of J.values())Y();J.clear();for(let Y of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});Q.clear(),$.removeEventListener("message",f),$.removeEventListener("close",X)};return $.addEventListener("message",f),$.addEventListener("close",X),X}}class OJ{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,J,Q){return this.transport.subscribe($,J,Q)}}function rS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();return String($)}function iS($){return{send(J){$.send(J)},addEventListener(J,Q){if(J==="message"){$.on("message",(Z)=>{Q({data:rS(Z)})});return}$.on("close",Q)},removeEventListener(){}}}function nS($){try{$.write(`HTTP/1.1 400 Bad Request\r
578
+ ${H}`:Y.instructions}})}})}}function wS($,J,Q,Z){let W=Q.map((j)=>[j.executor,async(...f)=>{let X=f.at(-1),Y=f.slice(0,-1);return(await Z($,j.capabilityName,{executor:j.executor,args:Y,context:BK(X)},J))?.result}]);return W.length>0?Object.fromEntries(W):void 0}function SS($,J,Q,Z){if(Q.length===0)return;return Q.map((W)=>({name:W.name,description:W.description,inputSchema:W.inputSchema,lifecycle:W.lifecycle,async execute(j,f){return(await Z($,W.capabilityName,{toolName:W.name,input:j,context:BK(f)},J,f.emitUpdate?(Y)=>{f.emitUpdate?.(MS(Y))}:void 0))?.result}}))}function CS($,J,Q,Z){let W=new Map(Q.map((f)=>[f.name,f])),j={};for(let f of OS){let X=W.get(f);if(!X)continue;j[f]=async(Y)=>{return(await Z($,X.capabilityName,{context:Y},J))?.control}}return Object.keys(j).length>0?j:void 0}function q3($){let J=$.contributions.filter((Y)=>Y.kind==="toolExecutor"),Q=$.contributions.filter((Y)=>Y.kind==="tool"),Z=$.contributions.filter((Y)=>Y.kind==="hook"),W=$.contributions.find((Y)=>Y.kind==="compaction"),j=$.contributions.find((Y)=>Y.kind==="checkpoint"),f=$.contributions.find((Y)=>Y.kind==="mistakeLimit"),X=$.contributions.find((Y)=>Y.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:wS($.sessionId,$.targetClientId,J,$.requestCapability),localRuntime:{...Z.length>0?{hooks:CS($.sessionId,$.targetClientId,Z,$.requestCapability)}:{},...Q.length>0?{extraTools:SS($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...W?{compaction:{...$.sessionConfig?.compaction??{},...W.config,compact:async(Y)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...j?{checkpoint:{...$.sessionConfig?.checkpoint??{},...j.config,createCheckpoint:async(Y)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:Y},$.targetClientId))?.result}}}:{},...f?{onConsecutiveMistakeLimitReached:async(Y)=>{return(await $.requestCapability($.sessionId,f.capabilityName,{context:Y},$.targetClientId))?.result}}:{},...X?{userInstructionService:NS($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var GK="hubCapabilityOwnerClientId";function FK($,J){$[GK]=J}function yS($){let J=$?.[GK];return typeof J==="string"&&J.trim()?J.trim():void 0}async function DK($,J,Q){let Z=performance.now(),W={command:J.command,requestId:J.requestId,clientId:J.clientId,sessionId:J.sessionId};c("info","session.create.begin",W);let j=J.payload&&typeof J.payload==="object"?J.payload:{},f=j.metadata&&typeof j.metadata==="object"?JSON.parse(JSON.stringify(j.metadata)):{},X=j.sessionConfig&&typeof j.sessionConfig==="object"?JSON.parse(JSON.stringify(j.sessionConfig)):void 0,Y=j.runtimeOptions&&typeof j.runtimeOptions==="object"?j.runtimeOptions:{};if(typeof X?.mode==="string")f.mode=X.mode;else if(typeof Y.mode==="string")f.mode=Y.mode;if(typeof X?.systemPrompt==="string")f.systemPrompt=X.systemPrompt;else if(typeof Y.systemPrompt==="string")f.systemPrompt=Y.systemPrompt;if(X?.checkpoint?.enabled===!0)f.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)f.checkpointEnabled=!0;let V=j.modelSelection&&typeof j.modelSelection==="object"?j.modelSelection:{},H=typeof j.workspaceRoot==="string"&&j.workspaceRoot.trim()?j.workspaceRoot.trim():typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():"";if(!H)return c("warn","session.create.invalid",{...W,reason:"missing_workspace_root"}),v(J,"invalid_session_create","session.create requires workspaceRoot or cwd");let B=J.clientId?.trim()||"hub-client",A=M3(Y.clientContributions);if(c("info","session.create.contributions_parsed",{...W,clientId:B,workspaceRoot:H,cwd:typeof j.cwd==="string"?j.cwd:void 0,contributionCount:A.length}),A.length>0)FK(f,B);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||AK(),R=KK(Y.configExtensions);c("info","session.create.runtime_build.begin",{...W,sessionId:G,configExtensionCount:R?.length??0});let D=q3({sessionId:G,targetClientId:B,contributions:A,sessionConfig:X,requestCapability:$.requestCapability});c("info","session.create.start_session.begin",{...W,sessionId:G,provider:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),model:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub")});let U=await $.sessionHost.startSession({source:typeof f.source==="string"?f.source:void 0,interactive:f.interactive!==!1,sessionMetadata:Object.keys(f).length>0?f:void 0,initialMessages:Array.isArray(j.initialMessages)?j.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...D.localRuntime},capabilities:{toolExecutors:D.toolExecutors,requestToolApproval:Q},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof V.provider==="string"?V.provider:typeof f.provider==="string"?f.provider:"hub"),modelId:X?.modelId??(typeof V.model==="string"?V.model:typeof f.model==="string"?f.model:"hub"),apiKey:X?.apiKey??(typeof V.apiKey==="string"?V.apiKey:void 0),cwd:X?.cwd??(typeof j.cwd==="string"&&j.cwd.trim()?j.cwd.trim():H),workspaceRoot:X?.workspaceRoot??H,systemPrompt:X?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:X?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:X?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:X?.enableTools??Y.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:X?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof f.teamName==="string"?f.teamName:void 0)},toolPolicies:j.toolPolicies&&typeof j.toolPolicies==="object"&&!Array.isArray(j.toolPolicies)?JSON.parse(JSON.stringify(j.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});c("info","session.create.start_session.end",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z),hasImmediateResult:!!U.result}),KQ($,U.sessionId,B,"creator",{interactive:f.interactive!==!1}),c("info","session.create.read_records.begin",{...W,sessionId:U.sessionId});let[F,O]=await Promise.all([s0($,U.sessionId),o0($,U.sessionId)]);if(c("info","session.create.read_records.end",{...W,sessionId:U.sessionId,hasSession:!!F,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Z)}),F)$.publish($.buildEvent("session.created",{session:F,...O?{snapshot:O}:{}},U.sessionId));return c("info","session.create.reply",{...W,sessionId:U.sessionId,elapsedMs:Math.round(performance.now()-Z)}),l(J,{session:F,...O?{snapshot:O}:{}})}async function UK($,J,Q){let Z=J.payload&&typeof J.payload==="object"?J.payload:{},W=typeof Z.sessionId==="string"?Z.sessionId.trim():J.sessionId?.trim()||"",j=Z.checkpointRunCount;if(!W)return v(J,"invalid_restore","session.restore requires a session id");let f=Z.restore&&typeof Z.restore==="object"?Z.restore:{},X=f.messages!==!1;if(typeof j!=="number")return v(J,"invalid_restore","checkpointRunCount must be a positive integer");try{let Y=Z.sessionConfig&&typeof Z.sessionConfig==="object"?JSON.parse(JSON.stringify(Z.sessionConfig)):void 0;if(X&&!Y)return v(J,"invalid_restore","sessionConfig is required when restore.messages is true");let V=Z.runtimeOptions&&typeof Z.runtimeOptions==="object"?Z.runtimeOptions:{},H=Z.metadata&&typeof Z.metadata==="object"?JSON.parse(JSON.stringify(Z.metadata)):{};if(typeof Y?.mode==="string")H.mode=Y.mode;else if(typeof V.mode==="string")H.mode=V.mode;if(typeof Y?.systemPrompt==="string")H.systemPrompt=Y.systemPrompt;else if(typeof V.systemPrompt==="string")H.systemPrompt=V.systemPrompt;if(Y?.checkpoint?.enabled===!0)H.checkpointEnabled=!0;else if(V.checkpointEnabled===!0)H.checkpointEnabled=!0;let B=Z.modelSelection&&typeof Z.modelSelection==="object"?Z.modelSelection:{},A=J.clientId?.trim()||"hub-client",K=M3(V.clientContributions);if(K.length>0)FK(H,A);let R=(typeof Y?.sessionId==="string"?Y.sessionId.trim():"")||AK(),D=KK(V.configExtensions),U=q3({sessionId:R,targetClientId:A,contributions:K,sessionConfig:Y,requestCapability:$.requestCapability}),O=await new y$().restoreCheckpoint({sessionId:W,checkpointRunCount:j,restore:{messages:f.messages,workspace:f.workspace,omitCheckpointMessageFromSession:f.omitCheckpointMessageFromSession===!0},start:Y,cwd:typeof Y?.cwd==="string"&&Y.cwd.trim()||typeof Y?.workspaceRoot==="string"&&Y.workspaceRoot.trim()||void 0,getSession:(P)=>$.sessionHost.getSession(P),readMessages:(P)=>$.sessionHost.readSessionMessages(P),buildStartInput:(P)=>{if(P.restoredCheckpointMetadata)H.checkpoint=P.restoredCheckpointMetadata;let S=typeof Z.workspaceRoot==="string"&&Z.workspaceRoot.trim()?Z.workspaceRoot.trim():typeof Z.cwd==="string"&&Z.cwd.trim()?Z.cwd.trim():P.sourceSession.workspaceRoot||P.sourceSession.cwd;return{source:typeof H.source==="string"?H.source:void 0,interactive:H.interactive!==!1,sessionMetadata:{...H,restoredFromSessionId:W,restoredCheckpointRunCount:j},initialMessages:P.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...U.localRuntime},capabilities:{toolExecutors:U.toolExecutors,requestToolApproval:Q},config:{...Y??{},sessionId:R,providerId:Y?.providerId??(typeof B.provider==="string"?B.provider:P.sourceSession.provider),modelId:Y?.modelId??(typeof B.model==="string"?B.model:P.sourceSession.model),apiKey:Y?.apiKey??(typeof B.apiKey==="string"?B.apiKey:""),cwd:Y?.cwd??P.plan.cwd,workspaceRoot:Y?.workspaceRoot??S,systemPrompt:Y?.systemPrompt??(typeof V.systemPrompt==="string"?V.systemPrompt:""),mode:Y?.mode??(V.mode==="plan"||V.mode==="yolo"?V.mode:"act"),maxIterations:Y?.maxIterations??(typeof V.maxIterations==="number"?V.maxIterations:void 0),enableTools:Y?.enableTools??V.enableTools!==!1,enableSpawnAgent:Y?.enableSpawnAgent??V.enableSpawn!==!1,enableAgentTeams:Y?.enableAgentTeams??V.enableTeams!==!1,checkpoint:Y?.checkpoint??(V.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:Y?.teamName??(typeof H.teamName==="string"?H.teamName:void 0)},toolPolicies:Z.toolPolicies&&typeof Z.toolPolicies==="object"&&!Array.isArray(Z.toolPolicies)?JSON.parse(JSON.stringify(Z.toolPolicies)):V.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(P)=>$.sessionHost.startSession(P),getStartedSessionId:(P)=>P.sessionId,readRestoredSession:(P)=>$.sessionHost.getSession(P)});if(!X)return l(J,{checkpoint:O.checkpoint});let T=O.startResult;if(!T)return v(J,"restore_failed","Checkpoint restore did not start a session");KQ($,T.sessionId,A,"creator",{interactive:H.interactive!==!1});let[L,z]=await Promise.all([s0($,T.sessionId),o0($,T.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},T.sessionId));return l(J,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(Y){if(Y instanceof k0)return v(J,Y.code,Y.code==="session_not_found"?`Unknown session: ${W}`:Y.message);return v(J,"restore_failed",Y instanceof Error?Y.message:String(Y))}}async function RK($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_attach","session.attach requires a session id");KQ($,Q,J.clientId?.trim()||"hub-client","participant");let Z=await s0($,Q);if(Z)$.publish($.buildEvent("session.attached",{session:Z},Q));return Z?l(J,{session:Z}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function zK($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_detach","session.detach requires a session id");let Z=J.clientId?.trim()||"hub-client",[W]=await Promise.all([s0($,Q)]),j=yS(W?.metadata)??Z,f=$.sessionState.get(Q);if(f){if(f.participants.delete(Z),f.createdByClientId===Z)f.createdByClientId=j;if(f.participants.size===0)$.sessionState.delete(Q)}C$($,(V)=>V.sessionId===Q&&V.targetClientId===Z,`Capability owner client ${Z} detached before request was resolved.`);let[X,Y]=await Promise.all([s0($,Q),o0($,Q)]);return $.publish($.buildEvent("session.detached",X?{session:X,...Y?{snapshot:Y}:{},clientId:Z}:{clientId:Z},Q)),l(J)}async function LK($,J){let Q=h0(J),Z=J.payload?.includeSnapshot===!0,[W,j]=await Promise.all([s0($,Q),Z?o0($,Q):Promise.resolve(void 0)]);return W?l(J,{session:W,...j?{snapshot:j}:{}}):v(J,"session_not_found",`Unknown session: ${Q}`)}async function _K($,J){let Q=h0(J);if(!Q)return v(J,"invalid_session_id","session.messages requires a session id");if(!await s0($,Q))return v(J,"session_not_found",`Unknown session: ${Q}`);let W=await $.sessionHost.readSessionMessages(Q);return l(J,{sessionId:Q,messages:W})}async function OK($,J){let Q=typeof J.payload?.limit==="number"?J.payload.limit:200,W=(await $.sessionHost.listSessions(Q)).map((j)=>BQ(j,$.sessionState.get(j.sessionId)));return l(J,{sessions:W})}async function TK($,J){let Q=h0(J),Z=AQ(J.payload?.metadata),W=await $.sessionHost.updateSession(Q,{metadata:Z}),[j,f]=await Promise.all([s0($,Q),o0($,Q)]);if(j)$.publish($.buildEvent("session.updated",{session:j,...f?{snapshot:f}:{}},Q));return{version:J.version,requestId:J.requestId,ok:W.updated,payload:{updated:W.updated,session:j,...f?{snapshot:f}:{}}}}async function MK($,J){let Q=h0(J),Z=await $.sessionHost.deleteSession(Q);return $.sessionState.delete(Q),l(J,{deleted:Z})}async function qK($,J){let Q=h0(J),Z=$.sessionHost.pendingPrompts;if(!Z)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.list({sessionId:Q});return l(J,{sessionId:Q,prompts:W})}async function PK($,J){let Q=h0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=typeof J.payload?.prompt==="string"?J.payload.prompt:void 0,j=J.payload?.delivery==="queue"||J.payload?.delivery==="steer"?J.payload.delivery:void 0,f=$.sessionHost.pendingPrompts;if(!f)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await f.update({sessionId:Q,promptId:Z,prompt:W,delivery:j});return l(J,X)}async function NK($,J){let Q=h0(J),Z=typeof J.payload?.promptId==="string"?J.payload.promptId.trim():"",W=$.sessionHost.pendingPrompts;if(!W)return v(J,"pending_prompts_unavailable","Pending prompt service is not available.");let j=await W.delete({sessionId:Q,promptId:Z});return l(J,j)}function wK($){switch($){case"schedule.create":return"schedule.created";case"schedule.update":case"schedule.enable":case"schedule.disable":return"schedule.updated";case"schedule.delete":return"schedule.deleted";case"schedule.trigger":return"schedule.triggered";default:return}}var bS=new Set(["skills","workflows","rules","tools","mcp"]);function P3($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function LJ($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="string")throw Error(`settings payload '${J}' must be a string.`);return Q}function hS($,J){let Q=$[J];if(Q===void 0)return;if(typeof Q!=="boolean")throw Error(`settings payload '${J}' must be a boolean.`);return Q}function SK($){if($===void 0)return{};if(!P3($))throw Error("settings.list payload must be an object.");return{cwd:LJ($,"cwd"),workspaceRoot:LJ($,"workspaceRoot"),availabilityContext:P3($.availabilityContext)?$.availabilityContext:void 0}}function kS($){if(!P3($))throw Error("settings.toggle payload must be an object.");let{type:J}=$;if(typeof J!=="string"||!bS.has(J))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...SK($),type:J,id:LJ($,"id"),path:LJ($,"path"),name:LJ($,"name"),enabled:hS($,"enabled")}}class J4{options;clients=new Map;listeners=new Map;sessionState=new Map;pendingApprovals=new Map;pendingCapabilityRequests=new Map;suppressNextTerminalEventBySession=new Map;schedules;scheduleCommands;settings;cronService;sessionHost;hubId=ES("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry}),this.ctx={clients:this.clients,sessionState:this.sessionState,pendingApprovals:this.pendingApprovals,pendingCapabilityRequests:this.pendingCapabilityRequests,suppressNextTerminalEventBySession:this.suppressNextTerminalEventBySession,telemetry:$.telemetry,sessionHost:this.sessionHost,publish:(J)=>this.publish(J),buildEvent:w2,requestCapability:(J,Q,Z,W,j)=>nA(this.ctx,J,Q,Z,W,j)},this.schedules=new s8({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(J,Q)=>{let Z=J==="schedule.execution.completed"?"schedule.execution_completed":J==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Z)return;this.publish(w2(Z,Q&&typeof Q==="object"?Q:void 0))}}),this.scheduleCommands=new a8(this.schedules),this.settings=$.settingsService??new O$,$.cronOptions)this.cronService=new s6({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((J)=>{jK(this.ctx,J).catch((Q)=>{R3("session event handling failed",Q),GQ(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:Q,severity:"error",handled:!0,context:{eventType:J.type,sessionId:J.payload.sessionId}})})})}getCronService(){return this.cronService}getHubId(){return this.hubId}async start(){if(await this.schedules.start(),this.cronService)try{await this.cronService.start()}catch($){console.error("[hub] cron service start failed",$)}}async stop(){for(let $ of this.pendingApprovals.keys())D3(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(C$(this.ctx,()=>!0,"Hub shutting down before capability request was resolved."),await this.sessionHost.dispose("hub_server_stop"),await this.schedules.dispose(),this.cronService)try{await this.cronService.dispose()}catch($){console.error("[hub] cron service stop failed",$)}}async handleCommand($){try{let J=await this.dispatchCommand($);return this.captureFailedReply($,J),J}catch(J){throw GQ(this.options.telemetry,{component:"core",operation:"hub.command",error:J,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),J}}async dispatchCommand($){switch($.command){case"client.register":return tA(this.ctx,$);case"client.update":return eA(this.ctx,$);case"client.unregister":return $K(this.ctx,$,(J)=>{this.listeners.delete(J),this.detachClientFromSessions(J)});case"client.list":return JK(this.ctx,$);case"session.create":return await DK(this.ctx,$,(J)=>F3(this.ctx,J));case"session.restore":return await UK(this.ctx,$,(J)=>F3(this.ctx,J));case"session.attach":return await RK(this.ctx,$);case"session.detach":return await zK(this.ctx,$);case"session.get":return await LK(this.ctx,$);case"session.messages":return await _K(this.ctx,$);case"session.list":return await OK(this.ctx,$);case"session.update":return await TK(this.ctx,$);case"session.pending_prompts":return await qK(this.ctx,$);case"session.update_pending_prompt":return await PK(this.ctx,$);case"session.remove_pending_prompt":return await NK(this.ctx,$);case"session.delete":return await MK(this.ctx,$);case"session.hook":return await WK(this.ctx,$);case"run.start":case"session.send_input":return await QK(this.ctx,$);case"run.abort":return await ZK(this.ctx,$);case"capability.request":return await sA(this.ctx,$);case"approval.respond":return await rA(this.ctx,$);case"capability.respond":return oA(this.ctx,$);case"capability.progress":return aA(this.ctx,$);case"ui.notify":return this.publish(w2("ui.notify",$.payload??{})),l($);case"ui.show_window":return this.publish(w2("ui.show_window",$.payload??{})),l($);case"settings.list":return await this.handleSettingsList($);case"settings.toggle":return await this.handleSettingsToggle($);case"settings.get":case"settings.patch":return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"not_implemented",message:`${$.command} is not implemented yet.`}};default:{let J=await this.scheduleCommands.handleCommand($);if(J.ok){let Q=wK($.command);if(Q)this.publish(w2(Q,J.payload))}return J}}}captureFailedReply($,J){if(J.ok||!J.error||!IS(J.error.code))return;GQ(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(J.error.message),severity:J.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:J.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let J=await this.settings.list(SK($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:J instanceof Error?J.message:String(J)}}}}async handleSettingsToggle($){try{let J=await this.settings.toggle(kS($.payload));return this.publish(w2("settings.changed",{types:J.changedTypes,snapshot:J.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:J.snapshot,changedTypes:J.changedTypes}}}catch(J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:J instanceof Error?J.message:String(J)}}}}subscribe($,J,Q){let Z=this.listeners.get($)??new Set,W={sessionId:Q?.sessionId,listener:J};return Z.add(W),this.listeners.set($,Z),()=>{let j=this.listeners.get($);if(!j)return;if(j.delete(W),j.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[J,Q]of this.sessionState.entries())if(Q.participants.delete($),Q.participants.size===0)this.sessionState.delete(J);C$(this.ctx,(J)=>J.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let J of this.listeners.values())for(let Q of J){if(Q.sessionId&&Q.sessionId!==$.sessionId)continue;try{Q.listener($)}catch(Z){R3(`listener threw while publishing ${$.event}`,Z),GQ(this.options.telemetry,{component:"core",operation:"hub.publish",error:Z,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function IS($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as vS}from"node:crypto";import cS from"node:http";import uS from"node:net";import{URL as EK}from"node:url";import{CURRENT_HUB_PROTOCOL_VERSION as bK,HUB_CAPABILITIES as dS,isHubProtocolCompatible as lS,MAX_CLIENT_HUB_PROTOCOL_VERSION as hK,MIN_CLIENT_HUB_PROTOCOL_VERSION as kK}from"@cline/shared";import{WebSocketServer as pS}from"ws";import{captureSdkError as CK,HUB_COMMAND_SLOW_LOG_MS as xS,resolveHubCommandTimeoutMs as gS,safeJsonParse as mS}from"@cline/shared";function N3($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function yK($,J,Q){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:J,message:Q}}}class _J{transport;telemetry;constructor($,J){this.transport=$;this.telemetry=J}attach($){let J=new Map,Q=new Set,Z=!1,W=(Y)=>{try{$.send(JSON.stringify(Y))}catch(V){console.error(`[hub] failed to send websocket frame: ${V instanceof Error?V.stack||V.message:String(V)}`)}},j=(Y)=>{W({kind:"event",envelope:Y})},f=async(Y)=>{try{let V=JSON.parse(Y.data);switch(V.kind){case"command":{let H=performance.now(),B=!1,A=N3(V);c("info","command.start",A);let K=setTimeout(()=>{if(B)return;c("warn","command.slow",{...A,elapsedMs:Math.round(performance.now()-H)})},xS),G=this.transport.command(V.envelope);G.then((T)=>{if(!B)return;c(T.ok?"warn":"error","command.late_end",{...A,elapsedMs:Math.round(performance.now()-H),ok:T.ok,errorCode:T.error?.code,errorMessage:T.error?.message})},(T)=>{if(!B)return;c("error","command.late_error",{...A,elapsedMs:Math.round(performance.now()-H),error:T})});let R=!1,D,U,F=gS(V.envelope.command,V.envelope.timeoutMs);try{U=F===null?await G:await Promise.race([G,new Promise((T)=>{D=setTimeout(()=>{R=!0,CK(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${V.envelope.command} did not complete within ${F}ms.`),severity:"error",handled:!0,context:{...A,timeoutMs:F}}),T(yK(V,"hub_command_timeout",`Hub command ${V.envelope.command} did not complete within ${F}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${V.envelope.requestId}.`))},F)})])}catch(T){if(clearTimeout(K),D)clearTimeout(D);throw T}if(B=R,clearTimeout(K),D)clearTimeout(D);let O=Math.round(performance.now()-H);if(R)c("error","command.timeout",{...A,durationMs:O,timeoutMs:F});else c(U.ok?"info":"warn","command.end",{...A,durationMs:O,ok:U.ok,errorCode:U.error?.code,errorMessage:U.error?.message});if(V.envelope.command==="client.register"&&U.ok){let L=(V.envelope.payload??{}).clientId?.trim()||V.envelope.clientId?.trim();if(L)Q.add(L)}else if(V.envelope.command==="client.unregister"&&U.ok){let T=V.envelope.clientId?.trim();if(T)Q.delete(T)}W({kind:"reply",envelope:U});break}case"stream.subscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;if(J.has(H))break;let B=await this.transport.subscribe(V.clientId,j,{sessionId:V.sessionId});J.set(H,B);break}case"stream.unsubscribe":{let H=`${V.clientId}:${V.sessionId??"*"}`;J.get(H)?.(),J.delete(H);break}case"reply":case"event":break}}catch(V){let H=typeof Y.data==="string"?mS(Y.data):void 0;if(!H||H.kind!=="command"){c("error","rejected malformed websocket frame",{error:V});return}c("error","command.error",{...N3(H),error:V}),CK(this.telemetry,{component:"core",operation:"hub.websocket_command",error:V,severity:"error",handled:!0,context:N3(H)}),W({kind:"reply",envelope:yK(H,"command_failed",V instanceof Error?V.message:"Unknown hub error")})}},X=()=>{if(Z)return;Z=!0;for(let Y of J.values())Y();J.clear();for(let Y of Q)this.transport.command({version:"v1",command:"client.unregister",clientId:Y});Q.clear(),$.removeEventListener("message",f),$.removeEventListener("close",X)};return $.addEventListener("message",f),$.addEventListener("close",X),X}}class OJ{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,J,Q){return this.transport.subscribe($,J,Q)}}function rS($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((J)=>Buffer.from(J))).toString();return String($)}function iS($){return{send(J){$.send(J)},addEventListener(J,Q){if(J==="message"){$.on("message",(Z)=>{Q({data:rS(Z)})});return}$.on("close",Q)},removeEventListener(){}}}function nS($){try{$.write(`HTTP/1.1 400 Bad Request\r
579
579
  Connection: close\r
580
580
  Content-Length: 0\r
581
581
  \r
@@ -583,11 +583,11 @@ Content-Length: 0\r
583
583
  Connection: close\r
584
584
  Content-Length: 0\r
585
585
  \r
586
- `),$.end()}catch{$.destroy()}}function w3($,J){if(!$||!J)return!1;let Q=Buffer.from($,"utf8"),Z=Buffer.from(J,"utf8");return Q.length===Z.length&&vS(Q,Z)}function xK($,J){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Z=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",W=`Failed to start hub server on ${J.host}:${J.port}${J.pathname}: ${Z}`,j=Error(Q?`${W} (${Q})`:W);if(Q)$.code=Q,j.code=Q;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
587
- Caused by: ${$.stack}`;return j}async function sS($){return await new Promise((J,Q)=>{let Z=uS.createServer();Z.once("error",Q),Z.listen(0,$,()=>{let W=Z.address();if(!W||typeof W==="string"){Z.close(()=>Q(Error("Failed to resolve free port")));return}let j=W.port;Z.close((f)=>{if(f){Q(f);return}J(j)})})})}function oS($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var S3=new Map,gK="cline-hub-auth.",tS=30000;function vK($){return Array.isArray($)?$.join(","):$??""}function mK($){return $===32||$===9}function F9($){let J=vK($).trim(),Q="bearer";if(J.length<=6||J.slice(0,6).toLowerCase()!=="bearer"||!mK(J.charCodeAt(6)))return null;let Z=7;while(Z<J.length&&mK(J.charCodeAt(Z)))Z+=1;return J.slice(Z).trim()||null}function eS($){for(let J of vK($).split(",")){let Q=J.trim();if(Q.startsWith(gK))return Q.slice(gK.length).trim()||null}return null}async function C2($){let J=$.owner??l1(),Q=$.host??"127.0.0.1",Z=$.pathname??"/hub",W=$.port??b8(),j=W===0?await sS(Q):W,f=j,X=j1(Q,j,Z),Y=uQ(),V=cQ(),H=new J4($);await H.start();let B=new _J(new OJ(H),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:hK,minClientProtocolVersion:IK,maxClientProtocolVersion:kK,capabilities:dS,coreVersion:e6.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,D,U,F=async()=>{if(U)return U;return U=(async()=>{if(D)clearInterval(D),D=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of A)z();if(A.clear(),await new Promise((z,P)=>{T.close((S)=>{if(S){P(S);return}z()})}),await new Promise((z,P)=>{O.close((S)=>{if(S){P(S);return}z()})}),await H.stop(),(await A0(J.discoveryPath))?.url===X)await y0(J.discoveryPath)})(),U},O=cS.createServer((L,z)=>{if((L.url??"/")==="/health"){let S=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:Q,port:f,url:X});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/status"){if(!w3(F9(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}let S=JSON.stringify({hubId:H.getHubId(),...G,authToken:V,host:Q,port:f,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new bK(L.url??"/",`http://${Q}:${f}`).pathname==="/shutdown"&&L.method==="POST"){if(!w3(F9(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}z.statusCode=404,z.end("Not found")}),T=new pS({noServer:!0});D=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},tS),O.on("upgrade",(L,z,P)=>{if(new bK(L.url??"/",`http://${Q}:${f}`).pathname!==Z){z.destroy();return}if(!w3(eS(L.headers["sec-websocket-protocol"]),V)){aS(z);return}try{T.handleUpgrade(L,z,P,(b)=>{let u=b;u.isAlive=!0,u.on("pong",()=>{u.isAlive=!0}),R.add(u);let o=B.attach(iS(b));A.add(o),b.once("close",()=>{R.delete(u),o(),A.delete(o)})})}catch{nS(z)}});try{await new Promise((L,z)=>{O.once("error",(P)=>{z(xK(P,{host:Q,port:j,pathname:Z}))}),O.listen(j,Q,()=>{let P=O.address();if(!P||typeof P==="string"){z(xK(Error("Failed to resolve hub port"),{host:Q,port:j,pathname:Z}));return}f=P.port,X=j1(Q,f,Z),L()})})}catch(L){if(D)clearInterval(D),D=void 0;throw await H.stop().catch(()=>{return}),L}return await dQ(J.discoveryPath,{hubId:H.getHubId(),protocolVersion:hK,minClientProtocolVersion:IK,maxClientProtocolVersion:kK,capabilities:[...G.capabilities],coreVersion:e6.version,buildId:Y,authToken:V,host:Q,port:f,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:Q,port:f,url:X,authToken:V,close:F}}async function D9($){let J=$.owner??l1(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.host??"127.0.0.1",W=$.port??b8(),j=$.pathname??"/hub",f=j1(Z,W,j),X=J.discoveryPath,Y=(H)=>{if(!Q)P$(H.url,H.authToken);return H},V=S3.get(X);if(V){let H=await V;if(H.url===f)return Y({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await lQ(J.discoveryPath,async()=>{let H=await A0(J.discoveryPath);if(H?.url&&(H.url===f||$.allowPortFallback===!0)){let K=await p1(H.url,{authToken:H.authToken});if(K?.url&&lS(K).compatible&&await G1(K.url,{authToken:H.authToken}))return Y({url:K.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await y0(J.discoveryPath);let A=async(K)=>{let G=C2({...K,owner:J});S3.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw S3.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!oS(K))throw K;return await A({...$,port:0})}})}function uK(){return cK()==="production"?n0():E0()}function $C($){return cK()!=="production"&&!$}async function dK($){let J=i0({host:$.host,port:$.port,pathname:$.pathname});return await C2({...$,...J,owner:uK()})}async function lK($){let J=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=i0({host:$.host,port:$.port,pathname:$.pathname});return await D9({...$,...Q,allowPortFallback:$.allowPortFallback??$C(J),owner:uK()})}R9();var iK={};w(iK,{registerRemoteConfigSessionBlobUpload:()=>_9,readRemoteConfigSessionBlobUploadMetadata:()=>C3,prepareRemoteConfigCoreIntegration:()=>E3,createRemoteConfigSessionMessagesArtifactUploader:()=>y3,buildRemoteConfigSessionBlobUploadMetadata:()=>z9,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>L9});import{buildRemoteConfigSessionBlobUploadMetadata as z9,clearRemoteConfigSessionBlobUpload as JC,createClineTelemetryServiceConfig as QC,createSessionId as ZC,createRemoteConfigSessionMessagesArtifactUploader as WC,prepareRemoteConfigRuntime as jC,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as L9,readRemoteConfigSessionBlobUploadMetadata as C3,registerRemoteConfigSessionBlobUpload as _9}from"@cline/shared";function fC($,J){let Q=$.telemetry||J.telemetryService?{...J.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return s1(QC(Q)).telemetry}function y3(){let $=WC();return{async uploadMessagesFile(J){await $.uploadMessagesFile(J)}}}async function E3($){let J=await jC($),Q=fC(J,$),Z=[J.pluginDefinition],W=J.claims?.subject,j=z9(J.bundle?.remoteConfig,W),f;return{prepared:J,extensions:Z,telemetry:Q,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,H=j?X.config.sessionId?.trim()||ZC():X.config.sessionId;if(H&&j)f=H;let B=H&&j?_9(H,J.bundle?.remoteConfig,W):void 0,A=B?{...X.sessionMetadata??{},[L9]:B}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...H?{sessionId:H}:{},extensions:[...Y,...Z],telemetry:Q??V}}},async dispose(){if(f)JC(f)}}}var $G={};w($G,{createTeamName:()=>M9,DefaultRuntimeBuilder:()=>W4});import{hasRuntimeConfigExtension as LC}from"@cline/shared";import{nanoid as _C}from"nanoid";W1();var eK={};w(eK,{createLocalTeamStore:()=>I3,SqliteTeamStore:()=>y2,FileTeamStore:()=>TJ});import{appendFileSync as XC,existsSync as Q4,mkdirSync as nK,readdirSync as YC,readFileSync as aK,renameSync as VC,writeFileSync as HC}from"node:fs";import{join as b3}from"node:path";import{resolveTeamDataDir as BC}from"@cline/shared/storage";function sK(){return new Date().toISOString()}function h3($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function oK($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class TJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??BC()}init(){this.ensureTeamDir()}listTeamNames(){if(!Q4(this.teamDirPath))return[];return YC(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>Q4(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let J=this.readEnvelope($);return J?.teamState?oK(J.teamState):void 0}readHistory($,J=200){let Q=this.historyPath($);if(!Q4(Q))return[];return aK(Q,"utf8").split(`
588
- `).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>{try{return JSON.parse(Z)}catch{return}}).filter((Z)=>Z!==void 0).reverse().slice(0,J)}loadRuntime($){let J=this.readEnvelope($);return{state:J?.teamState?oK(J.teamState):void 0,teammates:J?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,J){this.ensureTeamSubdir($),XC(this.historyPath($),`${JSON.stringify({ts:sK(),eventType:J.type,payload:J})}
589
- `,"utf8")}persistRuntime($,J,Q){this.ensureTeamSubdir($);let Z={version:1,updatedAt:sK(),teamState:J,teammates:Q},W=this.statePath($),j=`${W}.tmp`;HC(j,`${JSON.stringify(Z,null,2)}
590
- `,"utf8"),VC(j,W)}markInProgressRunsInterrupted($,J){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let Z=Q.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Z.length===0)return[];let W=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:J,endedAt:W}:j)},this.persistRuntime($,Q.teamState,Q.teammates),Z}ensureTeamDir(){if(!Q4(this.teamDirPath))nK(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let J=b3(this.ensureTeamDir(),h3($));if(!Q4(J))nK(J,{recursive:!0});return J}statePath($){return b3(this.ensureTeamDir(),h3($),"state.json")}historyPath($){return b3(this.ensureTeamDir(),h3($),"task-history.jsonl")}readEnvelope($){let J=this.statePath($);if(!Q4(J))return;try{let Q=JSON.parse(aK(J,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as AC,mkdirSync as KC}from"node:fs";import{join as GC}from"node:path";import{safeJsonParse as tK}from"@cline/shared";import{loadSqliteDb as FC,nowIso as k3}from"@cline/shared/db";import{resolveDbDataDir as DC}from"@cline/shared/storage";function UC(){return DC()}function Z4($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function RC($){let J=tK($);if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,j=W.agentId,f=W.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof f!=="string"||!f.trim())continue;let X={agentId:j.trim(),rolePrompt:f};if(typeof W.modelId==="string"&&W.modelId.trim())X.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))X.maxIterations=Math.max(1,Math.floor(W.maxIterations));Q.push(X)}return Q}function zC($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class y2{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??UC()}init(){this.getRawDb()}ensureTeamDir(){if(!AC(this.teamDirPath))KC(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return GC(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=FC(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
586
+ `),$.end()}catch{$.destroy()}}function w3($,J){if(!$||!J)return!1;let Q=Buffer.from($,"utf8"),Z=Buffer.from(J,"utf8");return Q.length===Z.length&&vS(Q,Z)}function IK($,J){let Q=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Z=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",W=`Failed to start hub server on ${J.host}:${J.port}${J.pathname}: ${Z}`,j=Error(Q?`${W} (${Q})`:W);if(Q)$.code=Q,j.code=Q;if($ instanceof Error&&$.stack)j.stack=`${j.name}: ${j.message}
587
+ Caused by: ${$.stack}`;return j}async function sS($){return await new Promise((J,Q)=>{let Z=uS.createServer();Z.once("error",Q),Z.listen(0,$,()=>{let W=Z.address();if(!W||typeof W==="string"){Z.close(()=>Q(Error("Failed to resolve free port")));return}let j=W.port;Z.close((f)=>{if(f){Q(f);return}J(j)})})})}function oS($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var S3=new Map,xK="cline-hub-auth.",tS=30000;function mK($){return Array.isArray($)?$.join(","):$??""}function gK($){return $===32||$===9}function FQ($){let J=mK($).trim(),Q="bearer";if(J.length<=6||J.slice(0,6).toLowerCase()!=="bearer"||!gK(J.charCodeAt(6)))return null;let Z=7;while(Z<J.length&&gK(J.charCodeAt(Z)))Z+=1;return J.slice(Z).trim()||null}function eS($){for(let J of mK($).split(",")){let Q=J.trim();if(Q.startsWith(xK))return Q.slice(xK.length).trim()||null}return null}async function C2($){let J=$.owner??l1(),Q=$.host??"127.0.0.1",Z=$.pathname??"/hub",W=$.port??b8(),j=W===0?await sS(Q):W,f=j,X=j1(Q,j,Z),Y=u9(),V=c9(),H=new J4($);await H.start();let B=new _J(new OJ(H),$.telemetry),A=new Set,K=new Date().toISOString(),G={protocolVersion:bK,minClientProtocolVersion:kK,maxClientProtocolVersion:hK,capabilities:dS,coreVersion:e6.version,buildId:Y,pid:process.pid,startedAt:K},R=new Set,D,U,F=async()=>{if(U)return U;return U=(async()=>{if(D)clearInterval(D),D=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of A)z();if(A.clear(),await new Promise((z,P)=>{T.close((S)=>{if(S){P(S);return}z()})}),await new Promise((z,P)=>{O.close((S)=>{if(S){P(S);return}z()})}),await H.stop(),(await A0(J.discoveryPath))?.url===X)await y0(J.discoveryPath)})(),U},O=cS.createServer((L,z)=>{if((L.url??"/")==="/health"){let S=JSON.stringify({ok:!0,protocolVersion:G.protocolVersion,minClientProtocolVersion:G.minClientProtocolVersion,maxClientProtocolVersion:G.maxClientProtocolVersion,coreVersion:G.coreVersion,host:Q,port:f,url:X});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/status"){if(!w3(FQ(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}let S=JSON.stringify({hubId:H.getHubId(),...G,authToken:V,host:Q,port:f,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(S);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new EK(L.url??"/",`http://${Q}:${f}`).pathname==="/shutdown"&&L.method==="POST"){if(!w3(FQ(L.headers.authorization),V)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{F()});return}z.statusCode=404,z.end("Not found")}),T=new pS({noServer:!0});D=setInterval(()=>{for(let L of R){if(L.isAlive===!1){try{L.terminate?.()}catch{}R.delete(L);continue}L.isAlive=!1;try{L.ping?.()}catch{try{L.terminate?.()}catch{}R.delete(L)}}},tS),O.on("upgrade",(L,z,P)=>{if(new EK(L.url??"/",`http://${Q}:${f}`).pathname!==Z){z.destroy();return}if(!w3(eS(L.headers["sec-websocket-protocol"]),V)){aS(z);return}try{T.handleUpgrade(L,z,P,(b)=>{let u=b;u.isAlive=!0,u.on("pong",()=>{u.isAlive=!0}),R.add(u);let o=B.attach(iS(b));A.add(o),b.once("close",()=>{R.delete(u),o(),A.delete(o)})})}catch{nS(z)}});try{await new Promise((L,z)=>{O.once("error",(P)=>{z(IK(P,{host:Q,port:j,pathname:Z}))}),O.listen(j,Q,()=>{let P=O.address();if(!P||typeof P==="string"){z(IK(Error("Failed to resolve hub port"),{host:Q,port:j,pathname:Z}));return}f=P.port,X=j1(Q,f,Z),L()})})}catch(L){if(D)clearInterval(D),D=void 0;throw await H.stop().catch(()=>{return}),L}return await d9(J.discoveryPath,{hubId:H.getHubId(),protocolVersion:bK,minClientProtocolVersion:kK,maxClientProtocolVersion:hK,capabilities:[...G.capabilities],coreVersion:e6.version,buildId:Y,authToken:V,host:Q,port:f,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:Q,port:f,url:X,authToken:V,close:F}}async function DQ($){let J=$.owner??l1(),Q=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=$.host??"127.0.0.1",W=$.port??b8(),j=$.pathname??"/hub",f=j1(Z,W,j),X=J.discoveryPath,Y=(H)=>{if(!Q)P$(H.url,H.authToken);return H},V=S3.get(X);if(V){let H=await V;if(H.url===f)return Y({server:H,url:H.url,authToken:H.authToken,action:"reuse"})}return await l9(J.discoveryPath,async()=>{let H=await A0(J.discoveryPath);if(H?.url&&(H.url===f||$.allowPortFallback===!0)){let K=await p1(H.url,{authToken:H.authToken});if(K?.url&&lS(K).compatible&&await G1(K.url,{authToken:H.authToken}))return Y({url:K.url,authToken:H.authToken,action:"reuse"})}if(H?.url)await y0(J.discoveryPath);let A=async(K)=>{let G=C2({...K,owner:J});S3.set(X,G);try{let R=await G;return Y({server:R,url:R.url,authToken:R.authToken,action:"started"})}catch(R){throw S3.delete(X),R}};try{return await A($)}catch(K){if(!$.allowPortFallback||!oS(K))throw K;return await A({...$,port:0})}})}function cK(){return vK()==="production"?n0():E0()}function $C($){return vK()!=="production"&&!$}async function uK($){let J=i0({host:$.host,port:$.port,pathname:$.pathname});return await C2({...$,...J,owner:cK()})}async function dK($){let J=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=i0({host:$.host,port:$.port,pathname:$.pathname});return await DQ({...$,...Q,allowPortFallback:$.allowPortFallback??$C(J),owner:cK()})}RQ();var rK={};w(rK,{registerRemoteConfigSessionBlobUpload:()=>_Q,readRemoteConfigSessionBlobUploadMetadata:()=>C3,prepareRemoteConfigCoreIntegration:()=>E3,createRemoteConfigSessionMessagesArtifactUploader:()=>y3,buildRemoteConfigSessionBlobUploadMetadata:()=>zQ,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY:()=>LQ});import{buildRemoteConfigSessionBlobUploadMetadata as zQ,clearRemoteConfigSessionBlobUpload as JC,createClineTelemetryServiceConfig as QC,createSessionId as ZC,createRemoteConfigSessionMessagesArtifactUploader as WC,prepareRemoteConfigRuntime as jC,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as LQ,readRemoteConfigSessionBlobUploadMetadata as C3,registerRemoteConfigSessionBlobUpload as _Q}from"@cline/shared";function fC($,J){let Q=$.telemetry||J.telemetryService?{...J.telemetryService??{},...$.telemetry??{}}:void 0;if(!Q)return;return s1(QC(Q)).telemetry}function y3(){let $=WC();return{async uploadMessagesFile(J){await $.uploadMessagesFile(J)}}}async function E3($){let J=await jC($),Q=fC(J,$),Z=[J.pluginDefinition],W=J.claims?.subject,j=zQ(J.bundle?.remoteConfig,W),f;return{prepared:J,extensions:Z,telemetry:Q,applyToStartSessionInput(X){let Y=X.config.extensions??[],V=X.config.telemetry,H=j?X.config.sessionId?.trim()||ZC():X.config.sessionId;if(H&&j)f=H;let B=H&&j?_Q(H,J.bundle?.remoteConfig,W):void 0,A=B?{...X.sessionMetadata??{},[LQ]:B}:X.sessionMetadata;return{...X,...A?{sessionMetadata:A}:{},config:{...X.config,...H?{sessionId:H}:{},extensions:[...Y,...Z],telemetry:Q??V}}},async dispose(){if(f)JC(f)}}}var eK={};w(eK,{createTeamName:()=>MQ,DefaultRuntimeBuilder:()=>W4});import{hasRuntimeConfigExtension as LC}from"@cline/shared";import{nanoid as _C}from"nanoid";W1();var tK={};w(tK,{createLocalTeamStore:()=>I3,SqliteTeamStore:()=>y2,FileTeamStore:()=>TJ});import{appendFileSync as XC,existsSync as Q4,mkdirSync as iK,readdirSync as YC,readFileSync as nK,renameSync as VC,writeFileSync as HC}from"node:fs";import{join as b3}from"node:path";import{resolveTeamDataDir as BC}from"@cline/shared/storage";function aK(){return new Date().toISOString()}function h3($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function sK($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class TJ{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??BC()}init(){this.ensureTeamDir()}listTeamNames(){if(!Q4(this.teamDirPath))return[];return YC(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>Q4(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let J=this.readEnvelope($);return J?.teamState?sK(J.teamState):void 0}readHistory($,J=200){let Q=this.historyPath($);if(!Q4(Q))return[];return nK(Q,"utf8").split(`
588
+ `).map((Z)=>Z.trim()).filter(Boolean).map((Z)=>{try{return JSON.parse(Z)}catch{return}}).filter((Z)=>Z!==void 0).reverse().slice(0,J)}loadRuntime($){let J=this.readEnvelope($);return{state:J?.teamState?sK(J.teamState):void 0,teammates:J?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,J){this.ensureTeamSubdir($),XC(this.historyPath($),`${JSON.stringify({ts:aK(),eventType:J.type,payload:J})}
589
+ `,"utf8")}persistRuntime($,J,Q){this.ensureTeamSubdir($);let Z={version:1,updatedAt:aK(),teamState:J,teammates:Q},W=this.statePath($),j=`${W}.tmp`;HC(j,`${JSON.stringify(Z,null,2)}
590
+ `,"utf8"),VC(j,W)}markInProgressRunsInterrupted($,J){let Q=this.readEnvelope($);if(!Q?.teamState?.runs?.length)return[];let Z=Q.teamState.runs.filter((j)=>j.status==="queued"||j.status==="running").map((j)=>j.id);if(Z.length===0)return[];let W=new Date;return Q.teamState={...Q.teamState,runs:Q.teamState.runs.map((j)=>j.status==="queued"||j.status==="running"?{...j,status:"interrupted",error:J,endedAt:W}:j)},this.persistRuntime($,Q.teamState,Q.teammates),Z}ensureTeamDir(){if(!Q4(this.teamDirPath))iK(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let J=b3(this.ensureTeamDir(),h3($));if(!Q4(J))iK(J,{recursive:!0});return J}statePath($){return b3(this.ensureTeamDir(),h3($),"state.json")}historyPath($){return b3(this.ensureTeamDir(),h3($),"task-history.jsonl")}readEnvelope($){let J=this.statePath($);if(!Q4(J))return;try{let Q=JSON.parse(nK(J,"utf8"));if(Q?.version===1&&Q.teamState)return Q}catch{}return}}import{existsSync as AC,mkdirSync as KC}from"node:fs";import{join as GC}from"node:path";import{safeJsonParse as oK}from"@cline/shared";import{loadSqliteDb as FC,nowIso as k3}from"@cline/shared/db";import{resolveDbDataDir as DC}from"@cline/shared/storage";function UC(){return DC()}function Z4($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function RC($){let J=oK($);if(!Array.isArray(J))return[];let Q=[];for(let Z of J){if(!Z||typeof Z!=="object")continue;let W=Z,j=W.agentId,f=W.rolePrompt;if(typeof j!=="string"||!j.trim())continue;if(typeof f!=="string"||!f.trim())continue;let X={agentId:j.trim(),rolePrompt:f};if(typeof W.modelId==="string"&&W.modelId.trim())X.modelId=W.modelId.trim();if(typeof W.maxIterations==="number"&&Number.isFinite(W.maxIterations))X.maxIterations=Math.max(1,Math.floor(W.maxIterations));Q.push(X)}return Q}function zC($){return{...$,tasks:$.tasks.map((J)=>({...J,createdAt:new Date(J.createdAt),updatedAt:new Date(J.updatedAt)})),mailbox:$.mailbox.map((J)=>({...J,sentAt:new Date(J.sentAt),readAt:J.readAt?new Date(J.readAt):void 0})),missionLog:$.missionLog.map((J)=>({...J,ts:new Date(J.ts)})),runs:($.runs??[]).map((J)=>({...J,startedAt:new Date(J.startedAt),endedAt:J.endedAt?new Date(J.endedAt):void 0,nextAttemptAt:J.nextAttemptAt?new Date(J.nextAttemptAt):void 0,heartbeatAt:J.heartbeatAt?new Date(J.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),finalizedAt:J.finalizedAt?new Date(J.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((J)=>({...J,createdAt:new Date(J.createdAt),reviewedAt:J.reviewedAt?new Date(J.reviewedAt):void 0}))}}class y2{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??UC()}init(){this.getRawDb()}ensureTeamDir(){if(!AC(this.teamDirPath))KC(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return GC(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=FC(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
591
591
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
592
592
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
593
593
  version INTEGER NOT NULL
@@ -671,7 +671,7 @@ Caused by: ${$.stack}`;return j}async function sS($){return await new Promise((J
671
671
  version INTEGER NOT NULL DEFAULT 1,
672
672
  PRIMARY KEY(team_name, fragment_id)
673
673
  );
674
- `)}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}withTransaction($){let J=this.getRawDb();J.exec("BEGIN IMMEDIATE;");try{$(),J.exec("COMMIT;")}catch(Q){try{J.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let J=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Z4($)]);if(!J)return;let Q=tK(J.state_json);if(!Q)return;try{return zC(Q)}catch{return}}readHistory($,J=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[Z4($),J]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let J=Z4($),Q=this.readState(J),Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J]),W=Z?RC(Z.teammates_json):[];return{state:Q,teammates:W,interruptedRunIds:[]}}appendTeamEvent($,J,Q,Z){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
674
+ `)}run($,J=[]){return this.getRawDb().prepare($).run(...J)}queryOne($,J=[]){return this.getRawDb().prepare($).get(...J)??void 0}queryAll($,J=[]){return this.getRawDb().prepare($).all(...J)}withTransaction($){let J=this.getRawDb();J.exec("BEGIN IMMEDIATE;");try{$(),J.exec("COMMIT;")}catch(Q){try{J.exec("ROLLBACK;")}catch{}throw Q}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let J=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Z4($)]);if(!J)return;let Q=oK(J.state_json);if(!Q)return;try{return zC(Q)}catch{return}}readHistory($,J=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[Z4($),J]).flatMap((Q)=>{try{return[{eventType:Q.event_type,payload:JSON.parse(Q.payload_json),ts:Q.ts}]}catch{return[]}})}loadRuntime($){let J=Z4($),Q=this.readState(J),Z=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[J]),W=Z?RC(Z.teammates_json):[];return{state:Q,teammates:W,interruptedRunIds:[]}}appendTeamEvent($,J,Q,Z){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
675
675
  VALUES (?, ?, ?, ?, NULL, ?)`,[Z4($),k3(),J,JSON.stringify(Q),Z??null])}persistRuntime($,J,Q){let Z=Z4($),W=k3();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
676
676
  VALUES (?, ?, ?, ?)
677
677
  ON CONFLICT(team_name) DO UPDATE SET
@@ -718,15 +718,15 @@ Caused by: ${$.stack}`;return j}async function sS($){return await new Promise((J
718
718
  reviewed_by = excluded.reviewed_by,
719
719
  reviewed_at = excluded.reviewed_at,
720
720
  version = team_outcome_fragments.version + 1`,[Z,j.outcomeId,j.id,j.section,j.sourceAgentId,j.sourceRunId??null,j.content,j.status,j.reviewedBy??null,j.reviewedAt?j.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,J){let Q=Z4($),Z=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[Q]);if(Z.length===0)return[];let W=k3();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
721
- WHERE team_name = ? AND status IN ('queued', 'running')`,[J,W,Q]),Z.map((j)=>j.run_id)}handleTeamEvent($,J){this.appendTeamEvent($,J.type,J)}}function I3($={}){try{let J=new y2($);return J.init(),J}catch{let J=new TJ({teamDir:$.teamDir});return J.init(),J}}function O9($,J){return LC($,J)}function OC($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function TC($,J){return $.filter((Q)=>OC(Q.name,J))}function x3($,J){return I1(TC($,J))}var MC={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function qC($){let J=$.trim().toLowerCase();return MC[J]??J}function PC($,J){if(J.tools===void 0)return $;let Q=new Set(J.tools.map(qC));if(J.skills!==void 0)Q.add("skills");return $.filter((Z)=>Q.has(Z.name))}function M9(){return`team-${_C(5)}`}function T9($,J,Q,Z,W,j,f,X){let Y=c0[h1({mode:Q})],V=t2(J,Z,Q,W??o2);return x3(n$({cwd:$,...Y,enableSkills:!!f,...V,executors:{...f?{skills:f}:{},...X??{}}}),j)}function NC($){return T9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,wC,$.toolExecutors).some((J)=>J.name==="skills")}var wC=async()=>"";async function SC($){let J=B0();if(!c1({filePath:J}))return{tools:[]};let Q=new A2({clientFactory:S8({settingsPath:J})}),Z;try{Z=await B2(Q,{filePath:J})}catch(X){await Q.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let W=Z.filter((X)=>X.disabled!==!0),j=await Promise.allSettled(W.map((X)=>y8({serverName:X.name,provider:Q}))),f=[];for(let[X,Y]of j.entries())if(Y.status==="fulfilled")f.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${W[X].name}", skipping: ${V}`)}return{tools:f,shutdown:async()=>{await Q.dispose()}}}function CC($,J){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,J)}catch{}}function yC($){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 EC($){let J=c0[h1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??J.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??J.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 W4{teamRuntimeEntries=new Map;async build($){let{config:J,hooks:Q,extensions:Z,logger:W,telemetry:j,createSpawnTool:f,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:H}=$,B=$.onTeamEvent??(()=>{}),A=EC(J),K=J.workspaceRoot??J.cwd,G=$.toolPolicies??J.toolPolicies,R=B1(),D=[],U=J.teamName?.trim()||M9(),F=J.sessionId?.trim()||U,O=A.enableSpawnAgent?m8({workspaceRoot:K}):{configs:[],errors:[]},T=O.configs.some((m)=>m.skills!==void 0),L=O9(V,"rules"),z=O9(V,"skills"),P=z||T,S=O9(V,"workflows"),b=O9(V,"plugins"),u=L||z||S,o=!1,J0=Boolean(Y),t=Y,$1;for(let m of O.errors)(W??J.logger)?.log?.(`[agents] Failed to load agent config at ${m.path}: ${m.error.message}`);if(!t&&(u||T))t=_$({skills:P?{workspacePath:K,includePluginSkills:b,pluginSkillDirectories:b?$.pluginSkillDirectories:void 0,pluginPaths:J.pluginPaths,cwd:J.cwd}:{workspacePath:K},rules:{workspacePath:J.cwd},workflows:{workspacePath:J.cwd}});if(t)await t.start().catch(()=>{});let b$=A.enableTools&&z&&Boolean(t)&&t?.hasConfiguredSkills(J.skills)===!0&&NC({cwd:J.cwd,providerId:J.providerId,mode:A.mode,modelId:J.modelId,toolRoutingRules:J.toolRoutingRules,toolPolicies:G,toolExecutors:H}),n=t&&u?t.createExtension({includeRules:L,includeSkills:z,includeWorkflows:S,registerSkillsTool:b$,allowedSkillNames:J.skills}):void 0,O1=n?[...Z??J.extensions??[],n]:Z??J.extensions;if(A.enableTools){if(D.push(...T9(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H)),!A.disableMcpSettingsTools){let m=await SC(J.logger);D.push(...m.tools),$1=m.shutdown}}let C,F0=A.enableAgentTeams?I3():void 0,f0=F0?.loadRuntime(F),w0=f0?.state,k2=f0?.teammates??[],T1=new Map(k2.map((m)=>[m.agentId,m])),Y1=J.sessionId||U,Y4,I2=[],SJ=!1,M1=H$({providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey??"",baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:Q,extensions:O1,logger:W??J.logger,telemetry:$.telemetry??J.telemetry,workspaceMetadata:J.workspaceMetadata});if(A.enableSpawnAgent){if(O.configs.length>0)D.push(...x3(v8({configProvider:M1,agents:O.configs,createSubAgentTools:(m)=>A.enableTools?PC(T9(J.cwd,m.providerId??J.providerId,A.mode,m.modelId??J.modelId,J.toolRoutingRules,G,m.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(m.skills):void 0,H),m):[],hookErrorMode:J.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(Y1))this.teamRuntimeEntries.set(Y1,{delegatedAgentConfigProvider:M1});let CJ=()=>{if(!A.enableAgentTeams)return;let m=this.teamRuntimeEntries.get(Y1)??{delegatedAgentConfigProvider:M1};if(this.teamRuntimeEntries.set(Y1,m),C=m.runtime,!C){if(C=new T2({teamName:U,leadAgentId:J.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(Q0)=>{if(B(Q0),C&&F0){if(Q0.type==="teammate_spawned"&&Q0.teammate?.rolePrompt){let q1={agentId:Q0.agentId,rolePrompt:Q0.teammate.rolePrompt,modelId:Q0.teammate.modelId,maxIterations:Q0.teammate.maxIterations};T1.set(q1.agentId,q1)}if(Q0.type==="teammate_shutdown"&&!yC(Q0.reason))T1.delete(Q0.agentId);F0.handleTeamEvent(F,Q0),F0.persistRuntime(F,C.exportState(),Array.from(T1.values()))}}}),w0)C.hydrateState(w0),SJ=!0;m.runtime=C}if(!o){if(!C)return;o=!0;let Q0=Q8({runtime:C,leadAgentId:J.sessionId||"lead",restoredFromPersistence:Boolean(w0),restoredTeammates:k2,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(q1)=>{I2=q1,Y4?.addTools(q1)},createBaseTools:A.enableTools?()=>T9(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H):void 0,teammateConfigProvider:M1});if(SJ)C.recoverActiveRuns("runtime_recovered");if(Q0.restoredFromPersistence)X?.();D.push(...Q0.tools)}return C};if(A.enableSpawnAgent&&f){let m=f();D.push({...m,execute:async(Q0,q1)=>{return CJ(),m.execute(Q0,q1)}})}if(A.enableAgentTeams)CJ();let x2=x3(D,G),s9=x2.some((m)=>m.name==="submit_and_exit"&&m.lifecycle?.completesRun===!0),yJ=A.enableAgentTeams?()=>{let m=this.teamRuntimeEntries.get(Y1)?.runtime;if(!m)return;let Q0=m.listTasks(),q1=Q0.some((t1)=>t1.status==="in_progress"||t1.status==="pending"),mj=m.listRuns({}),WF=mj.some((t1)=>t1.status==="running"||t1.status==="queued");if(q1||WF){let t1=Q0.filter((x0)=>x0.status==="in_progress"||x0.status==="pending").map((x0)=>`${x0.id} (${x0.status}): ${x0.title}`).join(", "),vj=mj.filter((x0)=>x0.status==="running"||x0.status==="queued").map((x0)=>`${x0.id} (${x0.status})`).join(", "),o9=[];if(t1)o9.push(`Unfinished tasks: ${t1}`);if(vj)o9.push(`Active runs: ${vj}`);return`[SYSTEM] You still have team obligations. ${o9.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,ZF=s9?{requireCompletionTool:!0,...yJ?{completionGuard:yJ}:{}}:yJ?{completionGuard:yJ}:void 0;return{tools:x2,logger:W??J.logger,telemetry:j??J.telemetry,teamRuntime:C,teamRestoredFromPersistence:Boolean(w0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(Y1)?.delegatedAgentConfigProvider??M1,extensions:O1,completionPolicy:ZF,registerLeadAgent:(m)=>{if(Y4=m,I2.length>0)m.addTools(I1(I2,[...R]))},shutdown:async(m)=>{if(CC(C,m),this.teamRuntimeEntries.delete(Y1),await $1?.(),!J0)t?.stop()}}}}var QG={};w(QG,{requestDesktopToolApproval:()=>m3});import{mkdir as bC,readFile as hC,unlink as kC,writeFile as IC}from"node:fs/promises";import{join as JG}from"node:path";function xC($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function gC($){return new Promise((J)=>setTimeout(J,$))}async function g3($){try{await kC($)}catch{}}async function m3($,J={}){let Q=J.approvalDir?.trim(),Z=J.sessionId?.trim();if(!Q||!Z)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await bC(Q,{recursive:!0});let W=xC(`${$.toolCallId}`),j=JG(Q,`${Z}.request.${W}.json`),f=JG(Q,`${Z}.decision.${W}.json`),X=J.nowIso??(()=>new Date().toISOString());await IC(j,`${JSON.stringify({requestId:W,sessionId:Z,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
- `,"utf8");let Y=J.timeoutMs??300000,V=J.pollIntervalMs??200,H=Date.now();while(Date.now()-H<Y){try{let B=await hC(f,"utf8"),A=JSON.parse(B),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([g3(f),g3(j)]),K}catch{}await gC(V)}return await g3(j),{approved:!1,reason:"Tool approval request timed out"}}W1();var fG={};w(fG,{syncPluginMcpServersToSettings:()=>d3,removePluginMcpServersFromSettings:()=>MJ,disablePluginMcpServersInSettings:()=>l3});import{existsSync as mC,mkdirSync as vC,readFileSync as cC,writeFileSync as uC}from"node:fs";import{dirname as WG,isAbsolute as dC,relative as lC,resolve as ZG}from"node:path";function E2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function q9($,J){let Q=lC(ZG($),ZG(J));return Q===""||!Q.startsWith("..")&&!dC(Q)}function v3($){if(!mC($))return{mcpServers:{}};try{let J=JSON.parse(cC($,"utf8"));if(E2(J))return J}catch(J){throw Error(`Invalid MCP settings at "${$}": ${J instanceof Error?J.message:String(J)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function c3($){if(E2($.mcpServers))return{...$.mcpServers};return{}}function u3($,J,Q){vC(WG($),{recursive:!0}),uC($,`${JSON.stringify({...J,mcpServers:Q},null,2)}
723
- `,"utf8")}function jG($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((J)=>J.trim()).filter((J)=>J.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((J)=>J.trim()).filter((J)=>J.length>0))]}}function N9($){if(!E2($))return;let J=$.metadata;return E2(J)?J:void 0}function P9($,J){let Q=N9($);if(!Q||Q.source!=="plugin")return!1;let Z=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,W=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(J.pluginName&&Z===J.pluginName){if(!J.pluginPath||W===J.pluginPath)return!0}if(W&&J.pluginPath&&(W===J.pluginPath||q9(J.pluginPath,W)||q9(W,J.pluginPath)))return!0;if(Z&&J.pluginNames?.some((j)=>j===Z))return!0;if(W&&J.pluginPaths?.some((j)=>W===j||q9(j,W)||q9(W,j)))return!0;return!1}function pC($){let J=E2($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:WG($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...J,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function rC($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let J=await B8({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],Z=[],W=(J.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of J.extensions??[]){let f=j.__clinePluginPath;if(!f)continue;if(!j.setup){Q.push({pluginName:j.name,pluginPath:f});continue}let X=[],Y={registerTool:(V)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(V)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');X.push(V)}};try{await j.setup(Y,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(V){W.push({pluginPath:f,pluginName:j.name,message:V instanceof Error?V.message:String(V)});continue}Q.push({pluginName:j.name,pluginPath:f});for(let V of X)Z.push({pluginName:j.name,pluginPath:f,server:{...V,metadata:{...V.metadata??{},source:"plugin",pluginName:j.name,pluginPath:f}}})}return{plugins:Q,servers:Z,failures:W}}finally{await J.shutdown().catch(()=>{})}}async function d3($){let J=$.settingsPath??B0(),Q={mutations:[],failures:[]},Z;try{Z=await rC($)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}Q.failures.push(...Z.failures);let W;try{W=v3(J)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}let j=c3(W),f=new Map,X=new Map;for(let V of Z.plugins)f.set(V.pluginPath,new Set),X.set(V.pluginPath,V.pluginName);let Y=CQ(Z.servers.map((V)=>({server:V.server,owner:V,ownerLabel:V.pluginName})));for(let V of Y){let H=V.owner;if(!f.has(H.pluginPath))f.set(H.pluginPath,new Set);if(V.name)f.get(H.pluginPath)?.add(V.name);if(!V.registration){Q.mutations.push({name:V.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:V.loadError??"invalid MCP server registration"});continue}let B=j[V.registration.name];if(B!==void 0){if(!P9(B,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[V.registration.name]=pC({registration:V.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:E2(B)?B:void 0}),Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:B===void 0?"created":"updated"})}for(let[V,H]of Object.entries(j)){let B=N9(H),A=typeof B?.pluginPath==="string"?B.pluginPath:"",K=f.get(A);if(K&&P9(H,{pluginPath:A})&&!K.has(V))delete j[V],Q.mutations.push({name:V,pluginName:typeof B?.pluginName==="string"?B.pluginName:X.get(A)??"plugin",pluginPath:A,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((V)=>V.action!=="skipped"))try{u3(J,W,j)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)})}return Q}function l3($){let J=$.settingsPath??B0(),Q;try{Q=v3(J)}catch{return[]}let Z=c3(Q),W=jG($),j=[];for(let[f,X]of Object.entries(Z)){if(!E2(X)||!P9(X,W))continue;let Y=N9(X);Z[f]={...X,disabled:!0},j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"disabled"})}if(j.length>0)u3(J,Q,Z);return j}function MJ($){let J=$.settingsPath??B0(),Q;try{Q=v3(J)}catch{return[]}let Z=c3(Q),W=jG($),j=[];for(let[f,X]of Object.entries(Z)){if(!P9(X,W))continue;let Y=N9(X);delete Z[f],j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"removed"})}if(j.length>0)u3(J,Q,Z);return j}W1();var HG={};w(HG,{uninstallPlugin:()=>t3});import{existsSync as f4,readdirSync as iC,readFileSync as nC,rmdirSync as aC,rmSync as sC,statSync as oC}from"node:fs";import{basename as t0,dirname as E$,extname as tC,isAbsolute as eC,join as o1,relative as $y,resolve as j4,sep as p3}from"node:path";import{discoverPluginModulePaths as Jy,resolvePluginConfigSearchPaths as Qy}from"@cline/shared/storage";var s3="_installed",Zy="package",Wy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function r3($){return $.trim().toLowerCase()}function X1($,J){let Q=J?.trim();if(!Q)return;$.add(Q)}function jy($){return $.replace(/-[0-9a-f]{12}$/i,"")}function i3($){let J=tC($);return J?$.slice(0,-J.length):$}function n3($){if(!f4($))return;try{let J=JSON.parse(nC($,"utf8"));return typeof J.name==="string"?J.name.trim():void 0}catch{return}}function o3($,J){let Q=$y(J,$);return Q===""||!Q.startsWith("..")&&!eC(Q)}function XG($){let Q=j4($).split(p3),Z=Q.lastIndexOf(s3);if(Z<0)return;let W=Q[Z+1];if(!W)return;let j=Wy.get(W)??1,f=Z+2+j;if(Q.length<f)return;let X=Q.slice(0,f).join(p3)||p3;return f4(X)?X:void 0}function w9($){try{return iC($,{withFileTypes:!0})}catch{return[]}}function fy($){let J=o1($,s3);if(!f4(J))return[];let Q=[];for(let Z of w9(J)){if(!Z.isDirectory())continue;let W=o1(J,Z.name);if(Z.name==="git"){for(let j of w9(W)){if(!j.isDirectory())continue;let f=o1(W,j.name);for(let X of w9(f))if(X.isDirectory())Q.push(o1(f,X.name))}continue}for(let j of w9(W))if(j.isDirectory())Q.push(o1(W,j.name))}return Q.sort((Z,W)=>Z.localeCompare(W))}function YG($){try{return Jy($)}catch{return[]}}function a3($){let J=YG($),Q=new Set;X1(Q,t0($)),X1(Q,jy(t0($))),X1(Q,n3(o1($,"package.json"))),X1(Q,n3(o1($,Zy,"package.json")));for(let Z of J)X1(Q,t0(Z)),X1(Q,i3(t0(Z)));return{installPath:$,entryPaths:J,names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!0}}function Xy($,J){let Q=j4($),Z=J.find((f)=>o3(Q,f));if(!Z)return;let W=E$(Q);while(W!==Z&&W!==E$(W)){if(f4(o1(W,"package.json")))return W;W=E$(W)}let j=t0(Q);if((j==="index.ts"||j==="index.js")&&E$(Q)!==Z)return E$(Q);return Q}function VG($,J){let Q=Xy($,J);if(!Q)return;let Z=new Set;return X1(Z,t0($)),X1(Z,i3(t0($))),X1(Z,t0(Q)),X1(Z,i3(t0(Q))),X1(Z,n3(o1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...Z].sort((W,j)=>W.localeCompare(j)),installed:!1}}function Yy($){let J=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Qy(J).filter((Q)=>f4(Q))}function Vy($){let J=new Map;for(let Q of $){for(let Z of fy(Q))J.set(Z,a3(Z));for(let Z of YG(Q)){let W=XG(Z);if(W){if(!J.has(W))J.set(W,a3(W));continue}let j=VG(Z,$);if(j)J.set(j.installPath,j)}}return[...J.values()].sort((Q,Z)=>Q.installPath.localeCompare(Z.installPath))}function Hy($,J){let Q=r3(J);if(!Q)return!1;if(r3($.installPath)===Q)return!0;return $.names.some((Z)=>r3(Z)===Q)}function By($,J,Q){let Z=j4($);for(let j of J){if(o3(Z,j.installPath))return j;if(j.entryPaths.some((f)=>j4(f)===Z))return j}let W=XG(Z);if(W)return a3(W);if(f4(Z))return VG(Z,Q);return}function Ay($){let J=M0(),Q=J.disabledPlugins;if(!Q?.length)return;let Z=Q.filter((W)=>{let j=j4(W);if(o3(j,$.installPath))return!1;return!$.entryPaths.some((f)=>j4(f)===j)});if(Z.length===Q.length)return;k1({...J,disabledPlugins:Z})}function Ky($){let J=E$($);while(J!==E$(J)&&t0(J)!==s3){try{aC(J)}catch{return}J=E$(J)}}function Gy($){return`${$.names[0]??t0($.installPath)} at ${$.installPath}`}async function t3($){let J=Yy($),Q=Vy(J),Z=$.path?.trim(),W=$.name?.trim(),j;if(Z){if(j=By(Z,Q,J),!j)throw Error(`No plugin found at ${Z}`)}else{if(!W)throw Error("plugin uninstall requires a plugin name");let X=Q.filter((Y)=>Hy(Y,W));if(X.length===0)throw Error(`No plugin found matching "${W}"`);if(X.length>1)throw Error(`Multiple plugins match "${W}": ${X.map(Gy).join(", ")}`);j=X[0]}let f=oC(j.installPath,{throwIfNoEntry:!1});if(!f)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(MJ({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),sC(j.installPath,{recursive:f.isDirectory(),force:!0}),Ay(j),j.installed)Ky(j.installPath);return{name:W||j.names[0]||t0(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var CG={};w(CG,{updateLocalProvider:()=>I9,saveLocalProviderSettings:()=>fj,saveLocalProviderOAuthCredentials:()=>Hj,resolveLocalClineAuthToken:()=>Aj,refreshProviderModelsFromSource:()=>Xj,normalizeOAuthProvider:()=>Yj,loginLocalProvider:()=>Vj,loginAndSaveLocalProviderOAuthCredentials:()=>Bj,listLocalProviders:()=>Wj,getLocalProviderModels:()=>jj,ensureCustomProvidersLoaded:()=>b9,deleteLocalProvider:()=>x9,addLocalProvider:()=>Zj});import*as N0 from"@cline/llms";import{existsSync as Fy,mkdirSync as Dy,readFileSync as Uy,writeFileSync as Ry}from"node:fs";import{mkdir as zy,readFile as Ly,writeFile as _y}from"node:fs/promises";import{dirname as e3,join as Oy}from"node:path";import*as I0 from"@cline/llms";import{ModelCapabilitySchema as Ty,ProviderCapabilitySchema as My,ProviderClientSchema as qy,ProviderProtocolSchema as Py}from"@cline/shared";import{z as i}from"zod";var Ny=i.object({id:i.string().optional(),name:i.string().optional(),maxTokens:i.number().optional(),contextWindow:i.number().optional(),maxInputTokens:i.number().optional(),capabilities:i.array(Ty).optional(),supportsVision:i.boolean().optional(),supportsAttachments:i.boolean().optional(),supportsReasoning:i.boolean().optional()}).passthrough(),wy=i.object({name:i.string(),baseUrl:i.string(),defaultModelId:i.string().optional(),protocol:Py.optional(),client:qy.optional(),capabilities:i.array(My).optional(),modelsSourceUrl:i.string().optional()}).passthrough(),BG=i.object({provider:wy.optional(),models:i.record(i.string(),Ny).optional()}).passthrough(),AG=i.object({version:i.literal(1),providers:i.record(i.string(),BG)}),Sy=i.object({version:i.literal(1),providers:i.record(i.string(),i.unknown())}),S9=new Set;function KG($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function b2($){return Oy(e3($.getFilePath()),"models.json")}function C9(){return{version:1,providers:{}}}function GG($){let J=Sy.safeParse($);if(!J.success)return C9();let Q={};for(let[Z,W]of Object.entries(J.data.providers)){let j=BG.safeParse(W);if(j.success)Q[Z]=j.data}return{version:1,providers:Q}}function $j($){if(!Fy($))return C9();try{let J=Uy($,"utf8");return GG(JSON.parse(J))}catch{}return C9()}async function X4($){try{let J=await Ly($,"utf8");return GG(JSON.parse(J))}catch{}return C9()}function FG($,J){Dy(e3($),{recursive:!0});let Q=AG.parse(J);Ry($,`${JSON.stringify(Q,null,2)}
724
- `,"utf8")}async function y9($,J){await zy(e3($),{recursive:!0});let Q=AG.parse(J);await _y($,`${JSON.stringify(Q,null,2)}
725
- `,"utf8")}function DG($,J){return{id:$,name:J.name??$,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images"),supportsReasoning:J.capabilities?.includes("reasoning")||J.thinkingConfig!=null}}function UG($){if(!$||$.length===0)return;let J=new Set;if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("tools"))J.add("tools");return J.size>0?[...J]:void 0}function RG($){let J=new Set;if(!$||$.length===0)return[...J];if($.includes("streaming"))J.add("streaming");if($.includes("tools"))J.add("tools");if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("vision"))J.add("images"),J.add("files");return[...J]}function Cy($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function zG($,J){return $??J??"openai-chat"}function LG($,J,Q){return $??Q??(J==="openai-responses"?"openai":"openai-compatible")}function _G($,J,Q){let Z=new Set(J?.capabilities??Q??[]);if(J?.supportsVision)Z.add("images");if(J?.supportsAttachments)Z.add("files");if(J?.supportsReasoning)Z.add("reasoning");return{id:$,name:J?.name??$,maxTokens:J?.maxTokens,contextWindow:J?.contextWindow,maxInputTokens:J?.maxInputTokens,capabilities:Z.size>0?[...Z]:void 0}}function yy($,J){for(let[Q,Z]of Object.entries(J??{})){let W=Z.id?.trim()||Q.trim();if(!W)continue;I0.registerModel($,W,_G(W,Z))}}function Ey($,J,Q){return{...J??{},id:$,name:J?.name??$,capabilities:J?.capabilities??Q}}function by($){return Object.assign({},...I0.resolveProviderModelCatalogKeys($).map((Q)=>I0.getGeneratedModelsForProvider(Q)))}function hy($){let J=$.provider.trim();if(!J||I0.isBuiltInProviderId(J))return;let Q=$.baseUrl?.trim();if(!Q)return;let Z=I0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J],W=by(J),j=RG($.capabilities),f=j.length>0?j:void 0,X=$.model?.trim(),Y={...W,...Z?.models??{}};if(X)Y[X]=Ey(X,Y[X],f);let V=Object.keys(Y).filter(Boolean),H=X||V[0];if(!H)return;let B=zG($.protocol,Z?.provider.protocol),A=LG($.client,B,Z?.provider.client);I0.registerProvider({provider:{id:J,name:Z?.provider.name??KG(J),description:Z?.provider.description,protocol:B,client:A,baseUrl:Q,modelsSourceUrl:Z?.provider.modelsSourceUrl,defaultModelId:H,capabilities:UG($.capabilities)??Z?.provider.capabilities,source:"file"},models:Y})}function E9($){for(let J of Object.values($.providers))hy(J.settings)}function qJ($,J){let Q=J.models??{};if(!Cy(J.provider)){yy($,Q);return}let Z=RG(J.provider.capabilities),W=Object.entries(Q).map(([V,H])=>({id:H.id?.trim()||V.trim(),model:H})).filter(({id:V})=>V.length>0),j=J.provider.defaultModelId?.trim()||W[0]?.id||"default",f=zG(J.provider.protocol,void 0),X=LG(J.provider.client,f,void 0),Y=Object.fromEntries(W.map(({id:V,model:H})=>[V,{..._G(V,H,Z.length>0?Z:void 0),status:"active"}]));I0.registerProvider({provider:{id:$,name:J.provider.name.trim()||KG($),protocol:f,client:X,baseUrl:J.provider.baseUrl,modelsSourceUrl:J.provider.modelsSourceUrl,defaultModelId:j,capabilities:UG(J.provider.capabilities),source:"file"},models:Y})}function OG($){let J=b2($);if(S9.has(J))return;let Q=$j(J);for(let[Z,W]of Object.entries(Q.providers))qJ(Z,W);S9.add(J)}async function b9($){let J=b2($);if(S9.has(J))return;let Q=await X4(J);for(let[Z,W]of Object.entries(Q.providers))qJ(Z,W);S9.add(J)}var ky="cline-pass";function Iy($){return $.apiKey??$.auth?.apiKey}function xy($){return($.auth?.accessToken?.trim()??"").length>0}function MG($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function gy($){let J=$.split(/\s+/).filter(Boolean);if(J.length===0)return"?";if(J.length===1)return J[0].slice(0,2).toUpperCase();return`${J[0][0]}${J[1][0]}`.toUpperCase()}function my($){let J=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let Z of $)Q=Q*31+Z.charCodeAt(0)>>>0;return J[Q%J.length]}function qG($){return Object.entries($).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>DG(J,Q))}async function vy($,J){let Q=await N0.getModelsForProvider($);if(!J)return Q;let Z=await F6($,{loadPrivateOnAuth:!0,failOnError:!1},J);return Z?.knownModels?{...Q,...Z.knownModels}:Q}function Jj($){return[...new Set(($??[]).map((J)=>J.trim()).filter(Boolean))]}function cy($){if(!$?.length)return;return[...new Set($)]}function uy($,J){return cy([...$??[],...J??[]])}function dy($){let J=$?.popularRank;return typeof J==="number"&&Number.isFinite(J)?J:Number.MAX_SAFE_INTEGER}function ly($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.path==="string"&&J.path.trim().length>0&&typeof J.label==="string"&&J.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(J.type))}function py($){let J=$?.configFields;if(!Array.isArray(J))return;return J.filter(ly)}var h9={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},TG={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function ry($){if(!$)return[h9];if($.source!=="system")return $.baseUrl?[h9,TG]:[h9];let J=[];if($.env?.length)J.push(h9);if($.baseUrl)J.push(TG);return J}function iy($,J){return J.split(".").reduce((Q,Z)=>{if(!Q||typeof Q!=="object")return;return Q[Z]},$)}function ny($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function ay($,J,Q){if(!$?.length)return;let Z={};for(let W of $){let f=ny(W.path==="baseUrl"&&J?.baseUrl===void 0?Q?.baseUrl:iy(J,W.path))??W.defaultValue;if(f!==void 0)Z[W.path]=f}return Z}function PG($){let J=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return J.length>0?Object.fromEntries(J):void 0}function Qj($,J){let Q=J?.includes("vision")??!1,Z=J?.includes("reasoning")??!1;return Object.fromEntries($.map((W)=>[W,{id:W,name:W,supportsVision:Q,supportsAttachments:Q,supportsReasoning:Z}]))}async function NG($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let J=$.modelsSourceUrl?await u5($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...J])]}function wG($,J){let Q=$.read(),Z=!1;if(Q.providers[J])delete Q.providers[J],Z=!0;if(Q.lastUsedProvider===J)delete Q.lastUsedProvider,Z=!0;if(Z)$.write(Q);N0.unregisterProvider(J)}async function Zj($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=J.baseUrl.trim(),W=J.apiKey?.trim()??"";if(!Z&&!W){let G=b2($);if((await X4(G)).providers[Q]){let D=await x9($,{providerId:Q});return{providerId:Q,settingsPath:D.settingsPath,modelsPath:D.modelsPath,modelsCount:0}}return wG($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let j=J.name.trim();if(!j)throw Error("name is required");if(!Z)throw Error("baseUrl is required");let f=Jj(J.models),X=J.modelsSourceUrl?.trim(),Y=await NG({providerId:Q,explicitModels:f,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=J.defaultModelId?.trim()&&Y.includes(J.defaultModelId.trim())?J.defaultModelId.trim():Y[0],H=J.capabilities?.length?[...new Set(J.capabilities)]:void 0,B=PG(J.headers);$.saveProviderSettings({provider:Q,apiKey:W||void 0,baseUrl:Z,headers:B,timeout:J.timeoutMs,model:V,protocol:J.protocol,client:J.client},{setLastUsed:!1});let A=b2($),K=await X4(A);return K.providers[Q]={provider:{name:j,baseUrl:Z,defaultModelId:V,protocol:J.protocol,client:J.client,capabilities:H,modelsSourceUrl:X},models:Qj(Y,H)},await y9(A,K),qJ(Q,K.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function I9($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=b2($),W=await X4(Z),j=W.providers[Q];if(!j){let T=$.getProviderSettings(Q);if(!T)throw Error(`provider "${Q}" does not exist`);let L=J.modelsSourceUrl?.trim(),z=Jj(J.models)[0]??T.model?.trim();if(!z&&!L)throw Error(`provider "${Q}" cannot be updated because no model is configured`);j={provider:{name:J.name?.trim()||MG(Q),baseUrl:J.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:z,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:z?Qj([z],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let f=J.name?.trim()??j.provider.name.trim();if(!f)throw Error("name is required");let X=J.baseUrl?.trim()??j.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=J.capabilities===void 0?j.provider.capabilities:J.capabilities===null?void 0:[...new Set(J.capabilities)],V=J.protocol===void 0?j.provider.protocol:J.protocol??void 0,H=J.client===void 0?j.provider.client:J.client??void 0,B=Jj(J.models),A=J.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:J.modelsSourceUrl?.trim()||void 0,K=J.models!==void 0||J.modelsSourceUrl!==void 0&&!!A,G=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),R=await NG({providerId:Q,explicitModels:B,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let D=J.defaultModelId===void 0?j.provider.defaultModelId?.trim():J.defaultModelId?.trim(),U=D&&R.includes(D)?D:R[0],O={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:X,model:U};if(V)O.protocol=V;else delete O.protocol;if(H)O.client=H;else delete O.client;if(J.apiKey!==void 0){let T=J.apiKey?.trim()??"";if(T)O.apiKey=T;else delete O.apiKey}if(J.headers!==void 0){let T=PG(J.headers);if(T)O.headers=T;else delete O.headers}if(J.timeoutMs!==void 0)if(typeof J.timeoutMs==="number")O.timeout=J.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),W.providers[Q]={provider:{name:f,baseUrl:X,defaultModelId:U,protocol:V,client:H,capabilities:Y,modelsSourceUrl:A},models:Qj(R,Y)},await y9(Z,W),qJ(Q,W.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z,modelsCount:R.length}}async function x9($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=b2($),W=await X4(Z);if(!W.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete W.providers[Q],await y9(Z,W),N0.unregisterProvider(Q),wG($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z}}async function Wj($,J={}){let Q=$.read(),Z=N0.getProviderIds(),W=await Promise.all(Z.map(async(f)=>{let[X,Y]=await Promise.all([N0.getProvider(f),N0.getModelsForProvider(f)]),V=qG(Y),H=Q.providers[f]?.settings,B=X?.name??MG(f),A=uy(X?.capabilities,H?.capabilities),K=py(X?.metadata)??ry(X);return{provider:{id:f,name:B,models:V.length,color:my(f),letter:gy(B),enabled:Boolean(H),apiKey:H?Iy(H):void 0,oauthAccessTokenPresent:H?xy(H):void 0,baseUrl:H?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:H?.protocol??X?.protocol,client:H?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:ay(K,H,X),modelList:V},rank:dy(X?.metadata)}}));W.sort((f,X)=>{if(f.rank!==X.rank)return f.rank-X.rank;return f.provider.name.localeCompare(X.provider.name)||f.provider.id.localeCompare(X.provider.id)});let j=W.map((f)=>f.provider);if(J.isClinePassEnabled!==!0)j=j.filter((f)=>f.id!==ky);return{providers:j,settingsPath:$.getFilePath()}}async function jj($,J){let Q=$.trim(),Z=await vy(Q,J),W=qG(Z);return{providerId:Q,models:W}}function k9($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function SG($,J){if(!k9(J))return k9($)?{...$}:void 0;let Q=k9($)?{...$}:{};for(let[Z,W]of Object.entries(J)){if(W==null||W===""){delete Q[Z];continue}if(k9(W)){let j=SG(Q[Z],W);if(j&&Object.keys(j).length>0)Q[Z]=j;else delete Q[Z];continue}Q[Z]=W}return Object.keys(Q).length>0?Q:void 0}function fj($,J){let Q=J.providerId.trim();if(J.enabled===!1){let j=$.read();if(delete j.providers[Q],j.lastUsedProvider===Q)delete j.lastUsedProvider;return $.write(j),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let W={...$.getProviderSettings(Q)??{},provider:Q};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(J,j)&&typeof J[j]==="string")if(J[j].trim().length===0)delete W[j];else W[j]=J[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(J,j))W[j]=J[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(J,j)&&J[j]!=null){let f=SG(W[j],J[j]);if(f)W[j]=f;else delete W[j]}return $.saveProviderSettings(W,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function Xj($,J){let Q=J.trim(),Z=$.getProviderSettings(Q),j=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,f=Z?.baseUrl?.trim()||j?.baseUrl?.trim(),X=d5(f,j?.baseUrl,j?.modelsSourceUrl);if(!Z||!j||!f||!X)return{providerId:Q,refreshed:!1};let Y=await I9($,{providerId:Q,name:j.name,baseUrl:f,apiKey:Z.apiKey,headers:Z.headers??null,timeoutMs:Z.timeout??null,modelsSourceUrl:X,protocol:Z.protocol??j.protocol??null,client:Z.client??j.client??null,capabilities:Z.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:Y.modelsCount}}function Yj($){let J=$.trim().toLowerCase(),Q=Z0(J);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function Vj($,J,Q,Z){let W=Z0($);if(!W)throw Error(`provider "${$}" does not support OAuth login`);let j=T8({onPrompt:async(f)=>f.defaultValue??"",openUrl:Q,onOpenUrlError:({error:f})=>{throw f instanceof Error?f:Error(String(f))}});return W.login({settings:J,callbacks:j,telemetry:Z})}function Hj($,J,Q,Z,W){return x$({manager:$,providerId:J,settings:Q,credentials:Z,setLastUsed:W?.setLastUsed})}async function Bj($,J,Q,Z){let W=T8({onPrompt:async(j)=>j.defaultValue??"",openUrl:Q,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return z4($,J,{callbacks:W,telemetry:Z})}function Aj($){let J=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return J&&J.length>0?J:void 0}var yG={};w(yG,{getProviderConfigFields:()=>Kj});import*as g9 from"@cline/llms";var sy=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],oy={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function ty($,J){let Q={};for(let Z of sy){let W=$[Z],j=J[Z];if(W||j)Q[Z]={...W,...j}}return Q}function ey($){let J=oy[$.providerId];if(!J)return $;return{...$,description:J.description??$.description,fields:J.mode==="replace"?J.fields:ty($.fields,J.fields)}}var $E=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function JE($,J){if(!J?.provider.baseUrl)return!1;if(J.provider.source!=="system")return!0;return $E.has($)}function Kj($){let J=g9.normalizeProviderId($);if(I$(J))return{providerId:J,authMethod:"oauth",fields:{}};let Q=g9.MODEL_COLLECTIONS_BY_PROVIDER_ID[J];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:J,authMethod:"local",fields:{}};let Z=Q?.provider.baseUrl,W={apiKey:{}};if(JE(J,Q))W.baseUrl={defaultValue:Z};return ey({providerId:J,authMethod:"api-key",fields:W})}var kG={};w(kG,{resolveLegacyClineAuth:()=>Dj,migrateLegacyProviderSettings:()=>PJ});import{existsSync as QE,readFileSync as ZE}from"node:fs";import{dirname as WE,join as Gj}from"node:path";import*as v9 from"@cline/llms";import{resolveClineDataDir as jE}from"@cline/shared/storage";var m9="openai",hG=v9.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,EG=128000;function Dj($){let J=$?.trim();if(!J)return;try{let Q=JSON.parse(J);if(!Q)return;let Z=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:Z,accountId:Q.userInfo?.id}}catch{return}}function E($){let J=$?.trim();return J?J:void 0}function bG($){if(!QE($))return;try{let J=ZE($,"utf8"),Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function fE($){let J=$.dataDir??jE(),Q=$.globalStatePath??Gj(J,"globalState.json"),Z=$.secretsPath??Gj(J,"secrets.json"),W=bG(Q),j=bG(Z);if(!W&&!j)return;return{globalState:W??{},secrets:j??{}}}function Fj($){if($===m9)return hG;return $}function XE($,J,Q,Z){let W=Q==="plan"?"planMode":"actMode",j=J===Z?E(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[J];return(X?E(typeof $[X]==="string"?$[X]:void 0):void 0)??j}function YE($,J,Q){let Z=Q==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,W=Q==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,j=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,f=(J==="gemini"?W:void 0)??Z,X=f==="none"||f==="low"||f==="medium"||f==="high"?f:void 0,Y=typeof j==="number"&&Number.isInteger(j)&&j>0?j:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function VE($){let J=$["openai-codex-oauth-credentials"];if(!J)return;try{let Q=JSON.parse(J),Z=E(Q.access_token),W=E(Q.refresh_token),j=E(Q.accountId);if(!Z&&!W&&!j)return;return{...Z?{apiKey:Z}:{},auth:{...Z?{accessToken:Z}:{},...W?{refreshToken:W}:{},...j?{accountId:j}:{}}}}catch{return}}function HE($){let J=v9.getGeneratedModelsForProvider($);return Object.keys(J)[0]??void 0}function BE($,J,Q,Z){let W=Fj($),j=E(Z==="plan"?J.planModeApiProvider:J.actModeApiProvider),f=XE(J,$,Z,j)??HE(W),X=YE(J,W,Z),Y=typeof J.requestTimeoutMs==="number"&&Number.isInteger(J.requestTimeoutMs)&&J.requestTimeoutMs>0?J.requestTimeoutMs:void 0,V={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,VE(Q));if($==="cline")try{let U=E(Q["cline:clineAccountId"]);if(U)H.auth={...H.auth??{},...Dj(U)}}catch{}if($===m9&&J.openAiHeaders)H.headers=J.openAiHeaders;if($==="bedrock"){let U=J.awsAuthentication==="profile"||J.awsUseProfile===!0;H.aws={accessKey:E(Q.awsAccessKey),secretKey:E(Q.awsSecretKey),sessionToken:E(Q.awsSessionToken),region:E(J.awsRegion),authentication:J.awsAuthentication,profile:U?E(J.awsProfile):void 0,usePromptCache:J.awsBedrockUsePromptCache,useCrossRegionInference:J.awsUseCrossRegionInference,useGlobalInference:J.awsUseGlobalInference,endpoint:E(J.awsBedrockEndpoint),customModelBaseId:E(Z==="plan"?J.planModeAwsBedrockCustomModelBaseId:J.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:E(J.vertexProjectId),region:E(J.vertexRegion)};if($===m9&&(J.azureApiVersion||J.azureIdentity!==void 0))H.azure={apiVersion:E(J.azureApiVersion),useIdentity:J.azureIdentity};if($==="sapaicore")H.sap={clientId:E(Q.sapAiCoreClientId),clientSecret:E(Q.sapAiCoreClientSecret),tokenUrl:E(J.sapAiCoreTokenUrl),resourceGroup:E(J.sapAiResourceGroup),deploymentId:E(Z==="plan"?J.planModeSapAiCoreDeploymentId:J.actModeSapAiCoreDeploymentId),useOrchestrationMode:J.sapAiCoreUseOrchestrationMode};if($==="oca"){H.oca={mode:J.ocaMode};let U=E(Q.ocaRefreshToken);if(U)H.auth={...H.auth??{},refreshToken:U}}if($==="qwen")H.apiLine=J.qwenApiLine;if($==="moonshot")H.apiLine=J.moonshotApiLine;if($==="zai")H.apiLine=J.zaiApiLine;if($==="minimax")H.apiLine=J.minimaxApiLine;let B={anthropic:J.anthropicBaseUrl,openai:J.openAiBaseUrl,ollama:J.ollamaBaseUrl,lmstudio:J.lmStudioBaseUrl,litellm:J.liteLlmBaseUrl,gemini:J.geminiBaseUrl,requesty:J.requestyBaseUrl,asksage:J.asksageApiUrl,dify:J.difyBaseUrl,oca:J.ocaBaseUrl,aihubmix:J.aihubmixBaseUrl,sapaicore:J.sapAiCoreBaseUrl},A=E(V[$]),K=E(B[$]),G={provider:W,...A?{apiKey:A}:{},...f?{model:f}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...H},R=z8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function AE($,J){if($!==hG)return;if(!J.baseUrl||!J.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:J.baseUrl,defaultModelId:J.model},models:{[J.model]:{id:J.model,name:J.model,contextWindow:EG,maxInputTokens:EG,capabilities:["streaming","tools","images"]}}}}function KE($,J){let Q=new Set;for(let W of[$.actModeApiProvider,$.planModeApiProvider]){let j=E(W);if(j)Q.add(j)}if(E(J.apiKey))Q.add("anthropic");if(E(J.openRouterApiKey))Q.add("openrouter");if(E(J.openAiApiKey))Q.add(m9);if(E(J.openAiNativeApiKey))Q.add("openai-native");if(E(J["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(E(J.geminiApiKey))Q.add("gemini");if(E(J.ollamaApiKey))Q.add("ollama");if(E(J.awsAccessKey)||E(J.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||E($.awsProfile))Q.add("bedrock");if(E($.vertexProjectId)||E($.vertexRegion))Q.add("vertex");if(E(J.clineApiKey))Q.add("cline");let Z=Dj(E(J["cline:clineAccountId"]));if(Z?.accessToken||Z?.refreshToken||Z?.accountId)Q.add("cline");if(E(J.ocaApiKey))Q.add("oca");if(E(J.sapAiCoreClientId)||E(J.sapAiCoreClientSecret)||E($.sapAiCoreTokenUrl)||E($.sapAiCoreBaseUrl)||E($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function PJ($){let J=$.providerSettingsManager.read(),Q=fE($);if(!Q)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let{globalState:Z,secrets:W}=Q,j=Z.mode==="plan"?"plan":"act",f=KE(Z,W),X=L$();X.providers={...J.providers},X.lastUsedProvider=J.lastUsedProvider;let Y=new Date().toISOString(),V=0,H=Gj(WE($.providerSettingsManager.getFilePath()),"models.json"),B=$j(H),A=0;for(let R of f){let D=Fj(R);if(X.providers[D])continue;let U=BE(R,Z,W,j);if(!U)continue;X.providers[D]={settings:U,updatedAt:Y,tokenSource:"migration"},V+=1;let F=AE(D,U);if(F&&!B.providers[D])B.providers[D]=F,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let K=E(j==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),G=K?Fj(K):void 0;if(X.lastUsedProvider=J.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)FG(H,B);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}R9();O0();Y9();var IG={};w(IG,{FileTeamPersistenceStore:()=>c9});import{appendFileSync as GE,existsSync as Uj,mkdirSync as FE,readFileSync as DE,renameSync as UE,unlinkSync as RE,writeFileSync as zE}from"node:fs";import{join as Rj}from"node:path";import{resolveTeamDataDir as LE}from"@cline/shared/storage";function _E($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class c9{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let J=_E($.teamName),Q=$.baseDir?.trim()||LE();this.dirPath=Rj(Q,J),this.statePath=Rj(this.dirPath,"state.json"),this.taskHistoryPath=Rj(this.dirPath,"task-history.jsonl")}loadState(){if(!Uj(this.statePath))return;try{let $=DE(this.statePath,"utf8"),J=JSON.parse($);if(J.version!==1||!J.teamState)return;for(let Q of J.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return OA(J.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 J={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;zE(Q,`${JSON.stringify(J,null,2)}
721
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[J,W,Q]),Z.map((j)=>j.run_id)}handleTeamEvent($,J){this.appendTeamEvent($,J.type,J)}}function I3($={}){try{let J=new y2($);return J.init(),J}catch{let J=new TJ({teamDir:$.teamDir});return J.init(),J}}function OQ($,J){return LC($,J)}function OC($,J){let Q=J?.["*"]??{},Z=J?.[$]??{};return{...Q,...Z}.enabled!==!1}function TC($,J){return $.filter((Q)=>OC(Q.name,J))}function x3($,J){return I1(TC($,J))}var MC={apply_diff:"editor",attempt_completion:"submit_and_exit",bash:"run_commands",execute_command:"run_commands",list_code_definition_names:"search_codebase",list_files:"run_commands",read_file:"read_files",replace_in_file:"editor",search_files:"search_codebase",use_skill:"skills",write_to_file:"editor"};function qC($){let J=$.trim().toLowerCase();return MC[J]??J}function PC($,J){if(J.tools===void 0)return $;let Q=new Set(J.tools.map(qC));if(J.skills!==void 0)Q.add("skills");return $.filter((Z)=>Q.has(Z.name))}function MQ(){return`team-${_C(5)}`}function TQ($,J,Q,Z,W,j,f,X){let Y=c0[h1({mode:Q})],V=t2(J,Z,Q,W??o2);return x3(n$({cwd:$,...Y,enableSkills:!!f,...V,executors:{...f?{skills:f}:{},...X??{}}}),j)}function NC($){return TQ($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,wC,$.toolExecutors).some((J)=>J.name==="skills")}var wC=async()=>"";async function SC($){let J=B0();if(!c1({filePath:J}))return{tools:[]};let Q=new A2({clientFactory:S8({settingsPath:J})}),Z;try{Z=await B2(Q,{filePath:J})}catch(X){await Q.dispose().catch(()=>{});let Y=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${Y}`),{tools:[]}}let W=Z.filter((X)=>X.disabled!==!0),j=await Promise.allSettled(W.map((X)=>y8({serverName:X.name,provider:Q}))),f=[];for(let[X,Y]of j.entries())if(Y.status==="fulfilled")f.push(...Y.value);else{let V=Y.reason instanceof Error?Y.reason.message:String(Y.reason);$?.log(`[mcp] Failed to load tools from MCP server "${W[X].name}", skipping: ${V}`)}return{tools:f,shutdown:async()=>{await Q.dispose()}}}function CC($,J){if(!$)return;for(let Q of $.getTeammateIds())try{$.shutdownTeammate(Q,J)}catch{}}function yC($){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 EC($){let J=c0[h1({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??J.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??J.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 W4{teamRuntimeEntries=new Map;async build($){let{config:J,hooks:Q,extensions:Z,logger:W,telemetry:j,createSpawnTool:f,onTeamRestored:X,userInstructionService:Y,configExtensions:V,toolExecutors:H}=$,B=$.onTeamEvent??(()=>{}),A=EC(J),K=J.workspaceRoot??J.cwd,G=$.toolPolicies??J.toolPolicies,R=B1(),D=[],U=J.teamName?.trim()||MQ(),F=J.sessionId?.trim()||U,O=A.enableSpawnAgent?m8({workspaceRoot:K}):{configs:[],errors:[]},T=O.configs.some((m)=>m.skills!==void 0),L=OQ(V,"rules"),z=OQ(V,"skills"),P=z||T,S=OQ(V,"workflows"),b=OQ(V,"plugins"),u=L||z||S,o=!1,J0=Boolean(Y),t=Y,$1;for(let m of O.errors)(W??J.logger)?.log?.(`[agents] Failed to load agent config at ${m.path}: ${m.error.message}`);if(!t&&(u||T))t=_$({skills:P?{workspacePath:K,includePluginSkills:b,pluginSkillDirectories:b?$.pluginSkillDirectories:void 0,pluginPaths:J.pluginPaths,cwd:J.cwd}:{workspacePath:K},rules:{workspacePath:J.cwd},workflows:{workspacePath:J.cwd}});if(t)await t.start().catch(()=>{});let b$=A.enableTools&&z&&Boolean(t)&&t?.hasConfiguredSkills(J.skills)===!0&&NC({cwd:J.cwd,providerId:J.providerId,mode:A.mode,modelId:J.modelId,toolRoutingRules:J.toolRoutingRules,toolPolicies:G,toolExecutors:H}),n=t&&u?t.createExtension({includeRules:L,includeSkills:z,includeWorkflows:S,registerSkillsTool:b$,allowedSkillNames:J.skills}):void 0,O1=n?[...Z??J.extensions??[],n]:Z??J.extensions;if(A.enableTools){if(D.push(...TQ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H)),!A.disableMcpSettingsTools){let m=await SC(J.logger);D.push(...m.tools),$1=m.shutdown}}let C,F0=A.enableAgentTeams?I3():void 0,f0=F0?.loadRuntime(F),w0=f0?.state,k2=f0?.teammates??[],T1=new Map(k2.map((m)=>[m.agentId,m])),Y1=J.sessionId||U,Y4,I2=[],SJ=!1,M1=H$({providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey??"",baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:Q,extensions:O1,logger:W??J.logger,telemetry:$.telemetry??J.telemetry,workspaceMetadata:J.workspaceMetadata});if(A.enableSpawnAgent){if(O.configs.length>0)D.push(...x3(v8({configProvider:M1,agents:O.configs,createSubAgentTools:(m)=>A.enableTools?PC(TQ(J.cwd,m.providerId??J.providerId,A.mode,m.modelId??J.modelId,J.toolRoutingRules,G,m.skills!==void 0&&t?.createSkillsExecutor?t.createSkillsExecutor(m.skills):void 0,H),m):[],hookErrorMode:J.hookErrorMode,toolPolicies:G,requestToolApproval:$.requestToolApproval,onSubAgentEvent:$.onSubAgentEvent,onSubAgentStart:$.onSubAgentStart,onSubAgentEnd:$.onSubAgentEnd}),G))}if(!this.teamRuntimeEntries.has(Y1))this.teamRuntimeEntries.set(Y1,{delegatedAgentConfigProvider:M1});let CJ=()=>{if(!A.enableAgentTeams)return;let m=this.teamRuntimeEntries.get(Y1)??{delegatedAgentConfigProvider:M1};if(this.teamRuntimeEntries.set(Y1,m),C=m.runtime,!C){if(C=new T2({teamName:U,leadAgentId:J.sessionId||"lead",missionLogIntervalSteps:A.missionLogIntervalSteps,missionLogIntervalMs:A.missionLogIntervalMs,onTeamEvent:(Q0)=>{if(B(Q0),C&&F0){if(Q0.type==="teammate_spawned"&&Q0.teammate?.rolePrompt){let q1={agentId:Q0.agentId,rolePrompt:Q0.teammate.rolePrompt,modelId:Q0.teammate.modelId,maxIterations:Q0.teammate.maxIterations};T1.set(q1.agentId,q1)}if(Q0.type==="teammate_shutdown"&&!yC(Q0.reason))T1.delete(Q0.agentId);F0.handleTeamEvent(F,Q0),F0.persistRuntime(F,C.exportState(),Array.from(T1.values()))}}}),w0)C.hydrateState(w0),SJ=!0;m.runtime=C}if(!o){if(!C)return;o=!0;let Q0=Q8({runtime:C,leadAgentId:J.sessionId||"lead",restoredFromPersistence:Boolean(w0),restoredTeammates:k2,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(q1)=>{I2=q1,Y4?.addTools(q1)},createBaseTools:A.enableTools?()=>TQ(J.cwd,J.providerId,A.mode,J.modelId,J.toolRoutingRules,G,void 0,H):void 0,teammateConfigProvider:M1});if(SJ)C.recoverActiveRuns("runtime_recovered");if(Q0.restoredFromPersistence)X?.();D.push(...Q0.tools)}return C};if(A.enableSpawnAgent&&f){let m=f();D.push({...m,execute:async(Q0,q1)=>{return CJ(),m.execute(Q0,q1)}})}if(A.enableAgentTeams)CJ();let x2=x3(D,G),sQ=x2.some((m)=>m.name==="submit_and_exit"&&m.lifecycle?.completesRun===!0),yJ=A.enableAgentTeams?()=>{let m=this.teamRuntimeEntries.get(Y1)?.runtime;if(!m)return;let Q0=m.listTasks(),q1=Q0.some((t1)=>t1.status==="in_progress"||t1.status==="pending"),gj=m.listRuns({}),WF=gj.some((t1)=>t1.status==="running"||t1.status==="queued");if(q1||WF){let t1=Q0.filter((x0)=>x0.status==="in_progress"||x0.status==="pending").map((x0)=>`${x0.id} (${x0.status}): ${x0.title}`).join(", "),mj=gj.filter((x0)=>x0.status==="running"||x0.status==="queued").map((x0)=>`${x0.id} (${x0.status})`).join(", "),oQ=[];if(t1)oQ.push(`Unfinished tasks: ${t1}`);if(mj)oQ.push(`Active runs: ${mj}`);return`[SYSTEM] You still have team obligations. ${oQ.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,ZF=sQ?{requireCompletionTool:!0,...yJ?{completionGuard:yJ}:{}}:yJ?{completionGuard:yJ}:void 0;return{tools:x2,logger:W??J.logger,telemetry:j??J.telemetry,teamRuntime:C,teamRestoredFromPersistence:Boolean(w0),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(Y1)?.delegatedAgentConfigProvider??M1,extensions:O1,completionPolicy:ZF,registerLeadAgent:(m)=>{if(Y4=m,I2.length>0)m.addTools(I1(I2,[...R]))},shutdown:async(m)=>{if(CC(C,m),this.teamRuntimeEntries.delete(Y1),await $1?.(),!J0)t?.stop()}}}}var JG={};w(JG,{requestDesktopToolApproval:()=>m3});import{mkdir as bC,readFile as hC,unlink as kC,writeFile as IC}from"node:fs/promises";import{join as $G}from"node:path";function xC($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function gC($){return new Promise((J)=>setTimeout(J,$))}async function g3($){try{await kC($)}catch{}}async function m3($,J={}){let Q=J.approvalDir?.trim(),Z=J.sessionId?.trim();if(!Q||!Z)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await bC(Q,{recursive:!0});let W=xC(`${$.toolCallId}`),j=$G(Q,`${Z}.request.${W}.json`),f=$G(Q,`${Z}.decision.${W}.json`),X=J.nowIso??(()=>new Date().toISOString());await IC(j,`${JSON.stringify({requestId:W,sessionId:Z,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
722
+ `,"utf8");let Y=J.timeoutMs??300000,V=J.pollIntervalMs??200,H=Date.now();while(Date.now()-H<Y){try{let B=await hC(f,"utf8"),A=JSON.parse(B),K={approved:A.approved===!0,reason:typeof A.reason==="string"?A.reason:void 0};return await Promise.all([g3(f),g3(j)]),K}catch{}await gC(V)}return await g3(j),{approved:!1,reason:"Tool approval request timed out"}}W1();var jG={};w(jG,{syncPluginMcpServersToSettings:()=>d3,removePluginMcpServersFromSettings:()=>MJ,disablePluginMcpServersInSettings:()=>l3});import{existsSync as mC,mkdirSync as vC,readFileSync as cC,writeFileSync as uC}from"node:fs";import{dirname as ZG,isAbsolute as dC,relative as lC,resolve as QG}from"node:path";function E2($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function qQ($,J){let Q=lC(QG($),QG(J));return Q===""||!Q.startsWith("..")&&!dC(Q)}function v3($){if(!mC($))return{mcpServers:{}};try{let J=JSON.parse(cC($,"utf8"));if(E2(J))return J}catch(J){throw Error(`Invalid MCP settings at "${$}": ${J instanceof Error?J.message:String(J)}`)}throw Error(`Invalid MCP settings at "${$}": expected an object`)}function c3($){if(E2($.mcpServers))return{...$.mcpServers};return{}}function u3($,J,Q){vC(ZG($),{recursive:!0}),uC($,`${JSON.stringify({...J,mcpServers:Q},null,2)}
723
+ `,"utf8")}function WG($){return{pluginPaths:[...new Set(($.pluginPaths??[]).map((J)=>J.trim()).filter((J)=>J.length>0))],pluginNames:[...new Set(($.pluginNames??[]).map((J)=>J.trim()).filter((J)=>J.length>0))]}}function NQ($){if(!E2($))return;let J=$.metadata;return E2(J)?J:void 0}function PQ($,J){let Q=NQ($);if(!Q||Q.source!=="plugin")return!1;let Z=typeof Q.pluginName==="string"?Q.pluginName:typeof Q.plugin==="string"?Q.plugin:void 0,W=typeof Q.pluginPath==="string"?Q.pluginPath:void 0;if(J.pluginName&&Z===J.pluginName){if(!J.pluginPath||W===J.pluginPath)return!0}if(W&&J.pluginPath&&(W===J.pluginPath||qQ(J.pluginPath,W)||qQ(W,J.pluginPath)))return!0;if(Z&&J.pluginNames?.some((j)=>j===Z))return!0;if(W&&J.pluginPaths?.some((j)=>W===j||qQ(j,W)||qQ(W,j)))return!0;return!1}function pC($){let J=E2($.existing?.oauth)?{oauth:$.existing.oauth}:{};return{transport:$.registration.transport.type==="stdio"&&$.registration.transport.cwd===void 0?{...$.registration.transport,cwd:ZG($.pluginPath)}:$.registration.transport,...$.disabled?{disabled:!0}:{},...J,metadata:{...$.registration.metadata??{},source:"plugin",pluginName:$.pluginName,pluginPath:$.pluginPath}}}async function rC($){if($.pluginPaths.length===0)return{plugins:[],servers:[],failures:[]};let J=await B8({pluginPaths:[...$.pluginPaths],cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0});try{let Q=[],Z=[],W=(J.failures??[]).map((j)=>({pluginPath:j.pluginPath,pluginName:j.pluginName,message:j.message}));for(let j of J.extensions??[]){let f=j.__clinePluginPath;if(!f)continue;if(!j.setup){Q.push({pluginName:j.name,pluginPath:f});continue}let X=[],Y={registerTool:(V)=>{},registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{},registerMcpServer:(V)=>{if(!j.manifest.capabilities.includes("mcp"))throw Error('registerMcpServer requires the "mcp" capability');X.push(V)}};try{await j.setup(Y,{workspaceInfo:$.workspacePath?{rootPath:$.workspacePath}:void 0})}catch(V){W.push({pluginPath:f,pluginName:j.name,message:V instanceof Error?V.message:String(V)});continue}Q.push({pluginName:j.name,pluginPath:f});for(let V of X)Z.push({pluginName:j.name,pluginPath:f,server:{...V,metadata:{...V.metadata??{},source:"plugin",pluginName:j.name,pluginPath:f}}})}return{plugins:Q,servers:Z,failures:W}}finally{await J.shutdown().catch(()=>{})}}async function d3($){let J=$.settingsPath??B0(),Q={mutations:[],failures:[]},Z;try{Z=await rC($)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}Q.failures.push(...Z.failures);let W;try{W=v3(J)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)});return Q}let j=c3(W),f=new Map,X=new Map;for(let V of Z.plugins)f.set(V.pluginPath,new Set),X.set(V.pluginPath,V.pluginName);let Y=C9(Z.servers.map((V)=>({server:V.server,owner:V,ownerLabel:V.pluginName})));for(let V of Y){let H=V.owner;if(!f.has(H.pluginPath))f.set(H.pluginPath,new Set);if(V.name)f.get(H.pluginPath)?.add(V.name);if(!V.registration){Q.mutations.push({name:V.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:V.loadError??"invalid MCP server registration"});continue}let B=j[V.registration.name];if(B!==void 0){if(!PQ(B,{pluginName:H.pluginName,pluginPath:H.pluginPath})){Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:"skipped",reason:"MCP server name is already configured"});continue}}j[V.registration.name]=pC({registration:V.registration,pluginName:H.pluginName,pluginPath:H.pluginPath,existing:E2(B)?B:void 0}),Q.mutations.push({name:V.registration.name,pluginName:H.pluginName,pluginPath:H.pluginPath,action:B===void 0?"created":"updated"})}for(let[V,H]of Object.entries(j)){let B=NQ(H),A=typeof B?.pluginPath==="string"?B.pluginPath:"",K=f.get(A);if(K&&PQ(H,{pluginPath:A})&&!K.has(V))delete j[V],Q.mutations.push({name:V,pluginName:typeof B?.pluginName==="string"?B.pluginName:X.get(A)??"plugin",pluginPath:A,action:"removed",reason:"plugin no longer declares this MCP server"})}if(Q.mutations.some((V)=>V.action!=="skipped"))try{u3(J,W,j)}catch(V){for(let H of $.pluginPaths)Q.failures.push({pluginPath:H,message:V instanceof Error?V.message:String(V)})}return Q}function l3($){let J=$.settingsPath??B0(),Q;try{Q=v3(J)}catch{return[]}let Z=c3(Q),W=WG($),j=[];for(let[f,X]of Object.entries(Z)){if(!E2(X)||!PQ(X,W))continue;let Y=NQ(X);Z[f]={...X,disabled:!0},j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"disabled"})}if(j.length>0)u3(J,Q,Z);return j}function MJ($){let J=$.settingsPath??B0(),Q;try{Q=v3(J)}catch{return[]}let Z=c3(Q),W=WG($),j=[];for(let[f,X]of Object.entries(Z)){if(!PQ(X,W))continue;let Y=NQ(X);delete Z[f],j.push({name:f,pluginName:typeof Y?.pluginName==="string"?Y.pluginName:"plugin",pluginPath:typeof Y?.pluginPath==="string"?Y.pluginPath:"",action:"removed"})}if(j.length>0)u3(J,Q,Z);return j}W1();var VG={};w(VG,{uninstallPlugin:()=>t3});import{existsSync as f4,readdirSync as iC,readFileSync as nC,rmdirSync as aC,rmSync as sC,statSync as oC}from"node:fs";import{basename as t0,dirname as E$,extname as tC,isAbsolute as eC,join as o1,relative as $y,resolve as j4,sep as p3}from"node:path";import{discoverPluginModulePaths as Jy,resolvePluginConfigSearchPaths as Qy}from"@cline/shared/storage";var s3="_installed",Zy="package",Wy=new Map([["git",2],["local",1],["npm",1],["official",1],["remote",1]]);function r3($){return $.trim().toLowerCase()}function X1($,J){let Q=J?.trim();if(!Q)return;$.add(Q)}function jy($){return $.replace(/-[0-9a-f]{12}$/i,"")}function i3($){let J=tC($);return J?$.slice(0,-J.length):$}function n3($){if(!f4($))return;try{let J=JSON.parse(nC($,"utf8"));return typeof J.name==="string"?J.name.trim():void 0}catch{return}}function o3($,J){let Q=$y(J,$);return Q===""||!Q.startsWith("..")&&!eC(Q)}function fG($){let Q=j4($).split(p3),Z=Q.lastIndexOf(s3);if(Z<0)return;let W=Q[Z+1];if(!W)return;let j=Wy.get(W)??1,f=Z+2+j;if(Q.length<f)return;let X=Q.slice(0,f).join(p3)||p3;return f4(X)?X:void 0}function wQ($){try{return iC($,{withFileTypes:!0})}catch{return[]}}function fy($){let J=o1($,s3);if(!f4(J))return[];let Q=[];for(let Z of wQ(J)){if(!Z.isDirectory())continue;let W=o1(J,Z.name);if(Z.name==="git"){for(let j of wQ(W)){if(!j.isDirectory())continue;let f=o1(W,j.name);for(let X of wQ(f))if(X.isDirectory())Q.push(o1(f,X.name))}continue}for(let j of wQ(W))if(j.isDirectory())Q.push(o1(W,j.name))}return Q.sort((Z,W)=>Z.localeCompare(W))}function XG($){try{return Jy($)}catch{return[]}}function a3($){let J=XG($),Q=new Set;X1(Q,t0($)),X1(Q,jy(t0($))),X1(Q,n3(o1($,"package.json"))),X1(Q,n3(o1($,Zy,"package.json")));for(let Z of J)X1(Q,t0(Z)),X1(Q,i3(t0(Z)));return{installPath:$,entryPaths:J,names:[...Q].sort((Z,W)=>Z.localeCompare(W)),installed:!0}}function Xy($,J){let Q=j4($),Z=J.find((f)=>o3(Q,f));if(!Z)return;let W=E$(Q);while(W!==Z&&W!==E$(W)){if(f4(o1(W,"package.json")))return W;W=E$(W)}let j=t0(Q);if((j==="index.ts"||j==="index.js")&&E$(Q)!==Z)return E$(Q);return Q}function YG($,J){let Q=Xy($,J);if(!Q)return;let Z=new Set;return X1(Z,t0($)),X1(Z,i3(t0($))),X1(Z,t0(Q)),X1(Z,i3(t0(Q))),X1(Z,n3(o1(Q,"package.json"))),{installPath:Q,entryPaths:[$],names:[...Z].sort((W,j)=>W.localeCompare(j)),installed:!1}}function Yy($){let J=$.workspaceRoot?.trim()||$.cwd?.trim()||process.cwd();return Qy(J).filter((Q)=>f4(Q))}function Vy($){let J=new Map;for(let Q of $){for(let Z of fy(Q))J.set(Z,a3(Z));for(let Z of XG(Q)){let W=fG(Z);if(W){if(!J.has(W))J.set(W,a3(W));continue}let j=YG(Z,$);if(j)J.set(j.installPath,j)}}return[...J.values()].sort((Q,Z)=>Q.installPath.localeCompare(Z.installPath))}function Hy($,J){let Q=r3(J);if(!Q)return!1;if(r3($.installPath)===Q)return!0;return $.names.some((Z)=>r3(Z)===Q)}function By($,J,Q){let Z=j4($);for(let j of J){if(o3(Z,j.installPath))return j;if(j.entryPaths.some((f)=>j4(f)===Z))return j}let W=fG(Z);if(W)return a3(W);if(f4(Z))return YG(Z,Q);return}function Ay($){let J=M0(),Q=J.disabledPlugins;if(!Q?.length)return;let Z=Q.filter((W)=>{let j=j4(W);if(o3(j,$.installPath))return!1;return!$.entryPaths.some((f)=>j4(f)===j)});if(Z.length===Q.length)return;k1({...J,disabledPlugins:Z})}function Ky($){let J=E$($);while(J!==E$(J)&&t0(J)!==s3){try{aC(J)}catch{return}J=E$(J)}}function Gy($){return`${$.names[0]??t0($.installPath)} at ${$.installPath}`}async function t3($){let J=Yy($),Q=Vy(J),Z=$.path?.trim(),W=$.name?.trim(),j;if(Z){if(j=By(Z,Q,J),!j)throw Error(`No plugin found at ${Z}`)}else{if(!W)throw Error("plugin uninstall requires a plugin name");let X=Q.filter((Y)=>Hy(Y,W));if(X.length===0)throw Error(`No plugin found matching "${W}"`);if(X.length>1)throw Error(`Multiple plugins match "${W}": ${X.map(Gy).join(", ")}`);j=X[0]}let f=oC(j.installPath,{throwIfNoEntry:!1});if(!f)throw Error(`Plugin install path does not exist: ${j.installPath}`);if(MJ({pluginPaths:[j.installPath,...j.entryPaths],pluginNames:j.names}),sC(j.installPath,{recursive:f.isDirectory(),force:!0}),Ay(j),j.installed)Ky(j.installPath);return{name:W||j.names[0]||t0(j.installPath),installPath:j.installPath,removedPaths:[j.installPath],entryPaths:j.entryPaths}}var SG={};w(SG,{updateLocalProvider:()=>IQ,saveLocalProviderSettings:()=>fj,saveLocalProviderOAuthCredentials:()=>Hj,resolveLocalClineAuthToken:()=>Aj,refreshProviderModelsFromSource:()=>Xj,normalizeOAuthProvider:()=>Yj,loginLocalProvider:()=>Vj,loginAndSaveLocalProviderOAuthCredentials:()=>Bj,listLocalProviders:()=>Wj,getLocalProviderModels:()=>jj,ensureCustomProvidersLoaded:()=>bQ,deleteLocalProvider:()=>xQ,addLocalProvider:()=>Zj});import*as N0 from"@cline/llms";import{existsSync as Fy,mkdirSync as Dy,readFileSync as Uy,writeFileSync as Ry}from"node:fs";import{mkdir as zy,readFile as Ly,writeFile as _y}from"node:fs/promises";import{dirname as e3,join as Oy}from"node:path";import*as I0 from"@cline/llms";import{ModelCapabilitySchema as Ty,ProviderCapabilitySchema as My,ProviderClientSchema as qy,ProviderProtocolSchema as Py}from"@cline/shared";import{z as i}from"zod";var Ny=i.object({id:i.string().optional(),name:i.string().optional(),maxTokens:i.number().optional(),contextWindow:i.number().optional(),maxInputTokens:i.number().optional(),capabilities:i.array(Ty).optional(),supportsVision:i.boolean().optional(),supportsAttachments:i.boolean().optional(),supportsReasoning:i.boolean().optional()}).passthrough(),wy=i.object({name:i.string(),baseUrl:i.string(),defaultModelId:i.string().optional(),protocol:Py.optional(),client:qy.optional(),capabilities:i.array(My).optional(),modelsSourceUrl:i.string().optional()}).passthrough(),HG=i.object({provider:wy.optional(),models:i.record(i.string(),Ny).optional()}).passthrough(),BG=i.object({version:i.literal(1),providers:i.record(i.string(),HG)}),Sy=i.object({version:i.literal(1),providers:i.record(i.string(),i.unknown())}),SQ=new Set;function AG($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function b2($){return Oy(e3($.getFilePath()),"models.json")}function CQ(){return{version:1,providers:{}}}function KG($){let J=Sy.safeParse($);if(!J.success)return CQ();let Q={};for(let[Z,W]of Object.entries(J.data.providers)){let j=HG.safeParse(W);if(j.success)Q[Z]=j.data}return{version:1,providers:Q}}function $j($){if(!Fy($))return CQ();try{let J=Uy($,"utf8");return KG(JSON.parse(J))}catch{}return CQ()}async function X4($){try{let J=await Ly($,"utf8");return KG(JSON.parse(J))}catch{}return CQ()}function GG($,J){Dy(e3($),{recursive:!0});let Q=BG.parse(J);Ry($,`${JSON.stringify(Q,null,2)}
724
+ `,"utf8")}async function yQ($,J){await zy(e3($),{recursive:!0});let Q=BG.parse(J);await _y($,`${JSON.stringify(Q,null,2)}
725
+ `,"utf8")}function FG($,J){return{id:$,name:J.name??$,supportsAttachments:J.capabilities?.includes("files"),supportsVision:J.capabilities?.includes("images"),supportsReasoning:J.capabilities?.includes("reasoning")||J.thinkingConfig!=null}}function DG($){if(!$||$.length===0)return;let J=new Set;if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("tools"))J.add("tools");return J.size>0?[...J]:void 0}function UG($){let J=new Set;if(!$||$.length===0)return[...J];if($.includes("streaming"))J.add("streaming");if($.includes("tools"))J.add("tools");if($.includes("reasoning"))J.add("reasoning");if($.includes("prompt-cache"))J.add("prompt-cache");if($.includes("vision"))J.add("images"),J.add("files");return[...J]}function Cy($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function RG($,J){return $??J??"openai-chat"}function zG($,J,Q){return $??Q??(J==="openai-responses"?"openai":"openai-compatible")}function LG($,J,Q){let Z=new Set(J?.capabilities??Q??[]);if(J?.supportsVision)Z.add("images");if(J?.supportsAttachments)Z.add("files");if(J?.supportsReasoning)Z.add("reasoning");return{id:$,name:J?.name??$,maxTokens:J?.maxTokens,contextWindow:J?.contextWindow,maxInputTokens:J?.maxInputTokens,capabilities:Z.size>0?[...Z]:void 0}}function yy($,J){for(let[Q,Z]of Object.entries(J??{})){let W=Z.id?.trim()||Q.trim();if(!W)continue;I0.registerModel($,W,LG(W,Z))}}function Ey($,J,Q){return{...J??{},id:$,name:J?.name??$,capabilities:J?.capabilities??Q}}function by($){return Object.assign({},...I0.resolveProviderModelCatalogKeys($).map((Q)=>I0.getGeneratedModelsForProvider(Q)))}function hy($){let J=$.provider.trim();if(!J||I0.isBuiltInProviderId(J))return;let Q=$.baseUrl?.trim();if(!Q)return;let Z=I0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J],W=by(J),j=UG($.capabilities),f=j.length>0?j:void 0,X=$.model?.trim(),Y={...W,...Z?.models??{}};if(X)Y[X]=Ey(X,Y[X],f);let V=Object.keys(Y).filter(Boolean),H=X||V[0];if(!H)return;let B=RG($.protocol,Z?.provider.protocol),A=zG($.client,B,Z?.provider.client);I0.registerProvider({provider:{id:J,name:Z?.provider.name??AG(J),description:Z?.provider.description,protocol:B,client:A,baseUrl:Q,modelsSourceUrl:Z?.provider.modelsSourceUrl,defaultModelId:H,capabilities:DG($.capabilities)??Z?.provider.capabilities,source:"file"},models:Y})}function EQ($){for(let J of Object.values($.providers))hy(J.settings)}function qJ($,J){let Q=J.models??{};if(!Cy(J.provider)){yy($,Q);return}let Z=UG(J.provider.capabilities),W=Object.entries(Q).map(([V,H])=>({id:H.id?.trim()||V.trim(),model:H})).filter(({id:V})=>V.length>0),j=J.provider.defaultModelId?.trim()||W[0]?.id||"default",f=RG(J.provider.protocol,void 0),X=zG(J.provider.client,f,void 0),Y=Object.fromEntries(W.map(({id:V,model:H})=>[V,{...LG(V,H,Z.length>0?Z:void 0),status:"active"}]));I0.registerProvider({provider:{id:$,name:J.provider.name.trim()||AG($),protocol:f,client:X,baseUrl:J.provider.baseUrl,modelsSourceUrl:J.provider.modelsSourceUrl,defaultModelId:j,capabilities:DG(J.provider.capabilities),source:"file"},models:Y})}function _G($){let J=b2($);if(SQ.has(J))return;let Q=$j(J);for(let[Z,W]of Object.entries(Q.providers))qJ(Z,W);SQ.add(J)}async function bQ($){let J=b2($);if(SQ.has(J))return;let Q=await X4(J);for(let[Z,W]of Object.entries(Q.providers))qJ(Z,W);SQ.add(J)}var ky="cline-pass";function Iy($){return $.apiKey??$.auth?.apiKey}function xy($){return($.auth?.accessToken?.trim()??"").length>0}function TG($){return $.split(/[-_]/).filter(Boolean).map((J)=>J.charAt(0).toUpperCase()+J.slice(1)).join(" ")}function gy($){let J=$.split(/\s+/).filter(Boolean);if(J.length===0)return"?";if(J.length===1)return J[0].slice(0,2).toUpperCase();return`${J[0][0]}${J[1][0]}`.toUpperCase()}function my($){let J=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],Q=0;for(let Z of $)Q=Q*31+Z.charCodeAt(0)>>>0;return J[Q%J.length]}function MG($){return Object.entries($).sort(([J],[Q])=>J.localeCompare(Q)).map(([J,Q])=>FG(J,Q))}async function vy($,J){let Q=await N0.getModelsForProvider($);if(!J)return Q;let Z=await F6($,{loadPrivateOnAuth:!0,failOnError:!1},J);return Z?.knownModels?{...Q,...Z.knownModels}:Q}function Jj($){return[...new Set(($??[]).map((J)=>J.trim()).filter(Boolean))]}function cy($){if(!$?.length)return;return[...new Set($)]}function uy($,J){return cy([...$??[],...J??[]])}function dy($){let J=$?.popularRank;return typeof J==="number"&&Number.isFinite(J)?J:Number.MAX_SAFE_INTEGER}function ly($){if(!$||typeof $!=="object")return!1;let J=$;return typeof J.path==="string"&&J.path.trim().length>0&&typeof J.label==="string"&&J.label.trim().length>0&&["text","password","url","number","select","boolean"].includes(String(J.type))}function py($){let J=$?.configFields;if(!Array.isArray(J))return;return J.filter(ly)}var hQ={path:"apiKey",label:"API Key",type:"password",placeholder:"Enter API key...",description:"API key issued by the provider.",secret:!0},OG={path:"baseUrl",label:"Base URL",type:"url",placeholder:"https://...",description:"Base endpoint used for provider requests."};function ry($){if(!$)return[hQ];if($.source!=="system")return $.baseUrl?[hQ,OG]:[hQ];let J=[];if($.env?.length)J.push(hQ);if($.baseUrl)J.push(OG);return J}function iy($,J){return J.split(".").reduce((Q,Z)=>{if(!Q||typeof Q!=="object")return;return Q[Z]},$)}function ny($){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean"||$===null)return $;return}function ay($,J,Q){if(!$?.length)return;let Z={};for(let W of $){let f=ny(W.path==="baseUrl"&&J?.baseUrl===void 0?Q?.baseUrl:iy(J,W.path))??W.defaultValue;if(f!==void 0)Z[W.path]=f}return Z}function qG($){let J=Object.entries($??{}).filter(([Q])=>Q.trim().length>0);return J.length>0?Object.fromEntries(J):void 0}function Qj($,J){let Q=J?.includes("vision")??!1,Z=J?.includes("reasoning")??!1;return Object.fromEntries($.map((W)=>[W,{id:W,name:W,supportsVision:Q,supportsAttachments:Q,supportsReasoning:Z}]))}async function PG($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let J=$.modelsSourceUrl?await u5($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...J])]}function NG($,J){let Q=$.read(),Z=!1;if(Q.providers[J])delete Q.providers[J],Z=!0;if(Q.lastUsedProvider===J)delete Q.lastUsedProvider,Z=!0;if(Z)$.write(Q);N0.unregisterProvider(J)}async function Zj($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=J.baseUrl.trim(),W=J.apiKey?.trim()??"";if(!Z&&!W){let G=b2($);if((await X4(G)).providers[Q]){let D=await xQ($,{providerId:Q});return{providerId:Q,settingsPath:D.settingsPath,modelsPath:D.modelsPath,modelsCount:0}}return NG($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(N0.hasProvider(Q))throw Error(`provider "${Q}" already exists`);let j=J.name.trim();if(!j)throw Error("name is required");if(!Z)throw Error("baseUrl is required");let f=Jj(J.models),X=J.modelsSourceUrl?.trim(),Y=await PG({providerId:Q,explicitModels:f,modelsSourceUrl:X,shouldRecompute:!0});if(Y.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let V=J.defaultModelId?.trim()&&Y.includes(J.defaultModelId.trim())?J.defaultModelId.trim():Y[0],H=J.capabilities?.length?[...new Set(J.capabilities)]:void 0,B=qG(J.headers);$.saveProviderSettings({provider:Q,apiKey:W||void 0,baseUrl:Z,headers:B,timeout:J.timeoutMs,model:V,protocol:J.protocol,client:J.client},{setLastUsed:!1});let A=b2($),K=await X4(A);return K.providers[Q]={provider:{name:j,baseUrl:Z,defaultModelId:V,protocol:J.protocol,client:J.client,capabilities:H,modelsSourceUrl:X},models:Qj(Y,H)},await yQ(A,K),qJ(Q,K.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:A,modelsCount:Y.length}}async function IQ($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=b2($),W=await X4(Z),j=W.providers[Q];if(!j){let T=$.getProviderSettings(Q);if(!T)throw Error(`provider "${Q}" does not exist`);let L=J.modelsSourceUrl?.trim(),z=Jj(J.models)[0]??T.model?.trim();if(!z&&!L)throw Error(`provider "${Q}" cannot be updated because no model is configured`);j={provider:{name:J.name?.trim()||TG(Q),baseUrl:J.baseUrl?.trim()??T.baseUrl?.trim()??"",defaultModelId:z,protocol:T.protocol,client:T.client,capabilities:T.capabilities},models:z?Qj([z],T.capabilities):{}}}if(!j.provider)throw Error(`provider "${Q}" cannot be updated because it is a model overlay (no provider metadata)`);let f=J.name?.trim()??j.provider.name.trim();if(!f)throw Error("name is required");let X=J.baseUrl?.trim()??j.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let Y=J.capabilities===void 0?j.provider.capabilities:J.capabilities===null?void 0:[...new Set(J.capabilities)],V=J.protocol===void 0?j.provider.protocol:J.protocol??void 0,H=J.client===void 0?j.provider.client:J.client??void 0,B=Jj(J.models),A=J.modelsSourceUrl===void 0?j.provider.modelsSourceUrl:J.modelsSourceUrl?.trim()||void 0,K=J.models!==void 0||J.modelsSourceUrl!==void 0&&!!A,G=Object.keys(j.models??{}).map((T)=>T.trim()).filter(Boolean),R=await PG({providerId:Q,explicitModels:B,modelsSourceUrl:A,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let D=J.defaultModelId===void 0?j.provider.defaultModelId?.trim():J.defaultModelId?.trim(),U=D&&R.includes(D)?D:R[0],O={...$.getProviderSettings(Q)??{},provider:Q,baseUrl:X,model:U};if(V)O.protocol=V;else delete O.protocol;if(H)O.client=H;else delete O.client;if(J.apiKey!==void 0){let T=J.apiKey?.trim()??"";if(T)O.apiKey=T;else delete O.apiKey}if(J.headers!==void 0){let T=qG(J.headers);if(T)O.headers=T;else delete O.headers}if(J.timeoutMs!==void 0)if(typeof J.timeoutMs==="number")O.timeout=J.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),W.providers[Q]={provider:{name:f,baseUrl:X,defaultModelId:U,protocol:V,client:H,capabilities:Y,modelsSourceUrl:A},models:Qj(R,Y)},await yQ(Z,W),qJ(Q,W.providers[Q]),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z,modelsCount:R.length}}async function xQ($,J){let Q=J.providerId.trim().toLowerCase();if(!Q)throw Error("providerId is required");let Z=b2($),W=await X4(Z);if(!W.providers[Q])throw Error(`provider "${Q}" does not exist`);return delete W.providers[Q],await yQ(Z,W),N0.unregisterProvider(Q),NG($,Q),{providerId:Q,settingsPath:$.getFilePath(),modelsPath:Z}}async function Wj($,J={}){let Q=$.read(),Z=N0.getProviderIds(),W=await Promise.all(Z.map(async(f)=>{let[X,Y]=await Promise.all([N0.getProvider(f),N0.getModelsForProvider(f)]),V=MG(Y),H=Q.providers[f]?.settings,B=X?.name??TG(f),A=uy(X?.capabilities,H?.capabilities),K=py(X?.metadata)??ry(X);return{provider:{id:f,name:B,models:V.length,color:my(f),letter:gy(B),enabled:Boolean(H),apiKey:H?Iy(H):void 0,oauthAccessTokenPresent:H?xy(H):void 0,baseUrl:H?.baseUrl??X?.baseUrl,defaultModelId:X?.defaultModelId,protocol:H?.protocol??X?.protocol,client:H?.client??X?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",configFields:K,configValues:ay(K,H,X),modelList:V},rank:dy(X?.metadata)}}));W.sort((f,X)=>{if(f.rank!==X.rank)return f.rank-X.rank;return f.provider.name.localeCompare(X.provider.name)||f.provider.id.localeCompare(X.provider.id)});let j=W.map((f)=>f.provider);if(J.isClinePassEnabled!==!0)j=j.filter((f)=>f.id!==ky);return{providers:j,settingsPath:$.getFilePath()}}async function jj($,J){let Q=$.trim(),Z=await vy(Q,J),W=MG(Z);return{providerId:Q,models:W}}function kQ($){return $!=null&&typeof $==="object"&&!Array.isArray($)}function wG($,J){if(!kQ(J))return kQ($)?{...$}:void 0;let Q=kQ($)?{...$}:{};for(let[Z,W]of Object.entries(J)){if(W==null||W===""){delete Q[Z];continue}if(kQ(W)){let j=wG(Q[Z],W);if(j&&Object.keys(j).length>0)Q[Z]=j;else delete Q[Z];continue}Q[Z]=W}return Object.keys(Q).length>0?Q:void 0}function fj($,J){let Q=J.providerId.trim();if(J.enabled===!1){let j=$.read();if(delete j.providers[Q],j.lastUsedProvider===Q)delete j.lastUsedProvider;return $.write(j),{providerId:Q,enabled:!1,settingsPath:$.getFilePath()}}let W={...$.getProviderSettings(Q)??{},provider:Q};for(let j of["apiKey","baseUrl","model","region"])if(Object.hasOwn(J,j)&&typeof J[j]==="string")if(J[j].trim().length===0)delete W[j];else W[j]=J[j];for(let j of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(J,j))W[j]=J[j];for(let j of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(J,j)&&J[j]!=null){let f=wG(W[j],J[j]);if(f)W[j]=f;else delete W[j]}return $.saveProviderSettings(W,{setLastUsed:!1}),{providerId:Q,enabled:!0,settingsPath:$.getFilePath()}}async function Xj($,J){let Q=J.trim(),Z=$.getProviderSettings(Q),j=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[Q]?.provider,f=Z?.baseUrl?.trim()||j?.baseUrl?.trim(),X=d5(f,j?.baseUrl,j?.modelsSourceUrl);if(!Z||!j||!f||!X)return{providerId:Q,refreshed:!1};let Y=await IQ($,{providerId:Q,name:j.name,baseUrl:f,apiKey:Z.apiKey,headers:Z.headers??null,timeoutMs:Z.timeout??null,modelsSourceUrl:X,protocol:Z.protocol??j.protocol??null,client:Z.client??j.client??null,capabilities:Z.capabilities??null});return{providerId:Q,refreshed:!0,modelsCount:Y.modelsCount}}function Yj($){let J=$.trim().toLowerCase(),Q=Z0(J);if(Q)return Q.providerId;throw Error(`provider "${$}" does not support OAuth login`)}async function Vj($,J,Q,Z){let W=Z0($);if(!W)throw Error(`provider "${$}" does not support OAuth login`);let j=T8({onPrompt:async(f)=>f.defaultValue??"",openUrl:Q,onOpenUrlError:({error:f})=>{throw f instanceof Error?f:Error(String(f))}});return W.login({settings:J,callbacks:j,telemetry:Z})}function Hj($,J,Q,Z,W){return x$({manager:$,providerId:J,settings:Q,credentials:Z,setLastUsed:W?.setLastUsed})}async function Bj($,J,Q,Z){let W=T8({onPrompt:async(j)=>j.defaultValue??"",openUrl:Q,onOpenUrlError:({error:j})=>{throw j instanceof Error?j:Error(String(j))}});return z4($,J,{callbacks:W,telemetry:Z})}function Aj($){let J=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return J&&J.length>0?J:void 0}var CG={};w(CG,{getProviderConfigFields:()=>Kj});import*as gQ from"@cline/llms";var sy=["apiKey","baseUrl","azureApiVersion","awsRegion","awsProfile","gcpProjectId","gcpRegion","sapClientId","sapClientSecret","sapTokenUrl","sapResourceGroup","sapDeploymentId"],oy={"openai-compatible":{description:"For Azure AI Foundry deployments, use a Base URL ending at /openai/deployments/<deployment> and set the Azure API version.",fields:{azureApiVersion:{label:"Azure API Version (optional)",placeholder:"2025-01-01-preview",note:"Required for Azure AI Foundry deployment URLs.",optional:!0}}},vertex:{mode:"replace",description:"Vertex AI can use Google Cloud Application Default Credentials with a project/region. An API key is optional for supported Gemini models.",fields:{gcpProjectId:{label:"Google Cloud Project ID",placeholder:"my-gcp-project"},gcpRegion:{label:"Google Cloud Region",placeholder:"us-central1",defaultValue:"us-central1"},apiKey:{label:"API Key (optional)",placeholder:"Leave blank to use Google Cloud credentials",optional:!0}}},bedrock:{mode:"replace",description:"AWS region is required for Bedrock. It can be auto-filled from AWS_REGION, AWS_DEFAULT_REGION, or ~/.aws/config.",fields:{awsRegion:{label:"AWS Region",placeholder:"us-east-1"},apiKey:{label:"AWS Bedrock API Key (optional)",placeholder:"Leave blank to use AWS profile/default chain",optional:!0},awsProfile:{label:"AWS Profile Name (optional)",placeholder:"default",optional:!0}}},ollama:{fields:{apiKey:{note:"Keep empty if no API key for local inference."}}},sapaicore:{mode:"replace",description:"SAP AI Core uses OAuth client credentials and an AI Core API URL, not a generic API key.",fields:{baseUrl:{label:"AI Core Base URL",placeholder:"https://api.ai.<region>.aws.ml.hana.ondemand.com"},sapClientId:{label:"Client ID",placeholder:"sb-...|xsuaa_std!b..."},sapClientSecret:{label:"Client Secret",placeholder:"SAP AI Core client secret"},sapTokenUrl:{label:"Token URL",placeholder:"https://<subdomain>.authentication.sap.hana.ondemand.com"},sapResourceGroup:{label:"Resource Group",placeholder:"default",optional:!0},sapDeploymentId:{label:"Deployment ID",placeholder:"SAP AI Core deployment id",optional:!0}}}};function ty($,J){let Q={};for(let Z of sy){let W=$[Z],j=J[Z];if(W||j)Q[Z]={...W,...j}}return Q}function ey($){let J=oy[$.providerId];if(!J)return $;return{...$,description:J.description??$.description,fields:J.mode==="replace"?J.fields:ty($.fields,J.fields)}}var $E=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function JE($,J){if(!J?.provider.baseUrl)return!1;if(J.provider.source!=="system")return!0;return $E.has($)}function Kj($){let J=gQ.normalizeProviderId($);if(I$(J))return{providerId:J,authMethod:"oauth",fields:{}};let Q=gQ.MODEL_COLLECTIONS_BY_PROVIDER_ID[J];if(Q?.provider.capabilities?.includes("local-auth"))return{providerId:J,authMethod:"local",fields:{}};let Z=Q?.provider.baseUrl,W={apiKey:{}};if(JE(J,Q))W.baseUrl={defaultValue:Z};return ey({providerId:J,authMethod:"api-key",fields:W})}var hG={};w(hG,{resolveLegacyClineAuth:()=>Dj,migrateLegacyProviderSettings:()=>PJ});import{existsSync as QE,readFileSync as ZE}from"node:fs";import{dirname as WE,join as Gj}from"node:path";import*as vQ from"@cline/llms";import{resolveClineDataDir as jE}from"@cline/shared/storage";var mQ="openai",bG=vQ.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,yG=128000;function Dj($){let J=$?.trim();if(!J)return;try{let Q=JSON.parse(J);if(!Q)return;let Z=typeof Q.expiresAt==="number"&&Number.isFinite(Q.expiresAt)?Q.expiresAt<10000000000?Q.expiresAt*1000:Q.expiresAt:void 0;return{accessToken:Q.idToken,refreshToken:Q.refreshToken,expiresAt:Z,accountId:Q.userInfo?.id}}catch{return}}function E($){let J=$?.trim();return J?J:void 0}function EG($){if(!QE($))return;try{let J=ZE($,"utf8"),Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return}function fE($){let J=$.dataDir??jE(),Q=$.globalStatePath??Gj(J,"globalState.json"),Z=$.secretsPath??Gj(J,"secrets.json"),W=EG(Q),j=EG(Z);if(!W&&!j)return;return{globalState:W??{},secrets:j??{}}}function Fj($){if($===mQ)return bG;return $}function XE($,J,Q,Z){let W=Q==="plan"?"planMode":"actMode",j=J===Z?E(Q==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${W}OpenRouterModelId`,cline:`${W}ClineModelId`,openai:`${W}OpenAiModelId`,ollama:`${W}OllamaModelId`,lmstudio:`${W}LmStudioModelId`,litellm:`${W}LiteLlmModelId`,requesty:`${W}RequestyModelId`,together:`${W}TogetherModelId`,fireworks:`${W}FireworksModelId`,sapaicore:`${W}SapAiCoreModelId`,groq:`${W}GroqModelId`,baseten:`${W}BasetenModelId`,huggingface:`${W}HuggingFaceModelId`,"huawei-cloud-maas":`${W}HuaweiCloudMaasModelId`,oca:`${W}OcaModelId`,aihubmix:`${W}AihubmixModelId`,hicap:`${W}HicapModelId`,nousResearch:`${W}NousResearchModelId`,"vercel-ai-gateway":`${W}VercelAiGatewayModelId`}[J];return(X?E(typeof $[X]==="string"?$[X]:void 0):void 0)??j}function YE($,J,Q){let Z=Q==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,W=Q==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,j=Q==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,f=(J==="gemini"?W:void 0)??Z,X=f==="none"||f==="low"||f==="medium"||f==="high"?f:void 0,Y=typeof j==="number"&&Number.isInteger(j)&&j>0?j:void 0;if(!X&&Y===void 0)return;return{...X?{effort:X}:{},...Y!==void 0?{budgetTokens:Y}:{}}}function VE($){let J=$["openai-codex-oauth-credentials"];if(!J)return;try{let Q=JSON.parse(J),Z=E(Q.access_token),W=E(Q.refresh_token),j=E(Q.accountId);if(!Z&&!W&&!j)return;return{...Z?{apiKey:Z}:{},auth:{...Z?{accessToken:Z}:{},...W?{refreshToken:W}:{},...j?{accountId:j}:{}}}}catch{return}}function HE($){let J=vQ.getGeneratedModelsForProvider($);return Object.keys(J)[0]??void 0}function BE($,J,Q,Z){let W=Fj($),j=E(Z==="plan"?J.planModeApiProvider:J.actModeApiProvider),f=XE(J,$,Z,j)??HE(W),X=YE(J,W,Z),Y=typeof J.requestTimeoutMs==="number"&&Number.isInteger(J.requestTimeoutMs)&&J.requestTimeoutMs>0?J.requestTimeoutMs:void 0,V={anthropic:Q.apiKey,cline:Q.clineApiKey,openai:Q.openAiApiKey,"openai-native":Q.openAiNativeApiKey,openrouter:Q.openRouterApiKey,bedrock:Q.awsBedrockApiKey,gemini:Q.geminiApiKey,ollama:Q.ollamaApiKey,deepseek:Q.deepSeekApiKey,requesty:Q.requestyApiKey,together:Q.togetherApiKey,fireworks:Q.fireworksApiKey,qwen:Q.qwenApiKey,doubao:Q.doubaoApiKey,mistral:Q.mistralApiKey,litellm:Q.liteLlmApiKey,asksage:Q.asksageApiKey,xai:Q.xaiApiKey,moonshot:Q.moonshotApiKey,zai:Q.zaiApiKey,huggingface:Q.huggingFaceApiKey,nebius:Q.nebiusApiKey,sambanova:Q.sambanovaApiKey,cerebras:Q.cerebrasApiKey,groq:Q.groqApiKey,"huawei-cloud-maas":Q.huaweiCloudMaasApiKey,baseten:Q.basetenApiKey,"vercel-ai-gateway":Q.vercelAiGatewayApiKey,dify:Q.difyApiKey,minimax:Q.minimaxApiKey,hicap:Q.hicapApiKey,aihubmix:Q.aihubmixApiKey,nousResearch:Q.nousResearchApiKey,oca:Q.ocaApiKey},H={};if($==="openai-codex")Object.assign(H,VE(Q));if($==="cline")try{let U=E(Q["cline:clineAccountId"]);if(U)H.auth={...H.auth??{},...Dj(U)}}catch{}if($===mQ&&J.openAiHeaders)H.headers=J.openAiHeaders;if($==="bedrock"){let U=J.awsAuthentication==="profile"||J.awsUseProfile===!0;H.aws={accessKey:E(Q.awsAccessKey),secretKey:E(Q.awsSecretKey),sessionToken:E(Q.awsSessionToken),region:E(J.awsRegion),authentication:J.awsAuthentication,profile:U?E(J.awsProfile):void 0,usePromptCache:J.awsBedrockUsePromptCache,useCrossRegionInference:J.awsUseCrossRegionInference,useGlobalInference:J.awsUseGlobalInference,endpoint:E(J.awsBedrockEndpoint),customModelBaseId:E(Z==="plan"?J.planModeAwsBedrockCustomModelBaseId:J.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")H.gcp={projectId:E(J.vertexProjectId),region:E(J.vertexRegion)};if($===mQ&&(J.azureApiVersion||J.azureIdentity!==void 0))H.azure={apiVersion:E(J.azureApiVersion),useIdentity:J.azureIdentity};if($==="sapaicore")H.sap={clientId:E(Q.sapAiCoreClientId),clientSecret:E(Q.sapAiCoreClientSecret),tokenUrl:E(J.sapAiCoreTokenUrl),resourceGroup:E(J.sapAiResourceGroup),deploymentId:E(Z==="plan"?J.planModeSapAiCoreDeploymentId:J.actModeSapAiCoreDeploymentId),useOrchestrationMode:J.sapAiCoreUseOrchestrationMode};if($==="oca"){H.oca={mode:J.ocaMode};let U=E(Q.ocaRefreshToken);if(U)H.auth={...H.auth??{},refreshToken:U}}if($==="qwen")H.apiLine=J.qwenApiLine;if($==="moonshot")H.apiLine=J.moonshotApiLine;if($==="zai")H.apiLine=J.zaiApiLine;if($==="minimax")H.apiLine=J.minimaxApiLine;let B={anthropic:J.anthropicBaseUrl,openai:J.openAiBaseUrl,ollama:J.ollamaBaseUrl,lmstudio:J.lmStudioBaseUrl,litellm:J.liteLlmBaseUrl,gemini:J.geminiBaseUrl,requesty:J.requestyBaseUrl,asksage:J.asksageApiUrl,dify:J.difyBaseUrl,oca:J.ocaBaseUrl,aihubmix:J.aihubmixBaseUrl,sapaicore:J.sapAiCoreBaseUrl},A=E(V[$]),K=E(B[$]),G={provider:W,...A?{apiKey:A}:{},...f?{model:f}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...Y?{timeout:Y}:{},...H},R=z8.safeParse(G);if(!R.success)return;return Object.keys(G).filter((U)=>U!=="provider").length>0?R.data:void 0}function AE($,J){if($!==bG)return;if(!J.baseUrl||!J.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:J.baseUrl,defaultModelId:J.model},models:{[J.model]:{id:J.model,name:J.model,contextWindow:yG,maxInputTokens:yG,capabilities:["streaming","tools","images"]}}}}function KE($,J){let Q=new Set;for(let W of[$.actModeApiProvider,$.planModeApiProvider]){let j=E(W);if(j)Q.add(j)}if(E(J.apiKey))Q.add("anthropic");if(E(J.openRouterApiKey))Q.add("openrouter");if(E(J.openAiApiKey))Q.add(mQ);if(E(J.openAiNativeApiKey))Q.add("openai-native");if(E(J["openai-codex-oauth-credentials"]))Q.add("openai-codex");if(E(J.geminiApiKey))Q.add("gemini");if(E(J.ollamaApiKey))Q.add("ollama");if(E(J.awsAccessKey)||E(J.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||E($.awsProfile))Q.add("bedrock");if(E($.vertexProjectId)||E($.vertexRegion))Q.add("vertex");if(E(J.clineApiKey))Q.add("cline");let Z=Dj(E(J["cline:clineAccountId"]));if(Z?.accessToken||Z?.refreshToken||Z?.accountId)Q.add("cline");if(E(J.ocaApiKey))Q.add("oca");if(E(J.sapAiCoreClientId)||E(J.sapAiCoreClientSecret)||E($.sapAiCoreTokenUrl)||E($.sapAiCoreBaseUrl)||E($.sapAiResourceGroup)||$.sapAiCoreUseOrchestrationMode!==void 0)Q.add("sapaicore");return Q}function PJ($){let J=$.providerSettingsManager.read(),Q=fE($);if(!Q)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let{globalState:Z,secrets:W}=Q,j=Z.mode==="plan"?"plan":"act",f=KE(Z,W),X=L$();X.providers={...J.providers},X.lastUsedProvider=J.lastUsedProvider;let Y=new Date().toISOString(),V=0,H=Gj(WE($.providerSettingsManager.getFilePath()),"models.json"),B=$j(H),A=0;for(let R of f){let D=Fj(R);if(X.providers[D])continue;let U=BE(R,Z,W,j);if(!U)continue;X.providers[D]={settings:U,updatedAt:Y,tokenSource:"migration"},V+=1;let F=AE(D,U);if(F&&!B.providers[D])B.providers[D]=F,A+=1}if(V===0&&A===0)return{migrated:!1,providerCount:Object.keys(J.providers).length,lastUsedProvider:J.lastUsedProvider};let K=E(j==="plan"?Z.planModeApiProvider:Z.actModeApiProvider),G=K?Fj(K):void 0;if(X.lastUsedProvider=J.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),A>0)GG(H,B);return{migrated:V>0||A>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}RQ();O0();YQ();var kG={};w(kG,{FileTeamPersistenceStore:()=>cQ});import{appendFileSync as GE,existsSync as Uj,mkdirSync as FE,readFileSync as DE,renameSync as UE,unlinkSync as RE,writeFileSync as zE}from"node:fs";import{join as Rj}from"node:path";import{resolveTeamDataDir as LE}from"@cline/shared/storage";function _E($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class cQ{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let J=_E($.teamName),Q=$.baseDir?.trim()||LE();this.dirPath=Rj(Q,J),this.statePath=Rj(this.dirPath,"state.json"),this.taskHistoryPath=Rj(this.dirPath,"task-history.jsonl")}loadState(){if(!Uj(this.statePath))return;try{let $=DE(this.statePath,"utf8"),J=JSON.parse($);if(J.version!==1||!J.teamState)return;for(let Q of J.teammates??[])this.teammateSpecs.set(Q.agentId,Q);return _A(J.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 J={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},Q=`${this.statePath}.tmp`;zE(Q,`${JSON.stringify(J,null,2)}
726
726
  `,"utf8"),UE(Q,this.statePath)}appendTaskHistory($){let J={};switch($.type){case"team_task_updated":J=$.task;break;case"team_message":J={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":J={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":J={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":J={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":J={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),GE(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:J})}
727
- `,"utf8")}ensureDir(){if(!Uj(this.dirPath))FE(this.dirPath,{recursive:!0})}hasPersistableState($){let J=$.exportState();if(this.teammateSpecs.size>0)return!0;if(J.members.some((Q)=>Q.role==="teammate"))return!0;return J.tasks.length>0||J.mailbox.length>0||J.missionLog.length>0}clearPersistedState(){if(Uj(this.statePath))RE(this.statePath)}}var xG={};w(xG,{ChatViewStateSchema:()=>zj,ChatSummarySchema:()=>r9,ChatSessionStatusSchema:()=>d9,ChatSessionConfigSchema:()=>u9,ChatMessageSchema:()=>p9,ChatMessageRoleSchema:()=>l9});import{z as h}from"zod";var u9=h.object({workspaceRoot:h.string().min(1),cwd:h.string().optional(),provider:h.string().min(1),model:h.string().min(1),mode:h.enum(["act","plan"]).default("act"),apiKey:h.string(),systemPrompt:h.string().optional(),rules:h.string().optional(),maxIterations:h.number().int().positive().optional(),enableTools:h.boolean(),enableSpawn:h.boolean().optional(),enableTeams:h.boolean().optional(),autoApproveTools:h.boolean().optional(),missionStepInterval:h.number().int().positive().optional(),missionTimeIntervalMs:h.number().int().positive().optional()}),d9=h.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),l9=h.enum(["user","assistant","tool","system","status","error"]),p9=h.object({id:h.string().min(1),sessionId:h.string().nullable(),role:l9,content:h.string(),createdAt:h.number().int().nonnegative(),meta:h.object({stream:h.enum(["stdout","stderr"]).optional(),toolName:h.string().optional(),iteration:h.number().int().nonnegative().optional(),agentId:h.string().optional(),conversationId:h.string().optional(),hookEventName:h.string().optional(),inputTokens:h.number().int().nonnegative().optional(),outputTokens:h.number().int().nonnegative().optional(),checkpoint:h.object({ref:h.string(),createdAt:h.number().int().nonnegative(),runCount:h.number().int().positive(),kind:h.enum(["stash","commit"]).optional()}).optional()}).optional()}),r9=h.object({toolCalls:h.number().int().nonnegative(),tokensIn:h.number().int().nonnegative(),tokensOut:h.number().int().nonnegative()}),zj=h.object({sessionId:h.string().nullable(),status:d9,config:u9,messages:h.array(p9),rawTranscript:h.string(),error:h.string().nullable(),summary:r9});var gG={};w(gG,{CORE_BUILD_VERSION:()=>Lj});var Lj=UB;import{Agent as jb,createAgentRuntime as fb}from"@cline/agents";var mG={};w(mG,{fetchClineRecommendedModels:()=>Oj,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>i9});import{getClineEnvironmentConfig as OE}from"@cline/shared";var TE=5000,i9={clinePass:[],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 ME($){return{clinePass:$.clinePass.map((J)=>({...J,tags:[...J.tags]})),recommended:$.recommended.map((J)=>({...J,tags:[...J.tags]})),free:$.free.map((J)=>({...J,tags:[...J.tags]}))}}function _j($){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.id!=="string"||J.id.length===0)return null;return{id:J.id,name:typeof J.name==="string"&&J.name.length>0?J.name:J.id,description:typeof J.description==="string"?J.description:"",tags:Array.isArray(J.tags)?J.tags.filter((Q)=>typeof Q==="string"):[]}}function qE($){if(!$||typeof $!=="object")return null;let J=$,Q=Array.isArray(J.recommended)?J.recommended:[],Z=Array.isArray(J.free)?J.free:[],W=Array.isArray(J.clinePass)?J.clinePass:[],j=Q.map(_j).filter((Y)=>Y!==null),f=Z.map(_j).filter((Y)=>Y!==null),X=W.map(_j).filter((Y)=>Y!==null);if(j.length===0&&f.length===0&&X.length===0)return null;return{recommended:j,free:f,clinePass:X}}function PE($){let J=$.baseUrl?.trim();if(J)return J;let Q=OE().apiBaseUrl;try{return($.providerSettingsManager??new _1).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function NE($,J,Q){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await $(J,{signal:Z.signal})}finally{clearTimeout(W)}}async function Oj($={}){try{let J=PE($),Q=$.fetchImpl??fetch,Z=await NE(Q,`${J}/api/v1/ai/cline/recommended-models`,$.timeoutMs??TE);if(!Z.ok)throw Error(`HTTP ${Z.status}`);let W=await Z.json(),j=qE(W);if(j)return j}catch{}return ME(i9)}var vG={};w(vG,{loadLlmsConfigFromFile:()=>Mj,defineLlmsConfig:()=>Tj});import{readFile as wE}from"node:fs/promises";import SE from"node:path";function Tj($){return $}async function Mj($){let J=SE.resolve($),Q=await wE(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${J}": ${j}`)}return CE(Z,J)}function CE($,J){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${J}": expected an object.`);let Z=$.providers;if(!Array.isArray(Z))throw Error(`Invalid llms config in "${J}": "providers" must be an array.`);if(!Z.length)throw Error(`Invalid llms config in "${J}": "providers" cannot be empty.`);return $}var rG={};w(rG,{createLlmsSdk:()=>Pj,DefaultLlmsSdk:()=>NJ});import{BUILT_IN_PROVIDER_IDS as dG,createHandler as bE,createHandlerAsync as hE,getProviderCollection as kE,hasProvider as lG,registerAsyncHandler as IE,registerHandler as xE,registerModel as gE,registerProvider as pG}from"@cline/llms";function cG($){return $?{...$}:{}}function yE($,J){if($)return $;if(!J)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[J]}function EE($,J){if(!J.length)throw Error(`Provider "${$}" must include at least one model.`)}function uG($){let J=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:J,defaultModel:$.collection.provider.defaultModelId,modelCount:J.length}}class qj{providers=new Map;register($){EE($.id,$.models);let J=$.defaultModel??$.models[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(J))throw Error(`Default model "${J}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:J,defaults:{...Q?.defaults??{},...cG($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:yE($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...cG($.settings)}})}registerModel($,J){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([J]),defaultModel:J,defaults:{}});return}Q.models.add(J)}createHandlerConfig($){let J=this.require($.providerId),Q=$.modelId??J.defaultModel;if(!J.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...J.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($,J){return this.providers.get($)?.models.has(J)??!1}require($){let J=this.providers.get($);if(!J)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return J}}class NJ{configuredProviders=new qj;constructor($){this.applyConfig($)}createHandler($){return bE(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return hE(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(pG($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)xE($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)IE($.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 J=$.exposeModels??Object.keys($.models),Q=$.defaultModel??J[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);pG({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:J,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){gE($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...dG]}async getBuiltInProviders(){return(await Promise.all(dG.map((J)=>kE(J)))).filter((J)=>J!==void 0).map((J)=>uG({collection:J}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,J){return this.configuredProviders.hasModel($,J)}applyConfig($){for(let J of $.providers)this.configuredProviders.registerSelectionConfig(J);for(let J of $.models??[])this.registerModel(J);for(let J of $.customProviders??[])this.registerProvider(J);for(let J of this.configuredProviders.list()){let Q=lG(J.id),Z=this.configuredProviders.createHandlerConfig({providerId:J.id,modelId:J.defaultModel}).routingProviderId,W=typeof Z==="string"&&lG(Z);if(!Q&&!W)throw Error(`Provider "${J.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function Pj($){return new NJ($)}X3();async function mE(){return Promise.resolve().then(() => (R9(),rK))}function Bb(){return new Date().toISOString()}var Ab="cline",Kb="cline-pass";function Gb($){if(sG($)!=="providers.json")return;let J=wj($);if(sG(J)!=="settings")return;return wj(J)}class _1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Hb(),this.dataDir=$.dataDir??Gb(this.filePath),this.dataDir||!$.filePath)PJ({providerSettingsManager:this,dataDir:this.dataDir});if(OG(this),E9(this.read()),Nj(this.filePath))try{aG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!Nj(this.filePath))return L$();try{let $=Yb(this.filePath,"utf8"),J=JSON.parse($),Q=L8.safeParse(J);if(Q.success)return E9(Q.data),Q.data}catch{}return L$()}write($){let J=L8.parse($),Q=wj(this.filePath);if(!Nj(Q))Xb(Q,{recursive:!0,mode:448});Vb(this.filePath,`${JSON.stringify(J,null,2)}
728
- `,"utf8");try{aG(this.filePath,384)}catch{}E9(J)}saveProviderSettings($,J={}){let Q=z8.parse($),Z=this.read(),W=Q.provider,j=J.setLastUsed!==!1,f=Z.providers[W],X=J.tokenSource??f?.tokenSource??"manual",Y={...Z,providers:{...Z.providers,[W]:{settings:Q,updatedAt:Bb(),tokenSource:X}},lastUsedProvider:j?W:Z.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,J){let Q=$.providers[J]?.settings,W=Z0(J)?.storageProviderId;if(!W||W===J)return Q;let j=$.providers[W]?.settings;if(!j)return Q;return z8.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Q??{},provider:J})}getProviderSettings($){let J=this.read();return this.resolveProviderSettings(J,$)}resolveLastUsedProviderId($,J){let Q=$.lastUsedProvider;if(Q===Kb&&J.isClinePassEnabled===!1)return Ab;return Q}getLastUsedProviderSettings($={}){let J=this.read(),Q=this.resolveLastUsedProviderId(J,$);if(!Q)return;return this.resolveProviderSettings(J,Q)}getProviderConfig($,J){let Q=this.getProviderSettings($);if(!Q)return;return d0(Q,J)}getLastUsedProviderConfig($={}){let J=this.getLastUsedProviderSettings($);if(!J)return;return d0(J,$)}async refreshCatalog(){try{await U8({})}catch{}}}O0();g8();function Fb($,J){let Q=$?.expiresAt,Z=J?.expiresAt;return $?.accessToken===J?.accessToken&&$?.refreshToken===J?.refreshToken&&$?.accountId===J?.accountId&&Q===Z}class n9 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 Sj{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new _1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let J=Z0($.providerId);if(!J)return null;return this.resolveWithSingleFlight(J.providerId,J.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,J,Q=!1){let Z=this.refreshInFlight.get(J);if(Z)return Z;let W=this.resolveProviderApiKeyInternal($,J,Q).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(J)});return this.refreshInFlight.set(J,W),W}async resolveProviderApiKeyInternal($,J,Q){let Z=Z0($);if(!Z)return null;let W=this.providerSettingsManager.getProviderSettings(J);if(!W)return null;let j=L4($,W);if(!j)return null;let f=await Z.refresh({settings:W,credentials:j,forceRefresh:Q,telemetry:this.telemetry});if(!f)throw new n9($);let X=x$({manager:this.providerSettingsManager,providerId:$,settings:W,credentials:f,setLastUsed:!1,save:!1}),Y=!Fb(W.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Z.getApiKey(X)??f.access,accountId:f.accountId,refreshed:Y}}}import{normalizeUserInput as Db}from"@cline/shared";import{nanoid as Ub}from"nanoid";class oG{list($){return $?e0($):[]}update($,J){if(!$)return{sessionId:J.sessionId,prompts:[],updated:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((Y)=>Y.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:e0($),updated:!1};let W=$.pendingPrompts[Z];if(!W)return{sessionId:J.sessionId,prompts:e0($),updated:!1};let j=J.prompt===void 0?W.prompt:Db(J.prompt).trim();if(!j)throw Error("prompt cannot be empty");let f=J.delivery??W.delivery,X={...W,prompt:j,mode:J.mode??W.mode,delivery:f};return $.pendingPrompts.splice(Z,1),Rb($,X,Z,W.delivery),{sessionId:J.sessionId,prompts:e0($),prompt:a9(X),updated:!0}}delete($,J){if(!$)return{sessionId:J.sessionId,prompts:[],removed:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((j)=>j.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:e0($),removed:!1};let[W]=$.pendingPrompts.splice(Z,1);return{sessionId:J.sessionId,prompts:e0($),prompt:W?a9(W):void 0,removed:!0}}enqueue($,J){let{prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f}=J,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===Q);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:Q,mode:Z??Y.mode,userImages:j??Y.userImages,userFiles:f??Y.userFiles};if(W==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${Ub(5)}`,prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f};if(W==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return e0($)}consumeSteer($){let J=$.pendingPrompts.findIndex((Z)=>Z.delivery==="steer");if(J<0)return{prompts:e0($)};let[Q]=$.pendingPrompts.splice(J,1);return{entry:Q,prompts:e0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:e0($)}}requeueFront($,J){return $.pendingPrompts.unshift(J),e0($)}clear($){return $.pendingPrompts.length=0,[]}}class Cj{deps;service=new oG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}delete($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}enqueue($,J){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,J),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let J=this.deps.getSession($);if(!J)return;let{entry:Q}=this.service.consumeSteer(J);if(!Q)return;return this.emitPrompts(J),this.emitSubmitted(J,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:e0($)}})}scheduleDrain($,J){if(J.pendingPrompts.length===0||J.aborting||J.drainingPendingPrompts||!J.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let J=this.deps.getSession($);if(!J)return;if(J.aborting||J.drainingPendingPrompts)return;if(!J.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(J);if(!Q)return;this.emitPrompts(J),this.emitSubmitted(J,Q),J.drainingPendingPrompts=!0;let Z=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{Z=!1,this.service.requeueFront(J,Q),this.emitPrompts(J)}finally{if(J.drainingPendingPrompts=!1,Z&&J.pendingPrompts.length>0&&J.status!=="failed"&&J.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,J){let Q=a9(J);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}})}}function a9($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function e0($){return $.pendingPrompts.map(a9)}function Rb($,J,Q,Z){if(J.delivery==="steer")$.pendingPrompts.unshift(J);else if(Z==="steer")$.pendingPrompts.push(J);else $.pendingPrompts.splice(Q,0,J)}O0();class Ej{deps;constructor($){this.deps=$}dispatchAgentEvent($,J,Q){let Z=this.deps.getSession($),W={sessionId:$,config:J,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=f7(Q),f=!!Z&&(!j.agentId||j.agentId===yj(Z.agent));X7(W,Q,f?{isPrimaryAgentEvent:!0,agentId:yj(Z.agent),conversationId:Z.agent.getConversationId(),...Z?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,J){let Q=this.deps.getSession($);if(Q){if(pW(Q,J),J.type==="agent_event"){let Z={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};X7(Z,J.event,{agentId:J.agentId,teamRole:"teammate",teamAgentId:J.agentId,isPrimaryAgentEvent:!1})}if(J.type==="teammate_spawned"){let Z=g1({agentId:J.teammate.runtimeAgentId??J.agentId,conversationId:J.teammate.conversationId,parentAgentId:J.teammate.parentAgentId,createdByAgentId:yj(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:J.agentId});if(Z)$$(Q.config.telemetry,{ulid:$,modelId:J.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...Z})}}if(await rW($,J,this.deps.invokeBackendOptional),Q)iW(Q,$,J,this.deps.emit)}async handlePluginEvent($,J,Q){if(J.name==="plugin_log"){this.handlePluginLog($,J.payload);return}if(J.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!Y)return;let V=J.payload&&typeof J.payload==="object"?J.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(J.name!=="steer_message"&&J.name!=="queue_message"&&J.name!=="pending_prompt")return;let Z=J.payload&&typeof J.payload==="object"?J.payload:void 0,W=typeof Z?.sessionId==="string"&&Z.sessionId.trim().length>0?Z.sessionId.trim():$,j=typeof Z?.prompt==="string"?Z.prompt.trim():"";if(!j)return;let f=J.name==="steer_message"?"steer":J.name==="queue_message"?"queue":Z?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:j,delivery:f})}handlePluginLog($,J,Q){let Z=this.deps.getSession($),W=Q??Z?.config.extensionContext?.logger??Z?.config.logger;if(!W||!J||typeof J!=="object")return;let j=J,f=typeof j.message==="string"?j.message:"";if(!f)return;let X=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(X.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)X.pluginName=j.pluginName;if(j.level==="debug"){W.debug(f,X);return}if(j.level==="error"){if(W.error)W.error(f,X);else W.log(f,{...X,severity:"error"});return}W.log(f,X)}}function yj($){return $.getAgentId()}function bj($){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:G$($.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 hj($,J){let Q=$[J];return typeof Q==="function"?Q:null}async function tG($,J,...Q){let Z=hj($,J);if(!Z)throw Error(`session service method not available: ${J}`);return Promise.resolve(Z.apply($,Q))}async function eG($,J,...Q){let Z=hj($,J);if(!Z)return;await Promise.resolve(Z.apply($,Q))}async function $F($,J,...Q){let Z=hj($,J);if(!Z)return;return await Promise.resolve(Z.apply($,Q))}W1();O0();function kj($,J,Q){return{onSubAgentEvent:(Z)=>$.onAgentEvent(Q,J,Z),onSubAgentStart:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(Z.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let j=g1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId});if(j)$$(J.telemetry,{ulid:Q,modelId:J.modelId,provider:J.providerId,...j});B4(J.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:Z.parentAgentId,agentId:Z.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Q,Z)},onSubAgentEnd:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime,j=$.subAgentStarts.get(Z.subAgentId),f=j?Date.now()-j.startedAt:0,X=Z.result?.text?Z.result.text.split(`
729
- `).length:0;B4(J.telemetry,{event:"ended",ulid:Q,durationMs:f,outputLines:X,errorMessage:Z.error?String(Z.error):void 0,agentId:Z.subAgentId,parentId:Z.parentAgentId,...g1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId})}),$.subAgentStarts.delete(Z.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,Z)}}}function Ij($,J,Q,Z){let W=kj($,J,Q);return A$({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:J.hooks,extensions:J.extensions,logger:J.logger,telemetry:J.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let f=J.enableTools?n$({cwd:J.cwd,...c0[h1({mode:J.mode})],executors:Z}):[];if(J.enableSpawnAgent)f.push(Ij($,J,Q,Z));return I1(f)},...W})}import{readFile as zb,stat as Lb}from"node:fs/promises";var _b=20480000;async function JF($){let J=await Lb($);if(!J.isFile())throw Error("Path is not a file");if(J.size>_b)throw Error("File is too large to read into context.");let Q=await zb($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var QF=5000;function wJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Sb($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=wJ(J.inputTokens),Z=wJ(J.outputTokens),W=wJ(J.cacheReadTokens),j=wJ(J.cacheWriteTokens),f=wJ(J.totalCost);if(Q===void 0||Z===void 0||W===void 0||j===void 0||f===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:W,cacheWriteTokens:j,totalCost:f}}function Cb($,J){return{inputTokens:Math.max($.inputTokens,J.inputTokens),outputTokens:Math.max($.outputTokens,J.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,J.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,J.cacheWriteTokens),totalCost:Math.max($.totalCost,J.totalCost)}}class L1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new o6;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new y$;constructor($){let J=Tb();if(J)wb(J);let Q=b0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new W4,this.createAgentInstance=$.createAgent??((Z)=>new V$(Z)),this.defaultCapabilities=L0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new _1,this.oauthTokenManager=$.oauthTokenManager??new Sj({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new Cj({getSession:(Z)=>this.sessions.get(Z),emit:(Z)=>this.emit(Z),send:(Z)=>this.runTurn(Z)}),this.pendingPrompts={list:async(Z)=>this.pendingPromptsController.list(Z.sessionId),update:async(Z)=>this.pendingPromptsController.update(Z),delete:async(Z)=>this.pendingPromptsController.delete(Z)},this.eventBridge=new Ej({getSession:(Z)=>this.sessions.get(Z),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Z)=>this.emit(Z),persistMessages:(Z,W,j)=>{this.invoke("persistSessionMessages",Z,W,j)},enqueuePendingPrompt:(Z,W)=>this.pendingPromptsController.enqueue(Z,W),invokeBackendOptional:(Z,...W)=>this.invokeOptional(Z,...W)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!J?.apiKey)return $;return{...$,config:{...$.config,apiKey:J.apiKey}}}async startSession($){let J=$.source??U0.CLI,Q=e(),Z=$.config.sessionId?.trim()??"",W=Z||qb(),j=await this.applyInitialOAuthCredentials($),f=j.initialMessages??[],X=f.length>0?f8(f):G0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=xj(Y,W),H=xj(V,`${W}.messages.json`),B=xj(V,`${W}.json`),A=G$($.config),K=S0.parse({version:1,session_id:W,source:J,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:A,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),G;if(Z.length>0&&f.length>0&&!j.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",W);if(C)K=C,G={manifestPath:B,messagesPath:C.messages_path||H,manifest:C}}let D=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??H,manifest:K});this.usageBySession.set(W,X),this.aggregateUsageBySession.set(W,D);let U=L0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z,P={getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,F0,f0)=>this.eventBridge.dispatchAgentEvent(C,F0,f0),invokeBackendOptional:(C,...F0)=>this.invokeOptional(C,...F0)};z=await gV({input:j,localRuntime:$.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(W,C.payload,T);return}this.eventBridge.handlePluginEvent(W,C,L)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(W,C),z.config.onTeamEvent?.(C)},createSpawnTool:()=>Ij(P,z.config,W,F),createSubAgentLifecycleCallbacks:(C)=>kj(P,C,W),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(W,()=>C)}});let S=await this.runtimeBuilder.build(z.runtimeBuilderInput),b=z.config,u=z.providerConfig;if(S.teamRuntime&&!b.teamName?.trim())b.teamName=S.teamRuntime.getTeamName();let o=[...S.tools,...b.extraTools??[]],J0=S.extensions??z.extensions,t={sessionId:W,providerId:u.providerId,modelId:u.modelId,apiKey:u.apiKey,baseUrl:u.baseUrl,headers:u.headers,knownModels:u.knownModels,providerConfig:u,thinking:b.thinking,reasoningEffort:b.reasoningEffort??u.reasoningEffort,systemPrompt:b.systemPrompt,maxIterations:b.maxIterations,execution:b.execution,prepareTurn:P4(b),tools:o,hooks:z.hooks,extensions:J0,hookErrorMode:b.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:JF,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(C)=>{let F0=z.requestToolApproval,f0=this.sessions.get(W);if(f0)await this.markTurnPending(f0);try{if(!F0)return{approved:!1,reason:"Tool approval callback is not configured."};return await F0(C)}finally{let w0=this.sessions.get(W);if(w0?.status==="pending")await this.markTurnRunning(w0)}}:void 0,telemetry:b.telemetry,onConsecutiveMistakeLimitReached:b.onConsecutiveMistakeLimitReached,completionPolicy:S.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(W);return C?HJ(C.prompt,C.mode??b.mode):void 0},logger:S.logger??b.logger,extensionContext:b.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(W,b,C)};t.hooks={...t.hooks,onEvent:async(C)=>{if(await z.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let F0=this.sessions.get(W);if(!F0)return;let f0=F0.agent.getMessages();try{await this.invoke("persistSessionMessages",W,f0,b.systemPrompt)}catch(w0){b.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:w0}),h2(b.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:w0,severity:"warn",handled:!0,context:{sessionId:W,providerId:b.providerId,modelId:b.modelId}})}}};let $1=this.createAgentInstance(t);if(t.onEvent)$1.subscribeEvents(t.onEvent);S.registerLeadAgent?.($1);let b$=g1({agentId:$1.getAgentId(),conversationId:$1.getConversationId(),teamId:S.teamRuntime?.getTeamId(),teamName:S.teamRuntime?.getTeamName(),teamRole:S.teamRuntime?"lead":void 0});if(vV(b,W,Z.length>0,A,b$),b$)$$(b.telemetry,{ulid:W,modelId:b.modelId,provider:b.providerId,...b$});if(S.teamRuntime)pJ(b.telemetry,{ulid:W,teamId:S.teamRuntime.getTeamId(),teamName:S.teamRuntime.getTeamName(),leadAgentId:$1.getAgentId(),restoredFromPersistence:S.teamRestoredFromPersistence===!0});let n={sessionId:W,config:b,sessionMetadata:j.sessionMetadata,...G?{artifacts:G}:{},source:J,startedAt:G?.manifest.started_at??Q,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??Q,pendingPrompt:K.prompt,runtime:S,agent:$1,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:f,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(W,n),this.emitStatus(W,"running"),f.length>0&&!G){if(await this.ensureSessionPersisted(n),await this.invoke("persistSessionMessages",n.sessionId,f,n.config.systemPrompt),!j.prompt?.trim())await this.updateStatus(n,"completed",0)}let O1;try{if(j.prompt?.trim())if(O1=await this.executeTurn(n,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!n.interactive)await this.finalizeSingleRun(n,O1.finishReason);else await this.completeInteractiveTurn(n,O1.finishReason)}catch(C){if(n.interactive&&n.aborting)O1=await this.completeAbortedInteractiveTurn(n);else throw h2(n.config.telemetry,{component:"core",operation:"session.start",error:C,severity:"error",handled:!1,context:{sessionId:n.sessionId,providerId:n.config.providerId,modelId:n.config.modelId}}),await this.failSession(n),C}return{sessionId:W,manifest:K,manifestPath:B,messagesPath:H,result:O1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(J)=>this.getSession(J),readMessages:(J)=>this.readSessionMessages(J),buildStartInput:(J,Q)=>{let Z=J.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:J.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...Z?{sessionMetadata:Z}:{},initialMessages:J.initialMessages}},startSession:(J)=>this.startSession(J),getStartedSessionId:(J)=>J.sessionId,readRestoredSession:(J)=>this.getSession(J)})}async runTurn($){let J=this.getSessionOrThrow($.sessionId),Q=J.agent.canStartRun(),Z=$.delivery??(J.interactive&&!Q?"queue":void 0);if(J.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Z??"immediate"}}),Z==="queue"||Z==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Z,userImages:$.userImages,userFiles:$.userFiles});return}try{let W=await this.executeTurn(J,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!J.interactive)await this.finalizeSingleRun(J,W.finishReason);else await this.completeInteractiveTurn(J,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),W}catch(W){if(J.interactive&&J.aborting)return await this.completeAbortedInteractiveTurn(J);throw h2(J.config.telemetry,{component:"core",operation:"session.submit",error:W,severity:"error",handled:!1,context:{sessionId:J.sessionId,providerId:J.config.providerId,modelId:J.config.modelId}}),await this.failSession(J),W}}async getAccumulatedUsage($){let J=zW(this.usageBySession.get($)),Q=zW(this.aggregateUsageBySession.get($));return J||Q?{usage:J,aggregateUsage:Q}:void 0}async abort($,J){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(J)}async stopSession($){let J=this.sessions.get($);if(!J)return;if(J.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),J.interactive&&!j0(J.status)){await this.releaseSessionRuntime(J,"session_stop");return}if(J.interactive&&J.agent.canStartRun()){await this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:"session_stop",endReason:"stopped"});return}J.aborting=!0,J.agent.abort(Error("session_stop")),await this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let J=[...this.sessions.values()];if(J.length===0)return;await Promise.allSettled(J.map((Q)=>Q.interactive&&!j0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let J=this.sessions.get($);if(J)return bj(J);let Q=$.trim();if(!Q)return;let Z=await this.getRow(Q);if(Z)return $6(Z);let W=await this.readManifest(Q);return W?mQ(W):void 0}async listSessions($=200){let Q=(await this.listRows($)).map($6),Z=new Set(Q.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(Z.has(W.sessionId))continue;Q.unshift(bj(W))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let J=await this.invoke("deleteSession",$);if(J.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return J.deleted}async updateSession($,J){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:J.prompt,metadata:J.metadata,title:J.title}))?.updated===!0}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.getRow(J);if(Q?.messagesPath)return q$(Q.messagesPath);let Z=await this.readManifest(J);return q$(Z?.messages_path)}async dispatchHookEvent($){await VB($,{queueSpawnRequest:(J)=>this.invokeOptional("queueSpawnRequest",J),upsertSubagentSessionFromHook:(J)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",J),appendSubagentHookAudit:(J,Q)=>this.invokeOptional("appendSubagentHookAudit",J,Q),applySubagentStatus:(J,Q)=>this.invokeOptional("applySubagentStatus",J,Q)})}subscribe($,J){return this.events.subscribe($,J)}async updateSessionModel($,J){let Q=this.getSessionOrThrow($);Q.config.modelId=J,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:J}),Q.agent.updateConnection({modelId:J})}handlePluginEvent($,J,Q){return this.eventBridge.handlePluginEvent($,J,Q)}async executeTurn($,J){let Q=await this.prepareTurnInput($,J),Z=Q.prompt.trim();if(!Z)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Z;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let W=await this.executeAgentTurn($,Z,Q.userImages,Q.userFiles);while(nW($,W.finishReason)){let j=await aW($);if(j.length===0)break;let f=sW($,j);W=await this.executeAgentTurn($,f)}return W}async completeInteractiveTurn($,J){if(VJ($))return;$.lastInteractiveTurnFinishReason=J,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let J=$.lastInteractiveTurnFinishReason;if(!J)return"cancelled";switch(J){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return J}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let J=new Date,Q=$.agent.getMessages(),Z=G0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Z}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Z,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:J,endedAt:J,durationMs:0}}async executeAgentTurn($,J,Q,Z){let W=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),f=this.usageBySession.get($.sessionId)??G0(),X=this.aggregateUsageBySession.get($.sessionId)??f;$.turnUsageBaseline=f,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=G0(),$.turnUsageByAgent=new Map,gJ($.config.telemetry,$.sessionId,$.config.mode),g2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=W?()=>$.agent.continue(J,Q,Z):()=>$.agent.run(J,Q,Z),V=await this.runWithAuthRetry($,Y,j);$.started=!0;let H=y5(V.messages,V,j);$.persistedMessages=H;let B=Q6($.turnUsageByAgent?.values()??[]),A=V0(f,V.usage),K=V0(V0(G0(),V.usage),B),G=V0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw h2($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,J){if($.submitAndExitObserved)return;if(!J.toolCalls.some((Z)=>Z.name===K0.SUBMIT_AND_EXIT&&Z.error===void 0))return;$.submitAndExitObserved=!0,V4($.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($,J){let Q=G$($.config),Z=Nb(J.prompt).trim();if(!Z)return{prompt:"",userImages:J.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles)};let W=await a2(Z,Q);cV($.config.telemetry,W);let j=HJ(W.prompt,J.mode??$.config.mode),f=this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles),X=this.resolveAbsoluteFilePaths(Q,W.matchedFiles),Y=Array.from(new Set([...f,...X]));return{prompt:j,userImages:J.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let J=G$($.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:J,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($,J){let Q=this.sessions.get($),Z=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,W=J(Z?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:W}))?.updated===!1)return;Q.sessionMetadata=W,Q.artifacts.manifest.metadata=W}async finalizeSingleRun($,J){if(VJ($))return;let Q=J==="aborted"||$.aborting,Z=J==="error";await this.shutdownSession($,{status:Q?"cancelled":Z?"failed":"completed",exitCode:Z?1:0,shutdownReason:Z?"session_error":"session_complete",endReason:J})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,J){if(J.status==="completed"&&!$.submitAndExitObserved)V4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});Q9($);let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),h2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,status:J.status,shutdownReason:J.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,J.status,J.exitCode)}catch(W){Z("update_status",W)}try{await $.agent.shutdown(J.shutdownReason)}catch(W){Z("agent_shutdown",W)}}try{await Promise.resolve($.runtime.shutdown(J.shutdownReason))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:J.endReason,ts:Date.now()}}),Q.length>0&&J.status==="failed")throw Q[0]}async releaseSessionRuntime($,J){let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),h2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,reason:J,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(J)}catch(W){Z("agent_shutdown",W)}try{await Promise.resolve($.runtime.shutdown(J))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,J,Q){if(!$.artifacts)return;let Z=await this.invoke("updateSessionStatus",$.sessionId,J,Q);if(!Z.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(W.status=J,j0(J))delete W.ended_at,W.exit_code=null;else W.ended_at=Z.endedAt??e(),W.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=W,$.status=J,$.updatedAt=Z.endedAt??e(),$.endedAt=j0(J)?null:W.ended_at,$.exitCode=W.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,W),this.emitStatus($.sessionId,J)}async runWithAuthRetry($,J,Q){try{return await J()}catch(Z){if(!I$($.config.providerId)||!Pb(Z))throw Z;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),J()}}async syncOAuthCredentials($,J){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:J?.forceRefresh})}catch(Z){if(Z instanceof n9)throw Error(`${Z.providerId} requires re-authentication.`);throw Z}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let J=this.sessions.get($);if(!J){let Q=new u1($);throw h2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return J}resolveAbsoluteFilePaths($,J){if(!J||J.length===0)return[];let Q=J.map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Mb(Z)?Z:gj($,Z));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return g1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let J=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=V0($.initialUsage,J);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,J,Q){let Z=gj(J),W=`${Q}.messages.json`,j;try{j=Ob($)}catch{return G0()}let f=G0();for(let X of j){if(!X.endsWith(".messages.json"))continue;if(X===W)continue;let Y=gj($,X);if(Y===Z)continue;let V=await q$(Y);if(V.length===0)continue;f=V0(f,f8(V))}return f}withPersistedAggregateUsageFloor($,J){let Q=Sb(J.metadata?.aggregateUsage);if(Q)return Cb($,Q);let Z=J.metadata?.aggregatedAgentsCost;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=$.totalCost)return $;return{...$,totalCost:Z}}emitStatus($,J){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:J}})}async emitSessionSnapshot($){let J=await this.getSession($);if(!J)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:F1({session:J,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($)),QF))}async getRow($){let J=$.trim();if(!J)return;return(await this.listRows(QF)).find((Z)=>Z.sessionId===J)}async readManifest($){let J=$.trim();if(!J)return;return await this.invokeOptionalValue("readSessionManifest",J)}invoke($,...J){return tG(this.sessionService,$,...J)}invokeOptional($,...J){return eG(this.sessionService,$,...J)}invokeOptionalValue($,...J){return $F(this.sessionService,$,...J)}}function Eb($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function bb($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function U9($={}){let J=new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||U0.CLI,interactive:!1,config:{providerId:yb(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:bb(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:Eb(W)}},async abortSession(Q){return await J.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}kb(process.env.CLINE_VCR);function xb($){let J=process.cwd(),Q,Z,W;for(let j=0;j<$.length;j+=1){let f=$[j],X=$[j+1];if(f==="--cwd"&&X){J=X,j+=1;continue}if(f==="--host"&&X){Q=X,j+=1;continue}if(f==="--port"&&X){let Y=Number(X);if(Number.isFinite(Y))Z=Y;j+=1;continue}if(f==="--pathname"&&X)W=X,j+=1}return{cwd:J,host:Q,port:Z,pathname:W}}async function gb(){let $=xb(process.argv.slice(2));process.chdir($.cwd);let J=i0({host:$.host,port:$.port,pathname:$.pathname}),Q=await C2({host:J.host,port:J.port,pathname:J.pathname,owner:Ib()==="production"?n0():E0(),runtimeHandlers:U9(),cronOptions:{workspaceRoot:$.cwd}}),Z=async()=>{await Q.close(),process.exit(0)},W=!1,j=(f,X)=>{if(W)return;W=!0;let Y=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] ${f}: ${Y}
727
+ `,"utf8")}ensureDir(){if(!Uj(this.dirPath))FE(this.dirPath,{recursive:!0})}hasPersistableState($){let J=$.exportState();if(this.teammateSpecs.size>0)return!0;if(J.members.some((Q)=>Q.role==="teammate"))return!0;return J.tasks.length>0||J.mailbox.length>0||J.missionLog.length>0}clearPersistedState(){if(Uj(this.statePath))RE(this.statePath)}}var IG={};w(IG,{ChatViewStateSchema:()=>zj,ChatSummarySchema:()=>rQ,ChatSessionStatusSchema:()=>dQ,ChatSessionConfigSchema:()=>uQ,ChatMessageSchema:()=>pQ,ChatMessageRoleSchema:()=>lQ});import{z as h}from"zod";var uQ=h.object({workspaceRoot:h.string().min(1),cwd:h.string().optional(),provider:h.string().min(1),model:h.string().min(1),mode:h.enum(["act","plan"]).default("act"),apiKey:h.string(),systemPrompt:h.string().optional(),rules:h.string().optional(),maxIterations:h.number().int().positive().optional(),enableTools:h.boolean(),enableSpawn:h.boolean().optional(),enableTeams:h.boolean().optional(),autoApproveTools:h.boolean().optional(),missionStepInterval:h.number().int().positive().optional(),missionTimeIntervalMs:h.number().int().positive().optional()}),dQ=h.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),lQ=h.enum(["user","assistant","tool","system","status","error"]),pQ=h.object({id:h.string().min(1),sessionId:h.string().nullable(),role:lQ,content:h.string(),createdAt:h.number().int().nonnegative(),meta:h.object({stream:h.enum(["stdout","stderr"]).optional(),toolName:h.string().optional(),iteration:h.number().int().nonnegative().optional(),agentId:h.string().optional(),conversationId:h.string().optional(),hookEventName:h.string().optional(),inputTokens:h.number().int().nonnegative().optional(),outputTokens:h.number().int().nonnegative().optional(),checkpoint:h.object({ref:h.string(),createdAt:h.number().int().nonnegative(),runCount:h.number().int().positive(),kind:h.enum(["stash","commit"]).optional()}).optional()}).optional()}),rQ=h.object({toolCalls:h.number().int().nonnegative(),tokensIn:h.number().int().nonnegative(),tokensOut:h.number().int().nonnegative()}),zj=h.object({sessionId:h.string().nullable(),status:dQ,config:uQ,messages:h.array(pQ),rawTranscript:h.string(),error:h.string().nullable(),summary:rQ});var xG={};w(xG,{CORE_BUILD_VERSION:()=>Lj});var Lj=DB;import{Agent as jb,createAgentRuntime as fb}from"@cline/agents";var mG={};w(mG,{fetchClineRecommendedModels:()=>_j,FALLBACK_CLINE_RECOMMENDED_MODELS:()=>iQ});import{getClineEnvironmentConfig as OE}from"@cline/shared";var TE=5000,iQ={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 ME($){return{recommended:$.recommended.map((J)=>({...J,tags:[...J.tags]})),free:$.free.map((J)=>({...J,tags:[...J.tags]}))}}function gG($){if(!$||typeof $!=="object")return null;let J=$;if(typeof J.id!=="string"||J.id.length===0)return null;return{id:J.id,name:typeof J.name==="string"&&J.name.length>0?J.name:J.id,description:typeof J.description==="string"?J.description:"",tags:Array.isArray(J.tags)?J.tags.filter((Q)=>typeof Q==="string"):[]}}function qE($){if(!$||typeof $!=="object")return null;let J=$,Q=Array.isArray(J.recommended)?J.recommended:[],Z=Array.isArray(J.free)?J.free:[],W=Q.map(gG).filter((f)=>f!==null),j=Z.map(gG).filter((f)=>f!==null);if(W.length===0&&j.length===0)return null;return{recommended:W,free:j}}function PE($){let J=$.baseUrl?.trim();if(J)return J;let Q=OE().apiBaseUrl;try{return($.providerSettingsManager??new _1).getProviderSettings("cline")?.baseUrl?.trim()||Q}catch{return Q}}async function NE($,J,Q){let Z=new AbortController,W=setTimeout(()=>Z.abort(),Q);try{return await $(J,{signal:Z.signal})}finally{clearTimeout(W)}}async function _j($={}){try{let J=PE($),Q=$.fetchImpl??fetch,Z=await NE(Q,`${J}/api/v1/ai/cline/recommended-models`,$.timeoutMs??TE);if(!Z.ok)throw Error(`HTTP ${Z.status}`);let W=await Z.json(),j=qE(W);if(j)return j}catch{}return ME(iQ)}var vG={};w(vG,{loadLlmsConfigFromFile:()=>Tj,defineLlmsConfig:()=>Oj});import{readFile as wE}from"node:fs/promises";import SE from"node:path";function Oj($){return $}async function Tj($){let J=SE.resolve($),Q=await wE(J,"utf8"),Z;try{Z=JSON.parse(Q)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse JSON config at "${J}": ${j}`)}return CE(Z,J)}function CE($,J){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${J}": expected an object.`);let Z=$.providers;if(!Array.isArray(Z))throw Error(`Invalid llms config in "${J}": "providers" must be an array.`);if(!Z.length)throw Error(`Invalid llms config in "${J}": "providers" cannot be empty.`);return $}var rG={};w(rG,{createLlmsSdk:()=>qj,DefaultLlmsSdk:()=>NJ});import{BUILT_IN_PROVIDER_IDS as dG,createHandler as bE,createHandlerAsync as hE,getProviderCollection as kE,hasProvider as lG,registerAsyncHandler as IE,registerHandler as xE,registerModel as gE,registerProvider as pG}from"@cline/llms";function cG($){return $?{...$}:{}}function yE($,J){if($)return $;if(!J)return;let Q=globalThis.process;if(!Q?.env)return;return Q.env[J]}function EE($,J){if(!J.length)throw Error(`Provider "${$}" must include at least one model.`)}function uG($){let J=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:J,defaultModel:$.collection.provider.defaultModelId,modelCount:J.length}}class Mj{providers=new Map;register($){EE($.id,$.models);let J=$.defaultModel??$.models[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(J))throw Error(`Default model "${J}" is not included in configured models for "${$.id}".`);let Q=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...Q?.models??[],...$.models]),defaultModel:J,defaults:{...Q?.defaults??{},...cG($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:yE($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...cG($.settings)}})}registerModel($,J){let Q=this.providers.get($);if(!Q){this.providers.set($,{id:$,models:new Set([J]),defaultModel:J,defaults:{}});return}Q.models.add(J)}createHandlerConfig($){let J=this.require($.providerId),Q=$.modelId??J.defaultModel;if(!J.models.has(Q))throw Error(`Model "${Q}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:Q,...J.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($,J){return this.providers.get($)?.models.has(J)??!1}require($){let J=this.providers.get($);if(!J)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return J}}class NJ{configuredProviders=new Mj;constructor($){this.applyConfig($)}createHandler($){return bE(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return hE(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(pG($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)xE($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)IE($.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 J=$.exposeModels??Object.keys($.models),Q=$.defaultModel??J[0];if(!Q)throw Error(`Provider "${$.id}" must define a default model.`);pG({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:Q,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:J,defaultModel:Q,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){gE($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...dG]}async getBuiltInProviders(){return(await Promise.all(dG.map((J)=>kE(J)))).filter((J)=>J!==void 0).map((J)=>uG({collection:J}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,J){return this.configuredProviders.hasModel($,J)}applyConfig($){for(let J of $.providers)this.configuredProviders.registerSelectionConfig(J);for(let J of $.models??[])this.registerModel(J);for(let J of $.customProviders??[])this.registerProvider(J);for(let J of this.configuredProviders.list()){let Q=lG(J.id),Z=this.configuredProviders.createHandlerConfig({providerId:J.id,modelId:J.defaultModel}).routingProviderId,W=typeof Z==="string"&&lG(Z);if(!Q&&!W)throw Error(`Provider "${J.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function qj($){return new NJ($)}X3();async function mE(){return Promise.resolve().then(() => (RQ(),pK))}function Bb(){return new Date().toISOString()}var Ab="cline",Kb="cline-pass";function Gb($){if(sG($)!=="providers.json")return;let J=Nj($);if(sG(J)!=="settings")return;return Nj(J)}class _1{filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Hb(),this.dataDir=$.dataDir??Gb(this.filePath),this.dataDir||!$.filePath)PJ({providerSettingsManager:this,dataDir:this.dataDir});if(_G(this),EQ(this.read()),Pj(this.filePath))try{aG(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!Pj(this.filePath))return L$();try{let $=Yb(this.filePath,"utf8"),J=JSON.parse($),Q=L8.safeParse(J);if(Q.success)return EQ(Q.data),Q.data}catch{}return L$()}write($){let J=L8.parse($),Q=Nj(this.filePath);if(!Pj(Q))Xb(Q,{recursive:!0,mode:448});Vb(this.filePath,`${JSON.stringify(J,null,2)}
728
+ `,"utf8");try{aG(this.filePath,384)}catch{}EQ(J)}saveProviderSettings($,J={}){let Q=z8.parse($),Z=this.read(),W=Q.provider,j=J.setLastUsed!==!1,f=Z.providers[W],X=J.tokenSource??f?.tokenSource??"manual",Y={...Z,providers:{...Z.providers,[W]:{settings:Q,updatedAt:Bb(),tokenSource:X}},lastUsedProvider:j?W:Z.lastUsedProvider};return this.write(Y),Y}resolveProviderSettings($,J){let Q=$.providers[J]?.settings,W=Z0(J)?.storageProviderId;if(!W||W===J)return Q;let j=$.providers[W]?.settings;if(!j)return Q;return z8.parse({...j.auth?{auth:j.auth}:{},...j.apiKey?{apiKey:j.apiKey}:{},...j.baseUrl?{baseUrl:j.baseUrl}:{},...Q??{},provider:J})}getProviderSettings($){let J=this.read();return this.resolveProviderSettings(J,$)}resolveLastUsedProviderId($,J){let Q=$.lastUsedProvider;if(Q===Kb&&J.isClinePassEnabled===!1)return Ab;return Q}getLastUsedProviderSettings($={}){let J=this.read(),Q=this.resolveLastUsedProviderId(J,$);if(!Q)return;return this.resolveProviderSettings(J,Q)}getProviderConfig($,J){let Q=this.getProviderSettings($);if(!Q)return;return d0(Q,J)}getLastUsedProviderConfig($={}){let J=this.getLastUsedProviderSettings($);if(!J)return;return d0(J,$)}async refreshCatalog(){try{await U8({})}catch{}}}O0();g8();function Fb($,J){let Q=$?.expiresAt,Z=J?.expiresAt;return $?.accessToken===J?.accessToken&&$?.refreshToken===J?.refreshToken&&$?.accountId===J?.accountId&&Q===Z}class nQ 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 wj{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new _1,this.telemetry=$?.telemetry}async resolveProviderApiKey($){let J=Z0($.providerId);if(!J)return null;return this.resolveWithSingleFlight(J.providerId,J.storageProviderId,$.forceRefresh)}async resolveWithSingleFlight($,J,Q=!1){let Z=this.refreshInFlight.get(J);if(Z)return Z;let W=this.resolveProviderApiKeyInternal($,J,Q).catch((j)=>{throw j}).finally(()=>{this.refreshInFlight.delete(J)});return this.refreshInFlight.set(J,W),W}async resolveProviderApiKeyInternal($,J,Q){let Z=Z0($);if(!Z)return null;let W=this.providerSettingsManager.getProviderSettings(J);if(!W)return null;let j=L4($,W);if(!j)return null;let f=await Z.refresh({settings:W,credentials:j,forceRefresh:Q,telemetry:this.telemetry});if(!f)throw new nQ($);let X=x$({manager:this.providerSettingsManager,providerId:$,settings:W,credentials:f,setLastUsed:!1,save:!1}),Y=!Fb(W.auth,X.auth);if(Y)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{apiKey:Z.getApiKey(X)??f.access,accountId:f.accountId,refreshed:Y}}}import{normalizeUserInput as Db}from"@cline/shared";import{nanoid as Ub}from"nanoid";class oG{list($){return $?e0($):[]}update($,J){if(!$)return{sessionId:J.sessionId,prompts:[],updated:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((Y)=>Y.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:e0($),updated:!1};let W=$.pendingPrompts[Z];if(!W)return{sessionId:J.sessionId,prompts:e0($),updated:!1};let j=J.prompt===void 0?W.prompt:Db(J.prompt).trim();if(!j)throw Error("prompt cannot be empty");let f=J.delivery??W.delivery,X={...W,prompt:j,mode:J.mode??W.mode,delivery:f};return $.pendingPrompts.splice(Z,1),Rb($,X,Z,W.delivery),{sessionId:J.sessionId,prompts:e0($),prompt:aQ(X),updated:!0}}delete($,J){if(!$)return{sessionId:J.sessionId,prompts:[],removed:!1};let Q=J.promptId.trim(),Z=$.pendingPrompts.findIndex((j)=>j.id===Q);if(Z<0)return{sessionId:J.sessionId,prompts:e0($),removed:!1};let[W]=$.pendingPrompts.splice(Z,1);return{sessionId:J.sessionId,prompts:e0($),prompt:W?aQ(W):void 0,removed:!0}}enqueue($,J){let{prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f}=J,X=$.pendingPrompts.findIndex((Y)=>Y.prompt===Q);if(X>=0){let[Y]=$.pendingPrompts.splice(X,1),V={...Y,prompt:Q,mode:Z??Y.mode,userImages:j??Y.userImages,userFiles:f??Y.userFiles};if(W==="steer"||Y.delivery==="steer")$.pendingPrompts.unshift({...V,delivery:"steer"});else $.pendingPrompts.push(V)}else{let Y={id:`pending_${Date.now()}_${Ub(5)}`,prompt:Q,mode:Z,delivery:W,userImages:j,userFiles:f};if(W==="steer")$.pendingPrompts.unshift(Y);else $.pendingPrompts.push(Y)}return e0($)}consumeSteer($){let J=$.pendingPrompts.findIndex((Z)=>Z.delivery==="steer");if(J<0)return{prompts:e0($)};let[Q]=$.pendingPrompts.splice(J,1);return{entry:Q,prompts:e0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:e0($)}}requeueFront($,J){return $.pendingPrompts.unshift(J),e0($)}clear($){return $.pendingPrompts.length=0,[]}}class Sj{deps;service=new oG;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let Q=this.service.update(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}delete($){let J=this.deps.getSession($.sessionId);if(!J||J.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let Q=this.service.delete(J,$);return this.emitPrompts(J),this.scheduleDrain($.sessionId,J),Q}enqueue($,J){let Q=this.deps.getSession($);if(!Q||Q.aborting)return;this.service.enqueue(Q,J),this.emitPrompts(Q),this.scheduleDrain($,Q)}consumeSteer($){let J=this.deps.getSession($);if(!J)return;let{entry:Q}=this.service.consumeSteer(J);if(!Q)return;return this.emitPrompts(J),this.emitSubmitted(J,Q),Q}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:e0($)}})}scheduleDrain($,J){if(J.pendingPrompts.length===0||J.aborting||J.drainingPendingPrompts||!J.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let J=this.deps.getSession($);if(!J)return;if(J.aborting||J.drainingPendingPrompts)return;if(!J.agent.canStartRun())return;let{entry:Q}=this.service.shiftNext(J);if(!Q)return;this.emitPrompts(J),this.emitSubmitted(J,Q),J.drainingPendingPrompts=!0;let Z=!0;try{await this.deps.send({sessionId:$,prompt:Q.prompt,...Q.mode?{mode:Q.mode}:{},userImages:Q.userImages,userFiles:Q.userFiles})}catch{Z=!1,this.service.requeueFront(J,Q),this.emitPrompts(J)}finally{if(J.drainingPendingPrompts=!1,Z&&J.pendingPrompts.length>0&&J.status!=="failed"&&J.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,J){let Q=aQ(J);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:Q.id,prompt:Q.prompt,delivery:Q.delivery,attachmentCount:Q.attachmentCount}})}}function aQ($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function e0($){return $.pendingPrompts.map(aQ)}function Rb($,J,Q,Z){if(J.delivery==="steer")$.pendingPrompts.unshift(J);else if(Z==="steer")$.pendingPrompts.push(J);else $.pendingPrompts.splice(Q,0,J)}O0();class yj{deps;constructor($){this.deps=$}dispatchAgentEvent($,J,Q){let Z=this.deps.getSession($),W={sessionId:$,config:J,liveSession:Z,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},j=f7(Q),f=!!Z&&(!j.agentId||j.agentId===Cj(Z.agent));X7(W,Q,f?{isPrimaryAgentEvent:!0,agentId:Cj(Z.agent),conversationId:Z.agent.getConversationId(),...Z?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,J){let Q=this.deps.getSession($);if(Q){if(pW(Q,J),J.type==="agent_event"){let Z={sessionId:$,config:Q.config,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};X7(Z,J.event,{agentId:J.agentId,teamRole:"teammate",teamAgentId:J.agentId,isPrimaryAgentEvent:!1})}if(J.type==="teammate_spawned"){let Z=g1({agentId:J.teammate.runtimeAgentId??J.agentId,conversationId:J.teammate.conversationId,parentAgentId:J.teammate.parentAgentId,createdByAgentId:Cj(Q.agent),teamId:Q.runtime.teamRuntime?.getTeamId(),teamName:Q.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:J.agentId});if(Z)$$(Q.config.telemetry,{ulid:$,modelId:J.teammate.modelId??Q.config.modelId,provider:Q.config.providerId,...Z})}}if(await rW($,J,this.deps.invokeBackendOptional),Q)iW(Q,$,J,this.deps.emit)}async handlePluginEvent($,J,Q){if(J.name==="plugin_log"){this.handlePluginLog($,J.payload);return}if(J.name==="automation_event"){let Y=this.deps.getSession($)?.config.extensionContext?.automation??Q;if(!Y)return;let V=J.payload&&typeof J.payload==="object"?J.payload:void 0;if(!V)return;await Y.ingestEvent(V);return}if(J.name!=="steer_message"&&J.name!=="queue_message"&&J.name!=="pending_prompt")return;let Z=J.payload&&typeof J.payload==="object"?J.payload:void 0,W=typeof Z?.sessionId==="string"&&Z.sessionId.trim().length>0?Z.sessionId.trim():$,j=typeof Z?.prompt==="string"?Z.prompt.trim():"";if(!j)return;let f=J.name==="steer_message"?"steer":J.name==="queue_message"?"queue":Z?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(W,{prompt:j,delivery:f})}handlePluginLog($,J,Q){let Z=this.deps.getSession($),W=Q??Z?.config.extensionContext?.logger??Z?.config.logger;if(!W||!J||typeof J!=="object")return;let j=J,f=typeof j.message==="string"?j.message:"";if(!f)return;let X=j.metadata&&typeof j.metadata==="object"?{...j.metadata}:{};if(X.sessionId??=$,typeof j.pluginName==="string"&&j.pluginName)X.pluginName=j.pluginName;if(j.level==="debug"){W.debug(f,X);return}if(j.level==="error"){if(W.error)W.error(f,X);else W.log(f,{...X,severity:"error"});return}W.log(f,X)}}function Cj($){return $.getAgentId()}function Ej($){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:G$($.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 bj($,J){let Q=$[J];return typeof Q==="function"?Q:null}async function tG($,J,...Q){let Z=bj($,J);if(!Z)throw Error(`session service method not available: ${J}`);return Promise.resolve(Z.apply($,Q))}async function eG($,J,...Q){let Z=bj($,J);if(!Z)return;await Promise.resolve(Z.apply($,Q))}async function $F($,J,...Q){let Z=bj($,J);if(!Z)return;return await Promise.resolve(Z.apply($,Q))}W1();O0();function hj($,J,Q){return{onSubAgentEvent:(Z)=>$.onAgentEvent(Q,J,Z),onSubAgentStart:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime;$.subAgentStarts.set(Z.subAgentId,{startedAt:Date.now(),rootSessionId:Q});let j=g1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId});if(j)$$(J.telemetry,{ulid:Q,modelId:J.modelId,provider:J.providerId,...j});B4(J.telemetry,{event:"started",ulid:Q,durationMs:0,parentId:Z.parentAgentId,agentId:Z.subAgentId,...j}),$.invokeBackendOptional("handleSubAgentStart",Q,Z)},onSubAgentEnd:(Z)=>{let W=$.getSession(Q)?.runtime.teamRuntime,j=$.subAgentStarts.get(Z.subAgentId),f=j?Date.now()-j.startedAt:0,X=Z.result?.text?Z.result.text.split(`
729
+ `).length:0;B4(J.telemetry,{event:"ended",ulid:Q,durationMs:f,outputLines:X,errorMessage:Z.error?String(Z.error):void 0,agentId:Z.subAgentId,parentId:Z.parentAgentId,...g1({agentId:Z.subAgentId,conversationId:Z.conversationId,parentAgentId:Z.parentAgentId,teamId:W?.getTeamId(),teamName:W?.getTeamName(),createdByAgentId:Z.parentAgentId})}),$.subAgentStarts.delete(Z.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",Q,Z)}}}function kj($,J,Q,Z){let W=hj($,J,Q);return A$({configProvider:{getRuntimeConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:J.providerId,modelId:J.modelId,cwd:J.cwd,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking,maxIterations:J.maxIterations,hooks:J.hooks,extensions:J.extensions,logger:J.logger,telemetry:J.telemetry},getConnectionConfig:()=>$.getSession(Q)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:J.providerId,modelId:J.modelId,apiKey:J.apiKey,baseUrl:J.baseUrl,headers:J.headers,providerConfig:J.providerConfig,knownModels:J.knownModels,thinking:J.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let f=J.enableTools?n$({cwd:J.cwd,...c0[h1({mode:J.mode})],executors:Z}):[];if(J.enableSpawnAgent)f.push(kj($,J,Q,Z));return I1(f)},...W})}import{readFile as zb,stat as Lb}from"node:fs/promises";var _b=20480000;async function JF($){let J=await Lb($);if(!J.isFile())throw Error("Path is not a file");if(J.size>_b)throw Error("File is too large to read into context.");let Q=await zb($,"utf8");if(Q.includes("\x00"))throw Error("Cannot read binary file into context.");return Q}var QF=5000;function wJ($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function Sb($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$,Q=wJ(J.inputTokens),Z=wJ(J.outputTokens),W=wJ(J.cacheReadTokens),j=wJ(J.cacheWriteTokens),f=wJ(J.totalCost);if(Q===void 0||Z===void 0||W===void 0||j===void 0||f===void 0)return;return{inputTokens:Q,outputTokens:Z,cacheReadTokens:W,cacheWriteTokens:j,totalCost:f}}function Cb($,J){return{inputTokens:Math.max($.inputTokens,J.inputTokens),outputTokens:Math.max($.outputTokens,J.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,J.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,J.cacheWriteTokens),totalCost:Math.max($.totalCost,J.totalCost)}}class L1{runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new o6;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new y$;constructor($){let J=Tb();if(J)wb(J);let Q=b0($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new W4,this.createAgentInstance=$.createAgent??((Z)=>new V$(Z)),this.defaultCapabilities=L0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new _1,this.oauthTokenManager=$.oauthTokenManager??new wj({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(Q),this.defaultFetch=$.fetch,this.pendingPromptsController=new Sj({getSession:(Z)=>this.sessions.get(Z),emit:(Z)=>this.emit(Z),send:(Z)=>this.runTurn(Z)}),this.pendingPrompts={list:async(Z)=>this.pendingPromptsController.list(Z.sessionId),update:async(Z)=>this.pendingPromptsController.update(Z),delete:async(Z)=>this.pendingPromptsController.delete(Z)},this.eventBridge=new yj({getSession:(Z)=>this.sessions.get(Z),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Z)=>this.emit(Z),persistMessages:(Z,W,j)=>{this.invoke("persistSessionMessages",Z,W,j)},enqueuePendingPrompt:(Z,W)=>this.pendingPromptsController.enqueue(Z,W),invokeBackendOptional:(Z,...W)=>this.invokeOptional(Z,...W)})}async applyInitialOAuthCredentials($){if($.config.apiKey?.trim())return $;let J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId});if(!J?.apiKey)return $;return{...$,config:{...$.config,apiKey:J.apiKey}}}async startSession($){let J=$.source??U0.CLI,Q=e(),Z=$.config.sessionId?.trim()??"",W=Z||qb(),j=await this.applyInitialOAuthCredentials($),f=j.initialMessages??[],X=f.length>0?f8(f):G0(),Y=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!Y)throw Error("session service method not available: ensureSessionsDir");let V=Ij(Y,W),H=Ij(V,`${W}.messages.json`),B=Ij(V,`${W}.json`),A=G$($.config),K=S0.parse({version:1,session_id:W,source:J,pid:process.pid,started_at:Q,status:"running",interactive:$.interactive===!0,provider:j.config.providerId,model:j.config.modelId,cwd:j.config.cwd,workspace_root:A,team_name:j.config.teamName,enable_tools:j.config.enableTools,enable_spawn:j.config.enableSpawnAgent,enable_teams:j.config.enableAgentTeams,prompt:j.prompt?.trim()||void 0,messages_path:H}),G;if(Z.length>0&&f.length>0&&!j.prompt?.trim()){let C=await this.invokeOptionalValue("readSessionManifest",W);if(C)K=C,G={manifestPath:B,messagesPath:C.messages_path||H,manifest:C}}let D=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:V,rootMessagesPath:G?.messagesPath??H,manifest:K});this.usageBySession.set(W,X),this.aggregateUsageBySession.set(W,D);let U=L0(this.defaultCapabilities,$.capabilities),F=U?.toolExecutors??this.toolExecutors,O=$.localRuntime,T=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z,P={getSession:(C)=>this.sessions.get(C),subAgentStarts:this.subAgentStarts,onAgentEvent:(C,F0,f0)=>this.eventBridge.dispatchAgentEvent(C,F0,f0),invokeBackendOptional:(C,...F0)=>this.invokeOptional(C,...F0)};z=await xV({input:j,localRuntime:$.localRuntime,sessionId:W,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:U,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(C)=>{if(C.name==="plugin_log"){this.eventBridge.handlePluginLog(W,C.payload,T);return}this.eventBridge.handlePluginEvent(W,C,L)},onTeamEvent:(C)=>{this.eventBridge.handleTeamEvent(W,C),z.config.onTeamEvent?.(C)},createSpawnTool:()=>kj(P,z.config,W,F),createSubAgentLifecycleCallbacks:(C)=>hj(P,C,W),readSessionMetadata:async()=>(await this.getSession(W))?.metadata,writeSessionMetadata:async(C)=>{await this.persistSessionMetadata(W,()=>C)}});let S=await this.runtimeBuilder.build(z.runtimeBuilderInput),b=z.config,u=z.providerConfig;if(S.teamRuntime&&!b.teamName?.trim())b.teamName=S.teamRuntime.getTeamName();let o=[...S.tools,...b.extraTools??[]],J0=S.extensions??z.extensions,t={sessionId:W,providerId:u.providerId,modelId:u.modelId,apiKey:u.apiKey,baseUrl:u.baseUrl,headers:u.headers,knownModels:u.knownModels,providerConfig:u,thinking:b.thinking,reasoningEffort:b.reasoningEffort??u.reasoningEffort,systemPrompt:b.systemPrompt,maxIterations:b.maxIterations,execution:b.execution,prepareTurn:P4(b),tools:o,hooks:z.hooks,extensions:J0,hookErrorMode:b.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:JF,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval?async(C)=>{let F0=z.requestToolApproval,f0=this.sessions.get(W);if(f0)await this.markTurnPending(f0);try{if(!F0)return{approved:!1,reason:"Tool approval callback is not configured."};return await F0(C)}finally{let w0=this.sessions.get(W);if(w0?.status==="pending")await this.markTurnRunning(w0)}}:void 0,telemetry:b.telemetry,onConsecutiveMistakeLimitReached:b.onConsecutiveMistakeLimitReached,completionPolicy:S.completionPolicy,consumePendingUserMessage:()=>{let C=this.pendingPromptsController.consumeSteer(W);return C?HJ(C.prompt,C.mode??b.mode):void 0},logger:S.logger??b.logger,extensionContext:b.extensionContext,onEvent:(C)=>this.eventBridge.dispatchAgentEvent(W,b,C)};t.hooks={...t.hooks,onEvent:async(C)=>{if(await z.hooks?.onEvent?.(C),C.type!=="assistant-message")return;let F0=this.sessions.get(W);if(!F0)return;let f0=F0.agent.getMessages();try{await this.invoke("persistSessionMessages",W,f0,b.systemPrompt)}catch(w0){b.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:W,error:w0}),h2(b.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:w0,severity:"warn",handled:!0,context:{sessionId:W,providerId:b.providerId,modelId:b.modelId}})}}};let $1=this.createAgentInstance(t);if(t.onEvent)$1.subscribeEvents(t.onEvent);S.registerLeadAgent?.($1);let b$=g1({agentId:$1.getAgentId(),conversationId:$1.getConversationId(),teamId:S.teamRuntime?.getTeamId(),teamName:S.teamRuntime?.getTeamName(),teamRole:S.teamRuntime?"lead":void 0});if(mV(b,W,Z.length>0,A,b$),b$)$$(b.telemetry,{ulid:W,modelId:b.modelId,provider:b.providerId,...b$});if(S.teamRuntime)pJ(b.telemetry,{ulid:W,teamId:S.teamRuntime.getTeamId(),teamName:S.teamRuntime.getTeamName(),leadAgentId:$1.getAgentId(),restoredFromPersistence:S.teamRestoredFromPersistence===!0});let n={sessionId:W,config:b,sessionMetadata:j.sessionMetadata,...G?{artifacts:G}:{},source:J,startedAt:G?.manifest.started_at??Q,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??Q,pendingPrompt:K.prompt,runtime:S,agent:$1,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:f,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(W,n),this.emitStatus(W,"running"),f.length>0&&!G){if(await this.ensureSessionPersisted(n),await this.invoke("persistSessionMessages",n.sessionId,f,n.config.systemPrompt),!j.prompt?.trim())await this.updateStatus(n,"completed",0)}let O1;try{if(j.prompt?.trim())if(O1=await this.executeTurn(n,{prompt:j.prompt,userImages:j.userImages,userFiles:j.userFiles}),!n.interactive)await this.finalizeSingleRun(n,O1.finishReason);else await this.completeInteractiveTurn(n,O1.finishReason)}catch(C){if(n.interactive&&n.aborting)O1=await this.completeAbortedInteractiveTurn(n);else throw h2(n.config.telemetry,{component:"core",operation:"session.start",error:C,severity:"error",handled:!1,context:{sessionId:n.sessionId,providerId:n.config.providerId,modelId:n.config.modelId}}),await this.failSession(n),C}return{sessionId:W,manifest:K,manifestPath:B,messagesPath:H,result:O1}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(J)=>this.getSession(J),readMessages:(J)=>this.readSessionMessages(J),buildStartInput:(J,Q)=>{let Z=J.restoredCheckpointMetadata?{...Q.sessionMetadata??{},checkpoint:J.restoredCheckpointMetadata}:Q.sessionMetadata;return{...Q,...Z?{sessionMetadata:Z}:{},initialMessages:J.initialMessages}},startSession:(J)=>this.startSession(J),getStartedSessionId:(J)=>J.sessionId,readRestoredSession:(J)=>this.getSession(J)})}async runTurn($){let J=this.getSessionOrThrow($.sessionId),Q=J.agent.canStartRun(),Z=$.delivery??(J.interactive&&!Q?"queue":void 0);if(J.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Z??"immediate"}}),Z==="queue"||Z==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Z,userImages:$.userImages,userFiles:$.userFiles});return}try{let W=await this.executeTurn(J,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!J.interactive)await this.finalizeSingleRun(J,W.finishReason);else await this.completeInteractiveTurn(J,W.finishReason);if(W.finishReason==="error"||W.finishReason==="aborted")return W;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),W}catch(W){if(J.interactive&&J.aborting)return await this.completeAbortedInteractiveTurn(J);throw h2(J.config.telemetry,{component:"core",operation:"session.submit",error:W,severity:"error",handled:!1,context:{sessionId:J.sessionId,providerId:J.config.providerId,modelId:J.config.modelId}}),await this.failSession(J),W}}async getAccumulatedUsage($){let J=zW(this.usageBySession.get($)),Q=zW(this.aggregateUsageBySession.get($));return J||Q?{usage:J,aggregateUsage:Q}:void 0}async abort($,J){let Q=this.sessions.get($);if(!Q)return;Q.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),Q.aborting=!0,this.pendingPromptsController.clearAborted(Q),Q.agent.abort(J)}async stopSession($){let J=this.sessions.get($);if(!J)return;if(J.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),J.interactive&&!j0(J.status)){await this.releaseSessionRuntime(J,"session_stop");return}if(J.interactive&&J.agent.canStartRun()){await this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:"session_stop",endReason:"stopped"});return}J.aborting=!0,J.agent.abort(Error("session_stop")),await this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let J=[...this.sessions.values()];if(J.length===0)return;await Promise.allSettled(J.map((Q)=>Q.interactive&&!j0(Q.status)?this.releaseSessionRuntime(Q,$):Q.interactive&&Q.agent.canStartRun()?this.shutdownSession(Q,{status:this.resolveInteractiveStopStatus(Q),exitCode:this.resolveInteractiveStopExitCode(Q),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(Q,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let J=this.sessions.get($);if(J)return Ej(J);let Q=$.trim();if(!Q)return;let Z=await this.getRow(Q);if(Z)return $6(Z);let W=await this.readManifest(Q);return W?m9(W):void 0}async listSessions($=200){let Q=(await this.listRows($)).map($6),Z=new Set(Q.map((W)=>W.sessionId));for(let W of this.sessions.values()){if(Z.has(W.sessionId))continue;Q.unshift(Ej(W))}return Q.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let J=await this.invoke("deleteSession",$);if(J.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return J.deleted}async updateSession($,J){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:J.prompt,metadata:J.metadata,title:J.title}))?.updated===!0}}async readSessionMessages($){let J=$.trim();if(!J)return[];let Q=await this.getRow(J);if(Q?.messagesPath)return q$(Q.messagesPath);let Z=await this.readManifest(J);return q$(Z?.messages_path)}async dispatchHookEvent($){await YB($,{queueSpawnRequest:(J)=>this.invokeOptional("queueSpawnRequest",J),upsertSubagentSessionFromHook:(J)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",J),appendSubagentHookAudit:(J,Q)=>this.invokeOptional("appendSubagentHookAudit",J,Q),applySubagentStatus:(J,Q)=>this.invokeOptional("applySubagentStatus",J,Q)})}subscribe($,J){return this.events.subscribe($,J)}async updateSessionModel($,J){let Q=this.getSessionOrThrow($);Q.config.modelId=J,Q.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:J}),Q.agent.updateConnection({modelId:J})}handlePluginEvent($,J,Q){return this.eventBridge.handlePluginEvent($,J,Q)}async executeTurn($,J){let Q=await this.prepareTurnInput($,J),Z=Q.prompt.trim();if(!Z)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Z;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let W=await this.executeAgentTurn($,Z,Q.userImages,Q.userFiles);while(nW($,W.finishReason)){let j=await aW($);if(j.length===0)break;let f=sW($,j);W=await this.executeAgentTurn($,f)}return W}async completeInteractiveTurn($,J){if(VJ($))return;$.lastInteractiveTurnFinishReason=J,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let J=$.lastInteractiveTurnFinishReason;if(!J)return"cancelled";switch(J){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return J}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let J=new Date,Q=$.agent.getMessages(),Z=G0();return $.persistedMessages=Q,$.started=$.started||Q.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Z}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Z,messages:Q,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:J,endedAt:J,durationMs:0}}async executeAgentTurn($,J,Q,Z){let W=$.started||$.agent.getMessages().length>0,j=$.persistedMessages??$.agent.getMessages(),f=this.usageBySession.get($.sessionId)??G0(),X=this.aggregateUsageBySession.get($.sessionId)??f;$.turnUsageBaseline=f,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=G0(),$.turnUsageByAgent=new Map,gJ($.config.telemetry,$.sessionId,$.config.mode),g2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let Y=W?()=>$.agent.continue(J,Q,Z):()=>$.agent.run(J,Q,Z),V=await this.runWithAuthRetry($,Y,j);$.started=!0;let H=y5(V.messages,V,j);$.persistedMessages=H;let B=Q6($.turnUsageByAgent?.values()??[]),A=V0(f,V.usage),K=V0(V0(G0(),V.usage),B),G=V0(X,K);return this.usageBySession.set($.sessionId,A),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:A.totalCost,aggregatedAgentsCost:G.totalCost,usage:A,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,H,$.config.systemPrompt),this.observeTaskCompletionTool($,V),V}catch(Y){throw h2($.config.telemetry,{component:"core",operation:"session.turn",error:Y,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),Y}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,J){if($.submitAndExitObserved)return;if(!J.toolCalls.some((Z)=>Z.name===K0.SUBMIT_AND_EXIT&&Z.error===void 0))return;$.submitAndExitObserved=!0,V4($.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($,J){let Q=G$($.config),Z=Nb(J.prompt).trim();if(!Z)return{prompt:"",userImages:J.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles)};let W=await a2(Z,Q);vV($.config.telemetry,W);let j=HJ(W.prompt,J.mode??$.config.mode),f=this.resolveAbsoluteFilePaths($.config.cwd,J.userFiles),X=this.resolveAbsoluteFilePaths(Q,W.matchedFiles),Y=Array.from(new Set([...f,...X]));return{prompt:j,userImages:J.userImages,userFiles:Y.length>0?Y:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let J=G$($.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:J,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($,J){let Q=this.sessions.get($),Z=await this.invokeOptionalValue("readSessionManifest",$)??Q?.artifacts?.manifest,W=J(Z?.metadata);if(!Q?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:W}))?.updated===!1)return;Q.sessionMetadata=W,Q.artifacts.manifest.metadata=W}async finalizeSingleRun($,J){if(VJ($))return;let Q=J==="aborted"||$.aborting,Z=J==="error";await this.shutdownSession($,{status:Q?"cancelled":Z?"failed":"completed",exitCode:Z?1:0,shutdownReason:Z?"session_error":"session_complete",endReason:J})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,J){if(J.status==="completed"&&!$.submitAndExitObserved)V4($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});QQ($);let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),h2($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,status:J.status,shutdownReason:J.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,J.status,J.exitCode)}catch(W){Z("update_status",W)}try{await $.agent.shutdown(J.shutdownReason)}catch(W){Z("agent_shutdown",W)}}try{await Promise.resolve($.runtime.shutdown(J.shutdownReason))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:J.endReason,ts:Date.now()}}),Q.length>0&&J.status==="failed")throw Q[0]}async releaseSessionRuntime($,J){let Q=[],Z=(W,j)=>{Q.push(j),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:W,error:j,severity:"warn"}),h2($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:j,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:W,reason:J,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(J)}catch(W){Z("agent_shutdown",W)}try{await Promise.resolve($.runtime.shutdown(J))}catch(W){Z("runtime_shutdown",W)}try{await $.pluginSandboxShutdown?.()}catch(W){Z("plugin_sandbox_shutdown",W)}if(this.sessions.delete($.sessionId),Q.length>0)throw Q[0]}async updateStatus($,J,Q){if(!$.artifacts)return;let Z=await this.invoke("updateSessionStatus",$.sessionId,J,Q);if(!Z.updated)return;let W=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(W.status=J,j0(J))delete W.ended_at,W.exit_code=null;else W.ended_at=Z.endedAt??e(),W.exit_code=typeof Q==="number"?Q:null;$.artifacts.manifest=W,$.status=J,$.updatedAt=Z.endedAt??e(),$.endedAt=j0(J)?null:W.ended_at,$.exitCode=W.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,W),this.emitStatus($.sessionId,J)}async runWithAuthRetry($,J,Q){try{return await J()}catch(Z){if(!I$($.config.providerId)||!Pb(Z))throw Z;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(Q),J()}}async syncOAuthCredentials($,J){let Q=null;try{Q=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:J?.forceRefresh})}catch(Z){if(Z instanceof nQ)throw Error(`${Z.providerId} requires re-authentication.`);throw Z}if(!Q?.apiKey||$.config.apiKey===Q.apiKey)return;$.config.apiKey=Q.apiKey,$.agent.updateConnection({apiKey:Q.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:Q.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:Q.apiKey})}getSessionOrThrow($){let J=this.sessions.get($);if(!J){let Q=new u1($);throw h2(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:Q,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),Q}return J}resolveAbsoluteFilePaths($,J){if(!J||J.length===0)return[];let Q=J.map((Z)=>Z.trim()).filter((Z)=>Z.length>0).map((Z)=>Mb(Z)?Z:xj($,Z));return Array.from(new Set(Q))}getSessionAgentTelemetryIdentity($){return g1({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let J=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),Q=V0($.initialUsage,J);return this.withPersistedAggregateUsageFloor(Q,$.manifest)}async summarizePersistedTeammateUsage($,J,Q){let Z=xj(J),W=`${Q}.messages.json`,j;try{j=Ob($)}catch{return G0()}let f=G0();for(let X of j){if(!X.endsWith(".messages.json"))continue;if(X===W)continue;let Y=xj($,X);if(Y===Z)continue;let V=await q$(Y);if(V.length===0)continue;f=V0(f,f8(V))}return f}withPersistedAggregateUsageFloor($,J){let Q=Sb(J.metadata?.aggregateUsage);if(Q)return Cb($,Q);let Z=J.metadata?.aggregatedAgentsCost;if(typeof Z!=="number"||!Number.isFinite(Z)||Z<=$.totalCost)return $;return{...$,totalCost:Z}}emitStatus($,J){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:J}})}async emitSessionSnapshot($){let J=await this.getSession($);if(!J)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:F1({session:J,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($)),QF))}async getRow($){let J=$.trim();if(!J)return;return(await this.listRows(QF)).find((Z)=>Z.sessionId===J)}async readManifest($){let J=$.trim();if(!J)return;return await this.invokeOptionalValue("readSessionManifest",J)}invoke($,...J){return tG(this.sessionService,$,...J)}invokeOptional($,...J){return eG(this.sessionService,$,...J)}invokeOptionalValue($,...J){return $F(this.sessionService,$,...J)}}function Eb($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((J)=>({name:J.name,input:J.input,output:J.output,error:J.error,durationMs:J.durationMs}))}}function bb($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function UQ($={}){let J=new L1({sessionService:new z1(new U1),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(Q){let Z=(Q.cwd?.trim()||Q.workspaceRoot).trim(),W=await J.startSession({source:Q.source?.trim()||U0.CLI,interactive:!1,config:{providerId:yb(Q.provider),modelId:Q.model,apiKey:Q.apiKey?.trim()||void 0,cwd:Z,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:bb(Q),maxIterations:Q.maxIterations,enableTools:Q.enableTools!==!1,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},toolPolicies:Q.toolPolicies??{"*":{autoApprove:Q.autoApproveTools!==!1}},localRuntime:{configExtensions:Q.configExtensions}});return{sessionId:W.sessionId,startResult:{sessionId:W.sessionId,manifestPath:W.manifestPath,messagesPath:W.messagesPath}}},async sendSession(Q,Z){let W=await J.runTurn({sessionId:Q,prompt:Z.prompt,userImages:Z.attachments?.userImages,userFiles:Z.attachments?.userFiles?.map((j)=>j.content)});if(!W)throw Error("local hub schedule runtime returned no turn result");return{result:Eb(W)}},async abortSession(Q){return await J.abort(Q,Error("hub schedule abort")),{applied:!0}},async stopSession(Q){return await J.stopSession(Q),{applied:!0}}}}kb(process.env.CLINE_VCR);function xb($){let J=process.cwd(),Q,Z,W;for(let j=0;j<$.length;j+=1){let f=$[j],X=$[j+1];if(f==="--cwd"&&X){J=X,j+=1;continue}if(f==="--host"&&X){Q=X,j+=1;continue}if(f==="--port"&&X){let Y=Number(X);if(Number.isFinite(Y))Z=Y;j+=1;continue}if(f==="--pathname"&&X)W=X,j+=1}return{cwd:J,host:Q,port:Z,pathname:W}}async function gb(){let $=xb(process.argv.slice(2));process.chdir($.cwd);let J=i0({host:$.host,port:$.port,pathname:$.pathname}),Q=await C2({host:J.host,port:J.port,pathname:J.pathname,owner:Ib()==="production"?n0():E0(),runtimeHandlers:UQ(),cronOptions:{workspaceRoot:$.cwd}}),Z=async()=>{await Q.close(),process.exit(0)},W=!1,j=(f,X)=>{if(W)return;W=!0;let Y=X instanceof Error?X.stack||X.message:String(X);process.stderr.write(`[hub-daemon] ${f}: ${Y}
730
730
  `),Q.close().catch((V)=>{let H=V instanceof Error?V.stack||V.message:String(V);process.stderr.write(`[hub-daemon] shutdown after ${f} failed: ${H}
731
731
  `)}).finally(()=>{process.exit(1)})};process.on("SIGINT",()=>{Z()}),process.on("SIGTERM",()=>{Z()}),process.on("uncaughtException",(f)=>{j("uncaughtException",f)}),process.on("unhandledRejection",(f)=>{if(f instanceof hb){process.stderr.write(`[hub-daemon] ignored agent runtime abort rejection: ${f.message}
732
732
  `);return}j("unhandledRejection",f)}),await new Promise(()=>{})}gb().catch(($)=>{let J=$ instanceof Error?$.stack||$.message:String($);process.stderr.write(`[hub-daemon] fatal: ${J}