@cline/core 0.0.41 → 0.0.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,8 +1,8 @@
1
- import{createRequire as SY}from"node:module";var MY=Object.defineProperty;var qY=($)=>$;function wY($,f){this[$]=qY.bind(null,f)}var t4=($,f)=>{for(var J in f)MY($,J,{get:f[J],enumerable:!0,configurable:!0,set:wY.bind(f,J)})};var p$=($,f)=>()=>($&&(f=$($=0)),f);var O7=SY(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as EY}from"@cline/shared";function d($,f,J){$?.capture({event:f,properties:J})}function M2($){if(!$)return;return $.substring(0,hY)}function bY($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function kY($){return typeof $==="string"?$:$.message}function N7($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function IY($){d($,g.CLIENT.EXTENSION_ACTIVATED)}function $6($,f){let J=[...f.vcs_types],Q={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:N7(J,new Set(["git"])),has_mercurial:N7(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)Q.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)Q.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)Q.is_remote_workspace=f.is_remote_workspace;d($,g.WORKSPACE.INITIALIZED,Q)}function f6($,f,J){d($,g.WORKSPACE.INIT_ERROR,{error_type:bY(f),error_message:M2(kY(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function xY($,f){d($,g.WORKSPACE.PATH_RESOLVED,{...f})}function G$($,f){d($,g.USER.AUTH_STARTED,{provider:f})}function P$($,f){d($,g.USER.AUTH_SUCCEEDED,{provider:f})}function F$($,f,J){d($,g.USER.AUTH_FAILED,{provider:f,errorMessage:M2(J)})}function r$($,f,J){d($,g.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function T7($,f){$?.captureRequired(g.USER.TELEMETRY_OPT_OUT,f)}function D$($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function J6($,f){d($,g.TASK.CREATED,f)}function Q6($,f){d($,g.TASK.RESTARTED,f)}function q2($,f){d($,g.TASK.COMPLETED,f)}function Hf($,f){d($,g.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function Z6($,f){d($,g.TASK.TOKEN_USAGE,f)}function W6($,f,J){d($,g.TASK.MODE_SWITCH,{ulid:f,mode:J})}function j6($,f){d($,g.TASK.TOOL_USED,f)}function X6($,f){d($,g.TASK.SKILL_USED,f)}function H6($,f){d($,g.TASK.DIFF_EDIT_FAILED,f)}function w2($,f){d($,g.TASK.PROVIDER_API_ERROR,{...f,errorMessage:M2(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function Y6($,f,J){d($,g.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function V6($,f,J,Q){d($,g.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:M2(Q),timestamp:new Date().toISOString()})}function A6($,f,J,Q,Z){d($,g.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function i$($,f){d($,g.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function B6($,f){d($,g.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function S2($,f){d($,f.event==="ended"?g.TASK.SUBAGENT_COMPLETED:g.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function K6($,f,J,Q){d($,g.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}var hY=500,g;var R0=p$(()=>{g={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",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"},HOOKS:{DISCOVERY_COMPLETED:"hooks.discovery_completed"},WORKSPACE:{INITIALIZED:"workspace.initialized",INIT_ERROR:"workspace.init_error",PATH_RESOLVED:"workspace.path_resolved"},SDK:{ERROR:EY}}});var LZ={};t4(LZ,{normalizeUserMessage:()=>XK,buildInitialUserContent:()=>jK});async function jK($,f,J,Q){let Z=HK(f),W=await VK(J,Q);if(Z.length===0&&!W)return $;let j=[{type:"text",text:$},...Z];if(W)j.push(...W);return j}function XK($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let Q of f)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
2
- `)}function HK($){if(!$||$.length===0)return[];let f=[];for(let J of $){let Q=YK(J);if(Q)f.push(Q)}return f}function YK($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let Q=J[1],Z=J[2];if(!Q||!Z)return;return{type:"image",mediaType:Q,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function VK($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let X=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${X}`}}}));if(Q.length===0)return;return Q}var V3={};t4(V3,{updateMcpServerOAuthState:()=>Sf,setMcpServerDisabled:()=>qf,resolveMcpServerRegistrations:()=>T$,resolveDefaultMcpSettingsPath:()=>w0,registerMcpServersFromSettingsFile:()=>Cf,normalizeMcpServerOAuthState:()=>c1,loadMcpSettingsFile:()=>Mf,listMcpServerOAuthStatuses:()=>wJ,hasMcpSettingsFile:()=>Z1,getMcpServerOAuthState:()=>wf});import{existsSync as oK,mkdirSync as Z3,readFileSync as MJ,writeFileSync as W3}from"node:fs";import{dirname as j3}from"node:path";import{resolveMcpSettingsPath as eK}from"@cline/shared/storage";import{z as M}from"zod";function TJ($){if(!$)return;if($==="http")return"streamableHttp";return $}function w0(){return eK()}function VG($){let f=MJ($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function Y3($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function AG($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function Mf($={}){let f=$.filePath??w0(),J=MJ(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=YG.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${W}`)}return Z.data}function BG($){let f=MJ($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Q}function c1($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function KG($){if($===void 0)return;let f=qJ.safeParse($);if(!f.success)return;return c1(f.data)}function Z1($={}){let f=$.filePath??w0();return oK(f)}function T$($={}){let f=Mf($);return Object.entries(f.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function qf($){let f=$.filePath??w0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=VG(f),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let W={...Z},j=Y3(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;AG(W,J,X),Z3(j3(f),{recursive:!0}),W3(f,`${JSON.stringify({...Q,mcpServers:W},null,2)}
3
- `)}function wf($,f={}){let J=Mf(f);if(!Object.hasOwn(J.mcpServers,$))return;return c1(J.mcpServers[$]?.oauth)}function Sf($,f,J={}){let Q=J.filePath??w0(),Z=BG(Q),W=Z.mcpServers,j=Y3(W,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let X=KG(j.oauth)??{},H=c1(f(X));if(H)j.oauth=H;else delete j.oauth;return Z3(j3(Q),{recursive:!0}),W3(Q,`${JSON.stringify(Z,null,2)}
4
- `,"utf8"),H??{}}function wJ($={}){return T$($).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function Cf($,f={}){let J=T$(f);for(let Q of J)await $.registerServer(Q);return J}var Tf,X3,qJ,$G,fG,JG,QG,ZG,WG,H3,jG,XG,HG,YG;var y8=p$(()=>{Tf=M.record(M.string(),M.string()),X3=M.record(M.string(),M.unknown()),qJ=M.object({clientInformation:M.record(M.string(),M.unknown()).optional(),tokens:M.record(M.string(),M.unknown()).optional(),codeVerifier:M.string().optional(),discoveryState:M.record(M.string(),M.unknown()).optional(),redirectUrl:M.string().url().optional(),lastError:M.string().optional(),lastAuthenticatedAt:M.number().int().positive().optional()}).strip(),$G=M.object({type:M.literal("stdio"),command:M.string().min(1),args:M.array(M.string()).optional(),cwd:M.string().min(1).optional(),env:Tf.optional()}),fG=M.object({type:M.literal("sse"),url:M.string().url(),headers:Tf.optional()}),JG=M.object({type:M.literal("streamableHttp"),url:M.string().url(),headers:Tf.optional()}),QG=M.discriminatedUnion("type",[$G,fG,JG]),ZG=M.object({transport:QG,disabled:M.boolean().optional(),metadata:X3.optional(),oauth:qJ.optional()}),WG=M.enum(["stdio","sse","http","streamableHttp"]).optional(),H3=M.object({type:M.enum(["stdio","sse","streamableHttp"]).optional(),transportType:WG,disabled:M.boolean().optional(),metadata:X3.optional(),oauth:qJ.optional()});jG=H3.extend({command:M.string().min(1),args:M.array(M.string()).optional(),cwd:M.string().min(1).optional(),env:Tf.optional()}).superRefine(($,f)=>{let J=$.type??TJ($.transportType);if(J&&J!=="stdio")f.addIssue({code:M.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})),XG=H3.extend({url:M.string().url(),headers:Tf.optional()}).superRefine(($,f)=>{let J=$.type??TJ($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:M.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??TJ($.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}}),HG=M.union([ZG,jG,XG]),YG=M.object({mcpServers:M.record(M.string(),HG)}).passthrough()});import{mkdirSync as gG,readFileSync as mG,writeFileSync as vG}from"node:fs";import{dirname as cG}from"node:path";import{resolveGlobalSettingsPath as N3}from"@cline/shared/storage";import{z as hf}from"zod";function y3(){return C8.parse({})}function Q$(){let $=N3(),f;try{f=JSON.parse(mG($,"utf8"))}catch{return y3()}let J=C8.safeParse(f);return J.success?J.data:y3()}function u1($,f={}){let J=N3(),Q=Q$();gG(cG(J),{recursive:!0});let Z=C8.parse($);if(!Q.telemetryOptOut&&Z.telemetryOptOut)T7(f.telemetry);vG(J,`${JSON.stringify(Z,null,2)}
5
- `,"utf8")}function hJ(){return Q$().telemetryOptOut}function uG($,f={}){u1({...Q$(),telemetryOptOut:$},f)}function r0($){return new Set($??Q$().disabledTools??[])}function E8($){return new Set($??Q$().disabledPlugins??[])}function dG($){return r0().has($)}function bJ($){let f=r0(),J=Q$();if(f.has($))return f.delete($),u1({...J,disabledTools:[...f]}),!1;return f.add($),u1({...J,disabledTools:[...f]}),!0}function T3($,f){let J=[...new Set($.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=Q$(),Z=r0(Q.disabledTools);for(let W of J)if(f)Z.add(W);else Z.delete(W);u1({...Q,disabledTools:[...Z]})}function M3($,f){return T3([$],f),f}function lG($){return E8().has($)}function pG($,f){let J=$.trim();if(!J)return;let Q=Q$(),Z=E8(Q.disabledPlugins);if(f)Z.add(J);else Z.delete(J);u1({...Q,disabledPlugins:[...Z]})}function kJ($,f){let J=E8(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q))}function d1($,f){let J=r0(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q.name))}function IJ($,f){if(!$||$.length===0)return $;let J=r0(f);if(J.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var _3,C8;var Z$=p$(()=>{R0();_3=hf.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,hf.array(hf.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,Q)=>J.localeCompare(Q));return f.length>0?f:void 0}),C8=hf.object({telemetryOptOut:hf.boolean().default(!1).catch(!1),disabledTools:_3.optional(),disabledPlugins:_3.optional()}).strip().transform(($)=>{let f={telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});import{existsSync as RU,mkdirSync as UU,readFileSync as LU,writeFileSync as OU}from"node:fs";import{resolve as zU}from"node:path";import{resolveSessionDataDir as _U}from"@cline/shared/storage";import{nanoid as yU}from"nanoid";import*as NU from"node-machine-id";function P1($){let f=$?.trim();if(f)return f;let J=qU();if(J)return J;return wU()}function MU(){let $=NU;return $.machineIdSync??$.default?.machineIdSync}function qU(){try{let $=MU();if(!$)return;return $().trim()||void 0}catch{return}}function wU(){let $=_U(),f=zU($,TU);try{if(RU(f)){let Q=LU(f,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${yU()}`;try{UU($,{recursive:!0}),OU(f,J,"utf8")}catch{}return J}var TU="machine-id";var J4=()=>{};class O2{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get($);if(!W)W=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,W);W.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get($);if(!W)W=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,W);W.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let H=X;if(!H)H=new Map,this.gaugeValues.set($,H);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,Q?{description:Q}:void 0);Y.addCallback((V)=>{for(let A of this.snapshotGaugeSeries($))V.observe(A.value,this.flattenProperties(A.attributes))}),this.gauges.set($,Y)}H.set(j,{value:f,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,Q=0){if(!$)return{};let Z={},W=100,j=10;for(let[X,H]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let Y=f?`${f}.${X}`:X;if(H===null||H===void 0){Z[Y]=String(H);continue}if(Array.isArray(H)){let V=H.length>W?H.slice(0,W):H;try{Z[Y]=JSON.stringify(V)}catch{Z[Y]="[UnserializableArray]"}if(H.length>W)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=H.length;continue}if(typeof H==="object"){if(H instanceof Date){Z[Y]=H.toISOString();continue}if(H instanceof Error){Z[Y]=H.message;continue}if(J.has(H)){Z[Y]="[Circular]";continue}if(Q>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(H),Object.assign(Z,this.flattenProperties(H,Y,J,Q+1));continue}if(M_(H)){Z[Y]=H;continue}try{Z[Y]=JSON.stringify(H)}catch{Z[Y]=String(H)}}return Z}}function M_($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class g4{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordHistogram($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordGauge($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class z2{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new g4({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let Q of this.adapters)Q.emitRequired($,J)}recordCounter($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,W,Q,Z)}recordHistogram($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,W,Q,Z)}recordGauge($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,W,Q,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var i9=()=>{};import{metrics as q_,trace as w_}from"@opentelemetry/api";import{logs as S_}from"@opentelemetry/api-logs";import{OTLPLogExporter as C_}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as E_}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as h_}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as b_}from"@opentelemetry/resources";import{BatchLogRecordProcessor as k_,ConsoleLogRecordExporter as I_,LoggerProvider as x_}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as g_,MeterProvider as m_,PeriodicExportingMetricReader as HH}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as v_,ConsoleSpanExporter as c_,SimpleSpanProcessor as u_}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as d_}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as l_,ATTR_SERVICE_VERSION as p_}from"@opentelemetry/semantic-conventions";class YH{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class _2{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=b_({[l_]:$.serviceName??"cline",...$.serviceVersion?{[p_]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)q_.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)S_.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return w_.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new O2({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new z2({...$,adapters:[f],distinctId:P1($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=n9(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=f.map((W)=>n_(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new m_({resource:$,readers:Z})}createTracerProvider($){let f=n9(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of f){let j=i_(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new d_({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=n9(this.options.logsExporter);if(f.length===0)return null;let J=f.map((Q)=>{let Z=r_(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new k_(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new x_({resource:$,processors:J})}}function m4($){let f=new _2($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function _1($){if(hJ())return{telemetry:new YH($)};if($.enabled!==!0)return{telemetry:new z2({...$,distinctId:P1($.distinctId)})};return m4($)}function v4($){let{telemetry:f,provider:J}=_1($);return{telemetry:f,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function n9($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function r_($,f){if($==="console")return new I_;if(!f.endpoint)return null;let J=a9(f.endpoint,"/v1/logs");return new C_({url:J,headers:f.headers})}function i_($,f){if($==="console")return new u_(new c_);if(!f.endpoint)return null;let J=a9(f.endpoint,"/v1/traces");return new v_(new h_({url:J,headers:f.headers}))}function n_($,f){if($==="console")return new HH({exporter:new g_,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=a9(f.endpoint,"/v1/metrics");return new HH({exporter:new E_({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function a9($,f){let J=new URL($),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith(f)?Q:`${Q}${f}`,J.toString()}var c4=p$(()=>{Z$();J4();i9()});var fY={};t4(fY,{createOpenTelemetryTelemetryService:()=>m4,createConfiguredTelemetryService:()=>_1,createConfiguredTelemetryHandle:()=>v4,OpenTelemetryProvider:()=>_2,OpenTelemetryAdapter:()=>O2});var A7=p$(()=>{c4()});import*as wu from"@cline/llms";import{buildClineSystemPrompt as Cu,buildSdkErrorProperties as Eu,ContributionRegistry as hu,captureSdkError as bu,createClineTelemetryServiceConfig as ku,createClineTelemetryServiceMetadata as Iu,createContributionRegistry as xu,createTool as gu,emptyWorkspaceManifest as mu,formatDisplayUserInput as vu,noopBasicLogger as cu,normalizeSdkError as uu,normalizeUserInput as du,parseUserCommandEnvelope as lu,registerDisposable as pu,SDK_ERROR_TELEMETRY_EVENT as ru}from"@cline/shared";export*from"@cline/shared/storage";function CY($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function z7($,f,J){let Q=CY(J);if(Q)return Q;let Z=f.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${W}`}return`Cline account request failed with status ${$}`}class s4{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),H;if(X.trim())try{H=JSON.parse(X)}catch{if(!j.ok)throw Error(z7(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(z7(j.status,X,H));if(typeof H==="object"&&H!==null){let Y=H;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(H===void 0||H===null)throw Error("Cline account response payload was empty");return H}finally{clearTimeout(W)}}}function _7($){return $.action==="clineAccount"}async function y7($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class o4{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}function e4($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((Q)=>{$.onOpenUrlError?.({url:f,error:Q})})}catch(Q){$.onOpenUrlError?.({url:f,error:Q})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}R0();import{getClineEnvironmentConfig as G6}from"@cline/shared";function gY(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function $$($){let f=await import("node:http"),J=$.host??"127.0.0.1",Q=$.timeoutMs??300000,Z=$.successHtml??mY,W=gY(),j=!1,X=null,H=null,Y=null,V=(K)=>{if(j)return;j=!0,W.resolve(K)},A=()=>{if(X)clearTimeout(X),X=null;let K=Y;if(Y=null,H)H.close(),H=null;if(K!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:K})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{A(),V(null)},Q),W.promise};for(let K of $.ports){let G=f.createServer((F,P)=>{try{let D=new URL(F.url||"",`http://${J}:${K}`);if(D.pathname!==$.callbackPath){P.statusCode=404,P.end("Not found");return}let O={url:D,code:D.searchParams.get("code")??void 0,state:D.searchParams.get("state")??void 0,provider:D.searchParams.get("provider")??void 0,error:D.searchParams.get("error")??void 0};if(O.error){P.statusCode=400,P.end(`Authentication failed: ${O.error}`),A(),V(O);return}if(!O.code){P.statusCode=400,P.end("Missing authorization code");return}if($.expectedState&&O.state!==$.expectedState){P.statusCode=400,P.end("State mismatch");return}P.statusCode=200,P.setHeader("Content-Type","text/html; charset=utf-8"),P.end(Z),A(),V(O)}catch{P.statusCode=500,P.end("Internal error")}}),R=await new Promise((F)=>{let P=(D)=>{G.off("error",P),F({bound:!1,error:D})};G.once("error",P),G.listen(K,J,()=>{G.off("error",P),H=G,F({bound:!0})})});if(R.error){if(R.error.code==="EADDRINUSE")continue;throw A(),R.error}if(R.bound){Y=K;let F=`http://${J}:${K}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:K,callbackUrl:F})).catch(()=>{});return{callbackUrl:F,waitForCallback:B,cancelWait:()=>{A(),V(null)},close:()=>{A(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var mY=`<!DOCTYPE html>
1
+ import{createRequire as tY}from"node:module";var iY=Object.defineProperty;var nY=($)=>$;function aY($,f){this[$]=nY.bind(null,f)}var Xf=($,f)=>{for(var J in f)iY($,J,{get:f[J],enumerable:!0,configurable:!0,set:aY.bind(f,J)})};var i$=($,f)=>()=>($&&(f=$($=0)),f);var k7=tY(import.meta.url);import{SDK_ERROR_TELEMETRY_EVENT as oY}from"@cline/shared";function c($,f,J){$?.capture({event:f,properties:J})}function S8($){if(!$)return;return $.substring(0,eY)}function $V($){if(typeof $==="string")return"Error";return $.name?.trim()||$.constructor?.name||"Error"}function fV($){return typeof $==="string"?$:$.message}function g7($,f){return $.some((J)=>f.has(J.trim().toLowerCase()))}function JV($){c($,k.CLIENT.EXTENSION_ACTIVATED)}function Af($,f){let J=[...f.vcs_types],Q={root_count:f.root_count,vcs_types:J,is_multi_root:f.root_count>1,has_git:g7(J,new Set(["git"])),has_mercurial:g7(J,new Set(["mercurial","hg"]))};if(f.init_duration_ms!==void 0)Q.init_duration_ms=f.init_duration_ms;if(f.feature_flag_enabled!==void 0)Q.feature_flag_enabled=f.feature_flag_enabled;if(f.is_remote_workspace!==void 0)Q.is_remote_workspace=f.is_remote_workspace;c($,k.WORKSPACE.INITIALIZED,Q)}function Bf($,f,J){c($,k.WORKSPACE.INIT_ERROR,{error_type:$V(f),error_message:S8(fV(f)),fallback_to_single_root:J.fallback_to_single_root,workspace_count:J.workspace_count??0})}function QV($,f){c($,k.WORKSPACE.PATH_RESOLVED,{...f})}function K$($,f){c($,k.USER.AUTH_STARTED,{provider:f})}function F$($,f){c($,k.USER.AUTH_SUCCEEDED,{provider:f})}function P$($,f,J){c($,k.USER.AUTH_FAILED,{provider:f,errorMessage:S8(J)})}function n$($,f,J){c($,k.USER.AUTH_LOGGED_OUT,{provider:f,reason:J})}function ZV($,f){c($,k.USER.PROVIDER_CONFIGURED,{provider:f})}function v7($,f){$?.captureRequired(k.USER.TELEMETRY_OPT_OUT,f)}function U$($,f){let J=f.id?.trim();if(J)$?.setDistinctId(J);$?.updateCommonProperties({account_id:f.id,account_email:f.email,provider:f.provider,organization_id:f.organizationId,organization_name:f.organizationName,member_id:f.memberId})}function Gf($,f){c($,k.TASK.CREATED,f)}function Kf($,f){c($,k.TASK.RESTARTED,f)}function h8($,f){c($,k.TASK.COMPLETED,f)}function A2($,f){c($,k.TASK.CONVERSATION_TURN,{...f,timestamp:new Date().toISOString()})}function Ff($,f){c($,k.TASK.TOKEN_USAGE,f)}function Pf($,f,J){c($,k.TASK.MODE_SWITCH,{ulid:f,mode:J})}function Uf($,f){c($,k.TASK.TOOL_USED,f)}function Df($,f){c($,k.TASK.SKILL_USED,f)}function Rf($,f){c($,k.TASK.DIFF_EDIT_FAILED,f)}function C8($,f){c($,k.TASK.PROVIDER_API_ERROR,{...f,errorMessage:S8(f.errorMessage)??"unknown",timestamp:new Date().toISOString()})}function Lf($,f,J){c($,k.TASK.MENTION_USED,{mentionType:f,contentLength:J,timestamp:new Date().toISOString()})}function Of($,f,J,Q){c($,k.TASK.MENTION_FAILED,{mentionType:f,errorType:J,errorMessage:S8(Q),timestamp:new Date().toISOString()})}function zf($,f,J,Q,Z){c($,k.TASK.MENTION_SEARCH_RESULTS,{queryLength:f.length,resultCount:J,searchType:Q,isEmpty:Z,timestamp:new Date().toISOString()})}function a$($,f){c($,k.TASK.AGENT_CREATED,{...f,timestamp:new Date().toISOString()})}function _f($,f){c($,k.TASK.AGENT_TEAM_CREATED,{...f,timestamp:new Date().toISOString()})}function E8($,f){c($,f.event==="ended"?k.TASK.SUBAGENT_COMPLETED:k.TASK.SUBAGENT_STARTED,{...f,timestamp:new Date().toISOString()})}function Nf($,f,J,Q){c($,k.HOOKS.DISCOVERY_COMPLETED,{hookName:f,globalCount:J,workspaceCount:Q,totalCount:J+Q,timestamp:new Date().toISOString()})}function Tf($,f){c($,k.TASK.COMPACTION_EXECUTED,{...f,timestamp:new Date().toISOString()})}function Mf($,f){c($,k.TASK.COMPACTION_SKIPPED,{...f,timestamp:new Date().toISOString()})}var eY=500,k;var G0=i$(()=>{k={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:oY}}});var kZ={};Xf(kZ,{normalizeUserMessage:()=>hG,buildInitialUserContent:()=>SG});async function SG($,f,J,Q){let Z=CG(f),W=await bG(J,Q);if(Z.length===0&&!W)return $;let j=[{type:"text",text:$},...Z];if(W)j.push(...W);return j}function hG($){if($==null)return"";if(typeof $==="string")return $;let f=$.content;if(typeof f==="string")return f;if(!Array.isArray(f))return"";let J=[];for(let Q of f)if(Q&&typeof Q==="object"&&Q.type==="text"){let Z=Q.text;if(typeof Z==="string")J.push(Z)}return J.join(`
2
+ `)}function CG($){if(!$||$.length===0)return[];let f=[];for(let J of $){let Q=EG(J);if(Q)f.push(Q)}return f}function EG($){let f=$.trim();if(!f)return;let J=f.match(/^data:([^;,]+);base64,(.+)$/);if(J){let Q=J[1],Z=J[2];if(!Q||!Z)return;return{type:"image",mediaType:Q,data:Z}}return{type:"image",mediaType:"image/png",data:f}}async function bG($,f){if(!$||$.length===0)return;let J=f??(async()=>{throw Error("File loading is not configured in this runtime. Provide userFileContentLoader to enable userFiles support.")}),Q=await Promise.all($.map(async(Z)=>{let W=Z.replace(/\\/g,"/");try{let j=await J(Z);return{type:"file",path:W,content:j}}catch(j){let X=j instanceof Error?j.message:String(j);return{type:"file",path:W,content:`Error fetching content: ${X}`}}}));if(Q.length===0)return;return Q}var T3={};Xf(T3,{updateMcpServerOAuthState:()=>C2,setMcpServerDisabled:()=>S2,resolveMcpServerRegistrations:()=>M$,resolveDefaultMcpSettingsPath:()=>C0,registerMcpServersFromSettingsFile:()=>E2,normalizeMcpServerOAuthState:()=>d1,loadMcpSettingsFile:()=>w2,listMcpServerOAuthStatuses:()=>vJ,hasMcpSettingsFile:()=>X1,getMcpServerOAuthState:()=>h2});import{existsSync as zK,mkdirSync as R3,readFileSync as mJ,writeFileSync as L3}from"node:fs";import{dirname as O3}from"node:path";import{resolveMcpSettingsPath as _K}from"@cline/shared/storage";import{z as q}from"zod";function xJ($){if(!$)return;if($==="http")return"streamableHttp";return $}function C0(){return _K()}function bK($){let f=mJ($,"utf8"),J;try{J=JSON.parse(f)}catch(Q){let Z=Q instanceof Error?Q.message:String(Q);throw Error(`Failed to parse MCP settings JSON at "${$}": ${Z}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object.`);return J}function N3($,f){if(!Object.hasOwn($,f))return;let J=$[f];if(!J||typeof J!=="object"||Array.isArray(J))return;return J}function kK($,f,J){Object.defineProperty($,f,{value:J,enumerable:!0,configurable:!0,writable:!0})}function w2($={}){let f=$.filePath??C0(),J=mJ(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${f}": ${j}`)}let Z=EK.safeParse(Q);if(!Z.success){let W=Z.error.issues.map((j)=>{let X=j.path.join(".");return X?`${X}: ${j.message}`:j.message}).join("; ");throw Error(`Invalid MCP settings at "${f}": ${W}`)}return Z.data}function IK($){let f=mJ($,"utf8"),J;try{J=JSON.parse(f)}catch(W){let j=W instanceof Error?W.message:String(W);throw Error(`Failed to parse MCP settings JSON at "${$}": ${j}`)}if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid MCP settings at "${$}": expected object`);let Q=J,Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${$}": mcpServers must be an object`);return Q}function d1($){if(!$)return;let f={...$.clientInformation?{clientInformation:$.clientInformation}:{},...$.tokens?{tokens:$.tokens}:{},...$.codeVerifier?{codeVerifier:$.codeVerifier}:{},...$.discoveryState?{discoveryState:$.discoveryState}:{},...$.redirectUrl?{redirectUrl:$.redirectUrl}:{},...$.lastError?{lastError:$.lastError}:{},...$.lastAuthenticatedAt?{lastAuthenticatedAt:$.lastAuthenticatedAt}:{}};return Object.keys(f).length>0?f:void 0}function xK($){if($===void 0)return;let f=gJ.safeParse($);if(!f.success)return;return d1(f.data)}function X1($={}){let f=$.filePath??C0();return zK(f)}function M$($={}){let f=w2($);return Object.entries(f.mcpServers).map(([J,Q])=>({name:J,transport:Q.transport,disabled:Q.disabled,metadata:Q.metadata,oauth:Q.oauth}))}function S2($){let f=$.filePath??C0(),J=$.name.trim();if(!J)throw Error("MCP server settings toggle requires a server name.");let Q=bK(f),Z=Q.mcpServers;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid MCP settings at "${f}": mcpServers must be an object.`);let W={...Z},j=N3(W,J);if(!j)throw Error(`Unknown MCP server: ${J}`);let X={...j};if($.disabled)X.disabled=!0;else delete X.disabled;kK(W,J,X),R3(O3(f),{recursive:!0}),L3(f,`${JSON.stringify({...Q,mcpServers:W},null,2)}
3
+ `)}function h2($,f={}){let J=w2(f);if(!Object.hasOwn(J.mcpServers,$))return;return d1(J.mcpServers[$]?.oauth)}function C2($,f,J={}){let Q=J.filePath??C0(),Z=IK(Q),W=Z.mcpServers,j=N3(W,$);if(!j)throw Error(`Unknown MCP server: ${$}`);let X=xK(j.oauth)??{},H=d1(f(X));if(H)j.oauth=H;else delete j.oauth;return R3(O3(Q),{recursive:!0}),L3(Q,`${JSON.stringify(Z,null,2)}
4
+ `,"utf8"),H??{}}function vJ($={}){return M$($).map((J)=>{let Q=J.transport.type!=="stdio",Z=J.oauth?.tokens?.access_token;return{serverName:J.name,oauthSupported:Q,oauthConfigured:Q&&typeof Z==="string"&&Z.trim().length>0,lastError:J.oauth?.lastError,lastAuthenticatedAt:J.oauth?.lastAuthenticatedAt}}).sort((J,Q)=>J.serverName.localeCompare(Q.serverName))}async function E2($,f={}){let J=M$(f);for(let Q of J)await $.registerServer(Q);return J}var y2,z3,gJ,NK,TK,MK,qK,yK,wK,_3,SK,hK,CK,EK;var S4=i$(()=>{y2=q.record(q.string(),q.string()),z3=q.record(q.string(),q.unknown()),gJ=q.object({clientInformation:q.record(q.string(),q.unknown()).optional(),tokens:q.record(q.string(),q.unknown()).optional(),codeVerifier:q.string().optional(),discoveryState:q.record(q.string(),q.unknown()).optional(),redirectUrl:q.string().url().optional(),lastError:q.string().optional(),lastAuthenticatedAt:q.number().int().positive().optional()}).strip(),NK=q.object({type:q.literal("stdio"),command:q.string().min(1),args:q.array(q.string()).optional(),cwd:q.string().min(1).optional(),env:y2.optional()}),TK=q.object({type:q.literal("sse"),url:q.string().url(),headers:y2.optional()}),MK=q.object({type:q.literal("streamableHttp"),url:q.string().url(),headers:y2.optional()}),qK=q.discriminatedUnion("type",[NK,TK,MK]),yK=q.object({transport:qK,disabled:q.boolean().optional(),metadata:z3.optional(),oauth:gJ.optional()}),wK=q.enum(["stdio","sse","http","streamableHttp"]).optional(),_3=q.object({type:q.enum(["stdio","sse","streamableHttp"]).optional(),transportType:wK,disabled:q.boolean().optional(),metadata:z3.optional(),oauth:gJ.optional()});SK=_3.extend({command:q.string().min(1),args:q.array(q.string()).optional(),cwd:q.string().min(1).optional(),env:y2.optional()}).superRefine(($,f)=>{let J=$.type??xJ($.transportType);if(J&&J!=="stdio")f.addIssue({code:q.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})),hK=_3.extend({url:q.string().url(),headers:y2.optional()}).superRefine(($,f)=>{let J=$.type??xJ($.transportType)??"sse";if(J!=="sse"&&J!=="streamableHttp")f.addIssue({code:q.ZodIssueCode.custom,message:'Expected type "sse" or "streamableHttp" for URL-based MCP server',path:["type"]})}).transform(($)=>{if(($.type??xJ($.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}}),CK=q.union([yK,SK,hK]),EK=q.object({mcpServers:q.record(q.string(),CK)}).passthrough()});import{mkdirSync as HF,readFileSync as YF,statSync as VF,writeFileSync as AF}from"node:fs";import{dirname as BF}from"node:path";import{resolveGlobalSettingsPath as g3}from"@cline/shared/storage";import{z as k2}from"zod";function x4(){return g4.parse({})}function GF(){m4=void 0}function KF($){if($.disabledTools)Object.freeze($.disabledTools);if($.disabledPlugins)Object.freeze($.disabledPlugins);return Object.freeze($)}function FF($){let f;try{f=YF($,"utf8")}catch{return x4()}try{let J=g4.safeParse(JSON.parse(f));return J.success?J.data:x4()}catch{return x4()}}function PF(){let $=g3(),f=VF($,{throwIfNoEntry:!1}),J=f?.mtimeMs??0,Q=f?.size??0,Z=m4;if(Z&&Z.path===$&&Z.mtimeMs===J&&Z.size===Q)return Z;let W=KF(f?FF($):x4());return m4={path:$,mtimeMs:J,size:Q,value:W},m4}function J$(){return PF().value}function I2($,f={}){let J=g3(),Q=J$();HF(BF(J),{recursive:!0});let Z=g4.parse($);if(!Q.telemetryOptOut&&Z.telemetryOptOut)v7(f.telemetry);AF(J,`${JSON.stringify(Z,null,2)}
5
+ `,"utf8"),GF()}function lJ(){return J$().telemetryOptOut}function UF($,f={}){I2({...J$(),telemetryOptOut:$},f)}function Q$($){return new Set($??J$().disabledTools??[])}function v4($){return new Set($??J$().disabledPlugins??[])}function DF($){return Q$().has($)}function pJ($){let f=J$(),J=new Set(f.disabledTools??[]),Q=J.has($);if(Q)J.delete($);else J.add($);return I2({...f,disabledTools:[...J]}),!Q}function v3($,f){let J=[...new Set($.map((W)=>W.trim()).filter(Boolean))];if(J.length===0)return;let Q=J$(),Z=Q$(Q.disabledTools);for(let W of J)if(f)Z.add(W);else Z.delete(W);I2({...Q,disabledTools:[...Z]})}function u3($,f){return v3([$],f),f}function RF($){return v4().has($)}function LF($,f){let J=$.trim();if(!J)return;let Q=J$(),Z=v4(Q.disabledPlugins);if(f)Z.add(J);else Z.delete(J);I2({...Q,disabledPlugins:[...Z]})}function rJ($,f){let J=v4(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q))}function l1($,f){let J=Q$(f);if(J.size===0)return[...$];return $.filter((Q)=>!J.has(Q.name))}function iJ($,f){if(!$||$.length===0)return $;let J=Q$(f);if(J.size===0)return $;return $.map((Q)=>{if(!Q.setup)return Q;return{...Q,setup:(Z,W)=>Q.setup?.({...Z,registerTool:(j)=>{if(!J.has(j.name))Z.registerTool(j)}},W)}})}var m3,g4,m4;var Z$=i$(()=>{G0();m3=k2.preprocess(($)=>Array.isArray($)?$.filter((f)=>typeof f==="string").map((f)=>f.trim()).filter(Boolean):void 0,k2.array(k2.string()).optional()).transform(($)=>{if(!$)return;let f=[...new Set($)].sort((J,Q)=>J.localeCompare(Q));return f.length>0?f:void 0}),g4=k2.object({telemetryOptOut:k2.boolean().default(!1).catch(!1),disabledTools:m3.optional(),disabledPlugins:m3.optional()}).strip().transform(($)=>{let f={telemetryOptOut:$.telemetryOptOut};if($.disabledTools?.length)f.disabledTools=$.disabledTools;if($.disabledPlugins?.length)f.disabledPlugins=$.disabledPlugins;return f})});import{existsSync as QL,mkdirSync as ZL,readFileSync as WL,writeFileSync as jL}from"node:fs";import{resolve as XL}from"node:path";import{resolveSessionDataDir as HL}from"@cline/shared/storage";import{nanoid as YL}from"nanoid";import*as VL from"node-machine-id";function U1($){let f=$?.trim();if(f)return f;let J=GL();if(J)return J;return KL()}function BL(){let $=VL;return $.machineIdSync??$.default?.machineIdSync}function GL(){try{let $=BL();if(!$)return;return $().trim()||void 0}catch{return}}function KL(){let $=HL(),f=XL($,AL);try{if(QL(f)){let Q=WL(f,"utf8").trim();if(Q.length>0)return Q}}catch{}let J=`cl-${YL()}`;try{ZL($,{recursive:!0}),jL(f,J,"utf8")}catch{}return J}var AL="machine-id";var V6=()=>{};class N8{name;metadata;meter;logger;enabled;distinctId;commonProperties;counters=new Map;histograms=new Map;gauges=new Map;gaugeValues=new Map;meterProvider;loggerProvider;constructor($){this.name=$.name??"OpenTelemetryAdapter",this.metadata={...$.metadata},this.meterProvider=$.meterProvider,this.loggerProvider=$.loggerProvider,this.meter=$.meterProvider?.getMeter("cline")??null,this.logger=$.loggerProvider?.getLogger("cline")??null,this.enabled=$.enabled??!0,this.distinctId=$.distinctId,this.commonProperties=$.commonProperties?{...$.commonProperties}:{}}emit($,f){if(!this.isEnabled())return;this.emitLog($,f,!1)}emitRequired($,f){this.emitLog($,f,!0)}recordCounter($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.counters.get($);if(!W)W=this.meter.createCounter($,Q?{description:Q}:void 0),this.counters.set($,W);W.add(f,this.flattenProperties(this.buildAttributes(J)))}recordHistogram($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.histograms.get($);if(!W)W=this.meter.createHistogram($,Q?{description:Q}:void 0),this.histograms.set($,W);W.record(f,this.flattenProperties(this.buildAttributes(J)))}recordGauge($,f,J,Q,Z=!1){if(!this.meter||!Z&&!this.isEnabled())return;let W=this.buildAttributes(J),j=JSON.stringify(W),X=this.gaugeValues.get($);if(f===null){if(X){if(X.delete(j),X.size===0)this.gaugeValues.delete($),this.gauges.delete($)}return}let H=X;if(!H)H=new Map,this.gaugeValues.set($,H);if(!this.gauges.has($)){let Y=this.meter.createObservableGauge($,Q?{description:Q}:void 0);Y.addCallback((V)=>{for(let A of this.snapshotGaugeSeries($))V.observe(A.value,this.flattenProperties(A.attributes))}),this.gauges.set($,Y)}H.set(j,{value:f,attributes:W})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}setDistinctId($){this.distinctId=$}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}async flush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.()])}emitLog($,f,J){if(!this.logger)return;let Q=this.flattenProperties(this.buildAttributes(f,J));this.logger.emit({severityText:"INFO",body:$,attributes:Q})}buildAttributes($,f=!1){return{...this.commonProperties,...this.metadata,...$,...this.distinctId?{distinct_id:this.distinctId}:{},...f?{_required:!0}:{}}}snapshotGaugeSeries($){let f=this.gaugeValues.get($);if(!f)return[];return Array.from(f.values(),(J)=>({value:J.value,attributes:J.attributes?{...J.attributes}:void 0}))}flattenProperties($,f="",J=new WeakSet,Q=0){if(!$)return{};let Z={},W=100,j=10;for(let[X,H]of Object.entries($)){if(X==="__proto__"||X==="constructor"||X==="prototype")continue;let Y=f?`${f}.${X}`:X;if(H===null||H===void 0){Z[Y]=String(H);continue}if(Array.isArray(H)){let V=H.length>W?H.slice(0,W):H;try{Z[Y]=JSON.stringify(V)}catch{Z[Y]="[UnserializableArray]"}if(H.length>W)Z[`${Y}_truncated`]=!0,Z[`${Y}_original_length`]=H.length;continue}if(typeof H==="object"){if(H instanceof Date){Z[Y]=H.toISOString();continue}if(H instanceof Error){Z[Y]=H.message;continue}if(J.has(H)){Z[Y]="[Circular]";continue}if(Q>=j){Z[Y]="[MaxDepthExceeded]";continue}J.add(H),Object.assign(Z,this.flattenProperties(H,Y,J,Q+1));continue}if(YN(H)){Z[Y]=H;continue}try{Z[Y]=JSON.stringify(H)}catch{Z[Y]=String(H)}}return Z}}function YN($){return typeof $==="string"||typeof $==="number"||typeof $==="boolean"}class n6{name;logger;enabled;constructor($={}){this.name=$.name??"TelemetryLoggerSink",this.logger=$.logger,this.enabled=$.enabled??!0}emit($,f){if(!this.isEnabled())return;this.logger?.log("telemetry.event",{telemetrySink:this.name,event:$,properties:f})}emitRequired($,f){this.logger?.log("telemetry.required_event",{telemetrySink:this.name,severity:"warn",event:$,properties:f})}recordCounter($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"counter",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordHistogram($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"histogram",name:$,value:f,attributes:J,description:Q,required:Z===!0})}recordGauge($,f,J,Q,Z){if(!Z&&!this.isEnabled())return;this.logger?.debug("telemetry.metric",{telemetrySink:this.name,instrument:"gauge",name:$,value:f,attributes:J,description:Q,required:Z===!0})}isEnabled(){return typeof this.enabled==="function"?this.enabled():this.enabled}async flush(){}async dispose(){}}class T8{adapters;metadata;distinctId;commonProperties;constructor($={}){if(this.adapters=[...$.adapters??[]],$.logger)this.adapters.push(new n6({logger:$.logger}));this.metadata={...$.metadata??{}},this.distinctId=$.distinctId,this.commonProperties={...$.commonProperties??{}}}addAdapter($){this.adapters.push($)}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return this.adapters.some(($)=>$.isEnabled())}capture($){let f=this.buildAttributes($.properties);for(let J of this.adapters)J.emit($.event,f)}captureRequired($,f){let J=this.buildAttributes(f);for(let Q of this.adapters)Q.emitRequired($,J)}recordCounter($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordCounter($,f,W,Q,Z)}recordHistogram($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordHistogram($,f,W,Q,Z)}recordGauge($,f,J,Q,Z=!1){let W=this.buildAttributes(J);for(let j of this.adapters)j.recordGauge($,f,W,Q,Z)}async flush(){await Promise.all(this.adapters.map(($)=>$.flush()))}async dispose(){await Promise.all(this.adapters.map(($)=>$.dispose()))}buildAttributes($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}var j7=()=>{};import{metrics as VN,trace as AN}from"@opentelemetry/api";import{logs as BN}from"@opentelemetry/api-logs";import{OTLPLogExporter as GN}from"@opentelemetry/exporter-logs-otlp-http";import{OTLPMetricExporter as KN}from"@opentelemetry/exporter-metrics-otlp-http";import{OTLPTraceExporter as FN}from"@opentelemetry/exporter-trace-otlp-http";import{resourceFromAttributes as PN}from"@opentelemetry/resources";import{BatchLogRecordProcessor as UN,ConsoleLogRecordExporter as DN,LoggerProvider as RN}from"@opentelemetry/sdk-logs";import{ConsoleMetricExporter as LN,MeterProvider as ON,PeriodicExportingMetricReader as qH}from"@opentelemetry/sdk-metrics";import{BatchSpanProcessor as zN,ConsoleSpanExporter as _N,SimpleSpanProcessor as NN}from"@opentelemetry/sdk-trace-base";import{NodeTracerProvider as TN}from"@opentelemetry/sdk-trace-node";import{ATTR_SERVICE_NAME as MN,ATTR_SERVICE_VERSION as qN}from"@opentelemetry/semantic-conventions";class yH{distinctId;metadata;commonProperties;constructor($={}){this.distinctId=$.distinctId,this.metadata={...$.metadata??{}},this.commonProperties={...$.commonProperties??{}}}setDistinctId($){this.distinctId=$}setMetadata($){this.metadata={...$}}updateMetadata($){this.metadata={...this.metadata,...$}}setCommonProperties($){this.commonProperties={...$}}updateCommonProperties($){this.commonProperties={...this.commonProperties,...$}}isEnabled(){return!1}capture($){this.resolveProperties($.properties)}captureRequired($,f){this.resolveProperties(f)}recordCounter(){}recordHistogram(){}recordGauge(){}async flush(){}async dispose(){}resolveProperties($){return{...this.commonProperties,...$,...this.metadata,...this.distinctId?{distinct_id:this.distinctId}:{}}}}class M8{meterProvider;loggerProvider;tracerProvider;options;constructor($={}){this.options=$;let f=PN({[MN]:$.serviceName??"cline",...$.serviceVersion?{[qN]:$.serviceVersion}:{}});if(this.meterProvider=this.createMeterProvider(f),this.loggerProvider=this.createLoggerProvider(f),this.tracerProvider=this.createTracerProvider(f),this.meterProvider)VN.setGlobalMeterProvider(this.meterProvider);if(this.loggerProvider)BN.setGlobalLoggerProvider(this.loggerProvider);if(this.tracerProvider)this.tracerProvider.register()}getTracer($="cline",f){return AN.getTracer($,f??this.options.serviceVersion)}createAdapter($){return new N8({...$,meterProvider:this.meterProvider,loggerProvider:this.loggerProvider})}createTelemetryService($){let f=this.createAdapter({name:$.name,enabled:this.options.enabled,metadata:$.metadata});return new T8({...$,adapters:[f],distinctId:U1($.distinctId)})}async forceFlush(){await Promise.all([this.meterProvider?.forceFlush?.(),this.loggerProvider?.forceFlush?.(),this.tracerProvider?.forceFlush?.()])}async dispose(){await Promise.all([this.meterProvider?.shutdown?.(),this.loggerProvider?.shutdown?.(),this.tracerProvider?.shutdown?.()])}createMeterProvider($){let f=X7(this.options.metricsExporter);if(f.length===0)return null;let J=Math.max(1000,this.options.metricExportIntervalMs??this.options.metricExportInterval??60000),Q=Math.min(30000,Math.floor(J*0.8)),Z=f.map((W)=>SN(W,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json",interval:J,timeout:Q})).filter((W)=>W!==null);if(Z.length===0)return null;return new ON({resource:$,readers:Z})}createTracerProvider($){let f=X7(this.options.tracesExporter);if(f.length===0)return null;let J=this.options.otlpTracesEndpoint??this.options.otlpEndpoint,Q=this.options.otlpTracesHeaders??this.options.otlpHeaders,Z=[];for(let W of f){let j=wN(W,{endpoint:J,headers:Q,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(j)Z.push(j)}if(Z.length===0)return null;return new TN({resource:$,spanProcessors:Z})}createLoggerProvider($){let f=X7(this.options.logsExporter);if(f.length===0)return null;let J=f.map((Q)=>{let Z=yN(Q,{endpoint:this.options.otlpEndpoint,headers:this.options.otlpHeaders,insecure:this.options.otlpInsecure??!1,protocol:"http/json"});if(!Z)return null;return new UN(Z,{maxQueueSize:this.options.logMaxQueueSize??2048,maxExportBatchSize:this.options.logBatchSize??512,scheduledDelayMillis:this.options.logBatchTimeoutMs??this.options.logBatchTimeout??5000})}).filter((Q)=>Q!==null);if(J.length===0)return null;return new RN({resource:$,processors:J})}}function a6($){let f=new M8($),J=f.createTelemetryService($);return J.captureRequired("telemetry.provider_created",{provider:"opentelemetry",enabled:$.enabled??!0,logsExporter:Array.isArray($.logsExporter)?$.logsExporter.join(","):$.logsExporter,metricsExporter:Array.isArray($.metricsExporter)?$.metricsExporter.join(","):$.metricsExporter,tracesExporter:Array.isArray($.tracesExporter)?$.tracesExporter.join(","):$.tracesExporter,otlpProtocol:$.otlpProtocol,hasOtlpEndpoint:Boolean($.otlpEndpoint),serviceName:$.serviceName,serviceVersion:$.serviceVersion}),{provider:f,telemetry:J}}function T1($){if(lJ())return{telemetry:new yH($)};if($.enabled!==!0)return{telemetry:new T8({...$,distinctId:U1($.distinctId)})};return a6($)}function t6($){let{telemetry:f,provider:J}=T1($);return{telemetry:f,provider:J,flush:async()=>{let W=J;if(W&&typeof W.forceFlush==="function")try{await W.forceFlush()}catch{}},dispose:async()=>{await Promise.allSettled([f.dispose(),J?.dispose()])}}}function X7($){if(!$)return[];return(Array.isArray($)?$:$.split(",")).map((J)=>J.trim()).filter((J)=>J==="console"||J==="otlp")}function yN($,f){if($==="console")return new DN;if(!f.endpoint)return null;let J=H7(f.endpoint,"/v1/logs");return new GN({url:J,headers:f.headers})}function wN($,f){if($==="console")return new NN(new _N);if(!f.endpoint)return null;let J=H7(f.endpoint,"/v1/traces");return new zN(new FN({url:J,headers:f.headers}))}function SN($,f){if($==="console")return new qH({exporter:new LN,exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout});if(!f.endpoint)return null;let J=H7(f.endpoint,"/v1/metrics");return new qH({exporter:new KN({url:J,headers:f.headers}),exportIntervalMillis:f.interval,exportTimeoutMillis:f.timeout})}function H7($,f){let J=new URL($),Q=J.pathname.endsWith("/")?J.pathname.slice(0,-1):J.pathname;return J.pathname=Q.endsWith(f)?Q:`${Q}${f}`,J.toString()}var s6=i$(()=>{Z$();V6();j7()});var OY={};Xf(OY,{createOpenTelemetryTelemetryService:()=>a6,createConfiguredTelemetryService:()=>T1,createConfiguredTelemetryHandle:()=>t6,OpenTelemetryProvider:()=>M8,OpenTelemetryAdapter:()=>N8});var T7=i$(()=>{s6()});import*as zd from"@cline/llms";import{buildClineSystemPrompt as Nd,buildSdkErrorProperties as Td,ContributionRegistry as Md,captureSdkError as qd,createClineTelemetryServiceConfig as yd,createClineTelemetryServiceMetadata as wd,createContributionRegistry as Sd,createTool as hd,emptyWorkspaceManifest as Cd,formatDisplayUserInput as Ed,noopBasicLogger as bd,normalizeSdkError as kd,normalizeUserInput as Id,parseUserCommandEnvelope as xd,registerDisposable as md,SDK_ERROR_TELEMETRY_EVENT as gd}from"@cline/shared";export*from"@cline/shared/storage";function sY($){if(typeof $!=="object"||$===null||!("error"in $))return;let f=$.error;return typeof f==="string"&&f.trim()?f:void 0}function I7($,f,J){let Q=sY(J);if(Q)return Q;let Z=f.trim();if(Z){let W=Z.length>200?`${Z.slice(0,200)}...`:Z;return`Cline account request failed with status ${$}: ${W}`}return`Cline account request failed with status ${$}`}class Hf{apiBaseUrl;getAuthTokenFn;getCurrentUserIdFn;getOrganizationMemberIdFn;getHeadersFn;requestTimeoutMs;fetchImpl;constructor($){let f=$.apiBaseUrl.trim();if(!f)throw Error("apiBaseUrl is required");this.apiBaseUrl=f,this.getAuthTokenFn=$.getAuthToken,this.getCurrentUserIdFn=$.getCurrentUserId,this.getOrganizationMemberIdFn=$.getOrganizationMemberId,this.getHeadersFn=$.getHeaders,this.requestTimeoutMs=$.requestTimeoutMs??30000,this.fetchImpl=$.fetchImpl??fetch}async fetchMe(){return this.request("/api/v1/users/me")}async fetchRemoteConfig(){return this.request("/api/v1/users/me/remote-config")}async fetchFeaturebaseToken(){try{return await this.request("/api/v1/users/me/featurebase-token")}catch{return}}async fetchBalance($){let f=await this.resolveUserId($);return this.request(`/api/v1/users/${encodeURIComponent(f)}/balance`)}async fetchUsageTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/usages`)).items??[]}async fetchPaymentTransactions($){let f=await this.resolveUserId($);return(await this.request(`/api/v1/users/${encodeURIComponent(f)}/payments`)).paymentTransactions??[]}async fetchUserOrganizations(){return(await this.fetchMe()).organizations??[]}async fetchOrganization($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}`)}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request(`/api/v1/organizations/${encodeURIComponent(f)}/balance`)}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");let J=await this.resolveOrganizationMemberId(f,$.memberId);return(await this.request(`/api/v1/organizations/${encodeURIComponent(f)}/members/${encodeURIComponent(J)}/usages`)).items??[]}async switchAccount($){await this.request("/api/v1/users/active-account",{method:"PUT",body:{organizationId:$?.trim()||null},expectNoContent:!0})}async resolveUserId($){let f=$?.trim();if(f)return f;let Q=(this.getCurrentUserIdFn?await this.getCurrentUserIdFn():void 0)?.trim();if(Q)return Q;let Z=await this.fetchMe();if(!Z.id?.trim())throw Error("Unable to resolve current user id");return Z.id}async resolveOrganizationMemberId($,f){let J=f?.trim();if(J)return J;let Z=(this.getOrganizationMemberIdFn?await this.getOrganizationMemberIdFn($):void 0)?.trim();if(Z)return Z;let j=(await this.fetchUserOrganizations()).find((X)=>X.organizationId===$)?.memberId;if(!j?.trim())throw Error(`Unable to resolve memberId for organization ${$}`);return j}async request($,f){let J=(await this.getAuthTokenFn())?.trim();if(!J)throw Error("No Cline account auth token found");let Q=this.getHeadersFn?await this.getHeadersFn():{},Z=new AbortController,W=setTimeout(()=>Z.abort(),this.requestTimeoutMs);try{let j=await this.fetchImpl(new URL($,this.apiBaseUrl),{method:f?.method??"GET",headers:{Authorization:`Bearer ${J}`,"Content-Type":"application/json",...Q??{}},body:f?.body!==void 0?JSON.stringify(f.body):void 0,signal:Z.signal});if(j.status===204||f?.expectNoContent){if(!j.ok)throw Error(`Cline account request failed with status ${j.status}`);return}let X=await j.text(),H;if(X.trim())try{H=JSON.parse(X)}catch{if(!j.ok)throw Error(I7(j.status,X,void 0));throw Error("Cline account response was not valid JSON")}if(!j.ok)throw Error(I7(j.status,X,H));if(typeof H==="object"&&H!==null){let Y=H;if(typeof Y.success==="boolean"){if(!Y.success)throw Error(Y.error||"Cline account request failed");if(Y.data!==void 0)return Y.data}}if(H===void 0||H===null)throw Error("Cline account response payload was empty");return H}finally{clearTimeout(W)}}}function x7($){return $.action==="clineAccount"}async function m7($,f){switch($.operation){case"fetchMe":return f.fetchMe();case"fetchBalance":return f.fetchBalance($.userId);case"fetchUsageTransactions":return f.fetchUsageTransactions($.userId);case"fetchPaymentTransactions":return f.fetchPaymentTransactions($.userId);case"fetchUserOrganizations":return f.fetchUserOrganizations();case"fetchOrganizationBalance":return f.fetchOrganizationBalance($.organizationId);case"fetchOrganizationUsageTransactions":return f.fetchOrganizationUsageTransactions({organizationId:$.organizationId,memberId:$.memberId});case"switchAccount":return await f.switchAccount($.organizationId),{updated:!0};case"fetchFeaturebaseToken":return f.fetchFeaturebaseToken?.();default:throw Error(`Unsupported Cline account operation: ${String($)}`)}}class Yf{executor;constructor($){this.executor=$}async fetchMe(){return this.request({action:"clineAccount",operation:"fetchMe"})}async fetchBalance($){return this.request({action:"clineAccount",operation:"fetchBalance",...$?.trim()?{userId:$.trim()}:{}})}async fetchUsageTransactions($){return this.request({action:"clineAccount",operation:"fetchUsageTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchPaymentTransactions($){return this.request({action:"clineAccount",operation:"fetchPaymentTransactions",...$?.trim()?{userId:$.trim()}:{}})}async fetchUserOrganizations(){return this.request({action:"clineAccount",operation:"fetchUserOrganizations"})}async fetchOrganizationBalance($){let f=$.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationBalance",organizationId:f})}async fetchOrganizationUsageTransactions($){let f=$.organizationId.trim();if(!f)throw Error("organizationId is required");return this.request({action:"clineAccount",operation:"fetchOrganizationUsageTransactions",organizationId:f,...$.memberId?.trim()?{memberId:$.memberId.trim()}:{}})}async switchAccount($){await this.request({action:"clineAccount",operation:"switchAccount",organizationId:$?.trim()||null})}async fetchFeaturebaseToken(){return this.request({action:"clineAccount",operation:"fetchFeaturebaseToken"})}async request($){return(await this.executor.runProviderAction($)).result}}function Vf($){return{onAuth:({url:f,instructions:J})=>{if($.onOutput?.(J??"Complete sign-in in your browser."),$.openUrl)try{Promise.resolve($.openUrl(f)).catch((Q)=>{$.onOpenUrlError?.({url:f,error:Q})})}catch(Q){$.onOpenUrlError?.({url:f,error:Q})}$.onOutput?.(f)},onPrompt:$.onPrompt,onServerListening:$.onServerListening,onServerClose:$.onServerClose}}G0();import{getClineEnvironmentConfig as qf}from"@cline/shared";function WV(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}async function e0($){let f=await import("node:http"),J=$.host??"127.0.0.1",Q=$.timeoutMs??300000,Z=$.successHtml??jV,W=WV(),j=!1,X=null,H=null,Y=null,V=(G)=>{if(j)return;j=!0,W.resolve(G)},A=()=>{if(X)clearTimeout(X),X=null;let G=Y;if(Y=null,H)H.close(),H=null;if(G!==null&&$.onClose)Promise.resolve($.onClose({host:J,port:G})).catch(()=>{})},B=async()=>{return X=setTimeout(()=>{A(),V(null)},Q),W.promise};for(let G of $.ports){let K=f.createServer((F,P)=>{try{let U=new URL(F.url||"",`http://${J}:${G}`);if(U.pathname!==$.callbackPath){P.statusCode=404,P.end("Not found");return}let z={url:U,code:U.searchParams.get("code")??void 0,state:U.searchParams.get("state")??void 0,provider:U.searchParams.get("provider")??void 0,error:U.searchParams.get("error")??void 0};if(z.error){P.statusCode=400,P.end(`Authentication failed: ${z.error}`),A(),V(z);return}if(!z.code){P.statusCode=400,P.end("Missing authorization code");return}if($.expectedState&&z.state!==$.expectedState){P.statusCode=400,P.end("State mismatch");return}P.statusCode=200,P.setHeader("Content-Type","text/html; charset=utf-8"),P.end(Z),A(),V(z)}catch{P.statusCode=500,P.end("Internal error")}}),D=await new Promise((F)=>{let P=(U)=>{K.off("error",P),F({bound:!1,error:U})};K.once("error",P),K.listen(G,J,()=>{K.off("error",P),H=K,F({bound:!0})})});if(D.error){if(D.error.code==="EADDRINUSE")continue;throw A(),D.error}if(D.bound){Y=G;let F=`http://${J}:${G}${$.callbackPath}`;if($.onListening)await Promise.resolve($.onListening({host:J,port:G,callbackUrl:F})).catch(()=>{});return{callbackUrl:F,waitForCallback:B,cancelWait:()=>{A(),V(null)},close:()=>{A(),V(null)}}}}return{callbackUrl:"",waitForCallback:async()=>null,cancelWait:()=>{},close:()=>{}}}var jV=`<!DOCTYPE html>
6
6
  <html lang="en">
7
7
  <head>
8
8
  <meta charset="utf-8">
@@ -43,17 +43,17 @@ import{createRequire as SY}from"node:module";var MY=Object.defineProperty;var qY
43
43
  </div>
44
44
  <script>setTimeout(() => window.close(), 3000);</script>
45
45
  </body>
46
- </html>`;function M7($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function vY($){let J=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function cY($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),M7(f)}async function C2(){let $=cY(),f=M7(await vY($));return{verifier:$,challenge:f}}function E2($){return $.endsWith("/")?$.slice(0,-1):$}function n$($,f){return new URL(f,`${E2($)}/`).toString()}function q1($,f={}){let J=$.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:f.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:f.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function uY($){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 j0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=uY(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function w1($){try{let f=JSON.parse($),J=f.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function a$($,f){return Date.now()>=$.expires-f}async function S1($){if(!$.onManualCodeInput){let W=await $.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let f,J,Q=$.onManualCodeInput().then((W)=>{f=W,$.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return q1(f,$.parseOptions);if(await Q,J)throw J;if(f)return q1(f,$.parseOptions);return{}}var h2={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},C7={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},P6="https://api.workos.com",dY="/auth",q7=Array.from({length:11},($,f)=>48801+f),lY=300000,pY=30000,C1=30000,rY=300,iY=5;class R$ extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function nY($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function F6($,f,J={}){let Q=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:nY($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function D6($){if(!$)return{};return typeof $==="function"?await $():$}function w7($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function S7($){await new Promise((f)=>setTimeout(f,$))}function R6($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function E7($,f){let J=await fetch(n$(P6,C7.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??C1)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new R$(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:w7(Q.expires_in,rY),pollIntervalSeconds:w7(Q.interval,iY)}}async function h7($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let Q=await fetch(n$($.workosApiBaseUrl,C7.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await S7(J*1000);break}case"slow_down":{J+=1,await S7(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new R$(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new R$(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function b7($,f,J){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(n$(f.apiBaseUrl,h2.register),{method:"POST",headers:{"Content-Type":"application/json",...await D6(f.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(f.requestTimeoutMs??C1)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=w1(j);throw new R$(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let W=await Z.json();return F6(R6(W,"Invalid token exchange response"),J??f.provider)}async function aY($,f,J,Q){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:Q??J.provider},W=await fetch(n$(J.apiBaseUrl,h2.token),{method:"POST",headers:{"Content-Type":"application/json",...await D6(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??C1)});if(!W.ok){let X=await W.text().catch(()=>""),H=w1(X);throw new R$(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let j=await W.json();return F6(R6(j,"Invalid token exchange response"),Q??J.provider)}async function b2($){G$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:q7,Q=$.callbackPath??dY,Z=f?null:await $$({ports:J,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??q7[0]}${Q}`;try{let j;if(f){let X=G6().workOsClientId,H=await E7(X,$);$.callbacks.onAuth({url:H.verificationUriComplete??H.verificationUri,instructions:`Enter this code in your browser: ${H.userCode}`});let Y=await h7({clientId:X,deviceCode:H.deviceCode,expiresInSeconds:H.expiresInSeconds,initialPollIntervalSeconds:H.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??C1,workosApiBaseUrl:P6,onProgress:$.callbacks.onProgress});j=await b7(Y,$,$.provider)}else{let X=new URL(n$($.apiBaseUrl,h2.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",W),X.searchParams.set("redirect_uri",W),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let H,Y=$.provider,V=await S1({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(H=V.code,Y=V.provider??Y,!H){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=q1(A,{includeProvider:!0});H=B.code,Y=B.provider??Y}if(!H)throw Error("Missing authorization code");j=await aY(H,W,$,Y)}return P$($.telemetry,$.provider??"cline"),D$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw F$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function tY($){return await E7(G6().workOsClientId,$)}async function sY($){let f=$.provider??"cline";G$($.telemetry,f);try{let J=await h7({clientId:G6().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??C1,workosApiBaseUrl:P6}),Q=await b7(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return P$($.telemetry,f),D$($.telemetry,{id:Q.accountId,email:Q.email,provider:f}),Q}catch(J){throw F$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function U6($,f){let J=await fetch(n$(f.apiBaseUrl,h2.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await D6(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??C1)});if(!J.ok){let W=await J.text().catch(()=>""),j=w1(W);throw new R$(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=$.metadata?.provider??f.provider;return F6(R6(Q,"Invalid token refresh response"),Z,$)}async function L6($,f,J){if(!$)return null;let Q=J?.refreshBufferMs??lY,Z=J?.retryableTokenGraceMs??pY;if(J?.forceRefresh!==!0&&!a$($,Q))return $;try{return await U6($,f)}catch(j){if(j instanceof R$&&j.isLikelyInvalidGrant())return r$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function oY($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return b2({...$,callbacks:f})},async refreshToken(f){return U6(f,$)},getApiKey(f){return`workos:${f.access}`}}}R0();import{nanoid as eY}from"nanoid";var t={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 k2 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function $V($,f,J=t.redirectUri){let Q=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function fV($){try{let f=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:t.clientId}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!f.ok){let Q=await f.text().catch(()=>""),Z=w1(Q);throw new k2(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof k2)throw f;return{type:"failed"}}}async function JV($="pi"){let{verifier:f,challenge:J}=await C2(),Q=eY(32),Z=new URL(t.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",t.clientId),Z.searchParams.set("redirect_uri",t.redirectUri),Z.searchParams.set("scope",t.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:Q,url:Z.toString()}}function QV(){try{let $=new URL(t.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):t.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:t.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:t.callbackPort,callbackPath:"/auth/callback",redirectUri:t.redirectUri}}}function k7($,f){let J=f?j0(f):j0($),Q=J?J:j0($),W=Q?.[t.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let H=j[0];if(typeof H?.id==="string"&&H.id.length>0)return H.id}let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function I7($,f){let J=k7($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function I2($){G$($.telemetry,"openai-codex");let f=QV(),{verifier:J,state:Q,url:Z}=await JV($.originator),W=await $$({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:Q});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await S1({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Q)throw Error("State mismatch");if(j=X.code,!j){let V=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=q1(V,{allowHashCodeState:!0});if(A.state&&A.state!==Q)throw Error("State mismatch");j=A.code}if(!j)throw Error("Missing authorization code");let H=await $V(j,J,f.redirectUri);if(H.type!=="success")throw Error("Token exchange failed");let Y=I7(H);return P$($.telemetry,"openai-codex"),D$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(X){throw F$($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{W.close()}}async function O6($,f){let J=await fV($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=I7(J,f);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function z6($,f){if(!$)return null;let J=f?.refreshBufferMs??t.refreshBufferMs,Q=f?.retryableTokenGraceMs??t.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!a$($,J))return $;try{return await O6($.refresh,$)}catch(W){if(W instanceof k2&&W.isLikelyInvalidGrant())return r$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}function ZV($,f=t.refreshBufferMs){return a$($,f)}function WV($){let f=$.accountId??k7($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var jV={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return I2({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return O6($.refresh,$)},getApiKey($){return $.access}};R0();import{nanoid as x7}from"nanoid";class _6{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+Q})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var XV="a8331954c0cf48ba99b5dd223a14c6ea",HV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",YV="openid offline_access",N6="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",VV="c1aba3deed5740659981a752714eba33",AV="https://login-ext.identity.oraclecloud.com",BV="openid offline_access",T6="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",KV="opc-request-id",GV="/auth/oca",PV=Array.from({length:11},($,f)=>48801+f),FV=300000,DV=30000,g7=30000,RV=600000;class x2 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var U$={internal:{clientId:XV,idcsUrl:HV,scopes:YV,baseUrl:N6},external:{clientId:VV,idcsUrl:AV,scopes:BV,baseUrl:T6}},Yf=new Map,UV=86400000,LV=300000,OV=32,y6=new _6(UV,OV);function m7($){if(typeof $==="function")return $();return $??"internal"}function v7($){return{internal:{clientId:$?.internal?.clientId??U$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??U$.internal.idcsUrl,scopes:$?.internal?.scopes??U$.internal.scopes,baseUrl:$?.internal?.baseUrl??U$.internal.baseUrl},external:{clientId:$?.external?.clientId??U$.external.clientId,idcsUrl:$?.external?.idcsUrl??U$.external.idcsUrl,scopes:$?.external?.scopes??U$.external.scopes,baseUrl:$?.external?.baseUrl??U$.external.baseUrl}}}function zV($=Date.now()){let f=$-RV;for(let[J,Q]of Yf.entries())if(Q.createdAt<f)Yf.delete(J)}function _V($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=j0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=j0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function c7($,f,J){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=j0($.id_token),j=j0(Q),X=W?.sub??j?.sub,H=W?.email??j?.email;return{access:Q,refresh:Z,expires:_V($,Q,$.id_token),accountId:X??J?.accountId,email:H??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function u7($,f){let J=E2($),Q=y6.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!W.ok){let H=`${J}/oauth2/v1/token`;return y6.set(J,H,Date.now(),LV),H}let X=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return y6.set(J,X),X}function d7($){return{code:$.error,message:$.error_description}}async function yV($){let f=Yf.get($.state);if(!f)throw Error("No PKCE verifier found for this state");Yf.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,Q=await u7(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await W.json();if(!W.ok){let H=d7(j);throw new x2(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let X=j0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return c7(j,$.mode)}function NV($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${E2(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function g2($){G$($.telemetry,"oca");let f=v7($.config),J=m7($.mode),Q=$.callbackPorts?.length?$.callbackPorts:PV,Z=$.callbackPath??GV,W=$.requestTimeoutMs??g7,j=await $$({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let H=x7(16),Y=x7(16),{verifier:V,challenge:A}=await C2();zV(),Yf.set(H,{verifier:V,nonce:Y,mode:J,redirectUri:X,createdAt:Date.now()});let B=NV({callbackUrl:X,mode:J,state:H,nonce:Y,challenge:A,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let K=await S1({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),G=K.code,R=K.state;if(K.error)throw Error(`OAuth error: ${K.error}`);if(!G){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!R||R!==H)throw Error("State mismatch");let F=await yV({code:G,state:R,mode:J,config:f,requestTimeoutMs:W});return P$($.telemetry,"oca"),D$($.telemetry,{id:F.accountId,email:F.email,provider:"oca"}),F}catch(K){throw F$($.telemetry,"oca",K instanceof Error?K.message:String(K)),K}finally{j.close()}}async function M6($,f={}){let J=v7(f.config),Q=f.requestTimeoutMs??g7,Z=$.metadata?.mode,W=Z==="internal"||Z==="external"?Z:m7(f.mode),j=W==="external"?J.external:J.internal,X=await u7(j.idcsUrl,Q),H=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(Q)}),V=await Y.json();if(!Y.ok){let A=d7(V);throw new x2(`Token refresh failed: ${Y.status}${A.message?` - ${A.message}`:""}`,{status:Y.status,errorCode:A.code})}return c7(V,W,$)}async function q6($,f,J){if(!$)return null;let Q=f?.refreshBufferMs??J?.refreshBufferMs??FV,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??DV;if(f?.forceRefresh!==!0&&!a$($,Q))return $;try{return await M6($,J)}catch(j){if(j instanceof x2&&j.isLikelyInvalidGrant())return r$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function TV($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return g2({...$,callbacks:f})},async refreshToken(f){return M6(f,$)},getApiKey(f){return f.access}}}async function l7($,f){let J=new TextEncoder,Q=async(Y)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(V).slice(0,4),(A)=>A.toString(16).padStart(2,"0")).join("")},[Z,W]=await Promise.all([Q(f),Q($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),X=new Uint32Array(1);crypto.getRandomValues(X);let H=(X[0]??0).toString(16).padStart(8,"0");return Z+W+j+H}async function MV($){let f=await l7($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[KV]:f}}import*as N0 from"@cline/llms";import{z as N}from"zod";import*as s from"@cline/llms";function w6($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((f)=>f.length>0)}function qV($,f){let J=w6($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let Q=$,Z=w6(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[f];if(W&&typeof W==="object"){let X=w6(W.models??W);if(X.length>0)return X}return[]}async function m2($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return qV(await J.json(),f)}function p7($){return $.replace(/\/+$/,"")}function v2($,f,J){let Q=J?.trim();if(!Q)return;let Z=$?.trim();if(!Z||!f?.trim())return Q;try{let W=new URL(Q),j=new URL(f),X=new URL(Z);if(W.origin!==j.origin)return Q;let H=p7(j.pathname),Y=p7(X.pathname);if(H&&W.pathname.startsWith(`${H}/`)){let V=W.pathname.slice(H.length);X.pathname=`${Y}${V}`}else X.pathname=W.pathname;return X.search=W.search,X.hash=W.hash,X.toString()}catch{return Q}}function wV($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function SV($){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 CV=Object.values(s.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:wV($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),i7=Object.fromEntries(CV.map(($)=>[$.id,$]));function EV($){return i7[$]}function hV(){return Object.fromEntries(Object.entries(i7).filter(([,$])=>SV($)))}function n7($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var a7="https://models.dev/api.json",bV=600000,t7=300000,kV=5000,u2=new Map,Vf=new Map,E6=new Map,c2=new Map;async function IV(){return s.getGeneratedProviderModels()}async function xV($,f={},J={},Q={},Z={},W={}){let j=await IV(),X=s.resolveProviderModelCatalogKeys($),H=Object.assign({},...X.map((B)=>j[B]??{})),Y=Boolean(s.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),V=Object.keys(Z).length>0;if(Y&&V)return s.sortModelsByReleaseDate({...Z,...W});let A=Object.keys(Q).length>0;if($==="openai-codex"&&A)return s.sortModelsByReleaseDate({...Q,...W});return s.sortModelsByReleaseDate({...H,...f,...J,...Q,...Z,...W})}function gV($,f){let J=s.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((Q)=>f[Q]??{}))}function h6($){let f=$?.trim();return f&&f.length>0?f:""}function b6($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function mV($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function vV($,f){return`${$}:${h6(f.baseUrl)}:${mV(b6(f)??"")}`}function cV($){let f=$?.trim();if(!f)return;let J=j0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}async function k6($,f,J=kV){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch($,{...f,signal:Q.signal})}finally{clearTimeout(Z)}}function S6($,f,J){if(J&&!$.includes(f))$.push(f)}function Af($,f){let J=["streaming","tools"];return S6(J,"images",Boolean(f.supportsImages)),S6(J,"prompt-cache",Boolean(f.supportsPromptCache)),S6(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}function uV($){let f=s.getGeneratedModelsForProvider("openai-native")[$.id];if(f)return{...f,id:$.id,name:$.name??f.name??$.id};return Af($.id,{name:$.name??$.id})}async function dV($,f){let J=await k6("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let H=j.supported_features??[];W[X]=Af(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:H.includes("reasoning")||H.includes("reasoning_effort"),supportsImages:!1})}return W}async function lV($,f){let J=await k6("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;W[X]=Af(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}function pV($){let f=h6($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function rV($,f){let Q=`${pV($.baseUrl)}/v1/model/info`,Z=async(Y)=>k6(Q,{method:"GET",headers:{accept:"application/json",...Y}}),W=await Z({"x-litellm-api-key":f});if(!W.ok)W=await Z({Authorization:`Bearer ${f}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let X=(await W.json())?.data??[],H={};for(let Y of X){let V=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||V;if(!B)continue;let K=Y.model_info,G=Af(B,{name:V??B,maxTokens:K?.max_output_tokens??K?.max_tokens,maxInputTokens:K?.max_input_tokens??K?.max_tokens,supportsImages:K?.supports_vision,supportsPromptCache:K?.supports_prompt_caching,supportsReasoning:K?.supports_reasoning});if(H[B]=G,V)H[V]={...G,id:V,name:V}}return H}async function iV($,f){let J=await s.listOpenAICodexModels({accessToken:f,accountId:$.accountId??cV(f),cwd:typeof $.codex?.defaultSettings?.cwd==="string"?$.codex.defaultSettings.cwd:void 0,codexPath:typeof $.codex?.defaultSettings?.codexPath==="string"?$.codex.defaultSettings.codexPath:void 0,env:$.codex?.defaultSettings?.env&&typeof $.codex.defaultSettings.env==="object"&&!Array.isArray($.codex.defaultSettings.env)?$.codex.defaultSettings.env:void 0});return Object.fromEntries(J.map((Q)=>[Q.id,uV(Q)]))}var s7={baseten:dV,hicap:lV,litellm:rV,"openai-codex":iV},r7=new Map,C6=new Map;function nV($,f){return`${$}:${h6(f.baseUrl)}`}async function aV($,f,J){let Q=s.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=v2(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=f?.cacheTtlMs??t7,j=nV($,J),X=Date.now(),H=r7.get(j);if(H&&H.expiresAt>X)return H.data;let Y=C6.get(j);if(Y)return Y;let V=m2(Z,$).then((A)=>{let B=Object.fromEntries(A.map((K)=>[K,Af(K,{name:K})]));return r7.set(j,{data:B,expiresAt:X+W}),B}).finally(()=>{C6.delete(j)});return C6.set(j,V),V}async function tV($,f){let J=b6(f);if(!J)return{};let Q=s7[$];if(!Q)return{};return Q(f,J)}function sV($,f,J){if(!J)return!1;if(!s7[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(b6(J))}async function oV($,f,J){let Q=f?.cacheTtlMs??t7,Z=vV($,J),W=Date.now(),j=E6.get(Z);if(j&&j.expiresAt>W)return j.data;let X=c2.get(Z);if(X)return X;let H=tV($,J).then((Y)=>{return E6.set(Z,{data:Y,expiresAt:W+Q}),Y}).finally(()=>{c2.delete(Z)});return c2.set(Z,H),H}async function eV($){return s.fetchModelsDevProviderModels($)}async function d2($={}){let f=$.url??a7,J=$.cacheTtlMs??bV,Q=Date.now(),Z=u2.get(f);if(Z&&Z.expiresAt>Q)return Z.data;let W=Vf.get(f);if(W)return W;let j=eV(f).then((X)=>{return u2.set(f,{data:X,expiresAt:Q+J}),X}).finally(()=>{Vf.delete(f)});return Vf.set(f,j),j}function $A($){if($){u2.delete($),Vf.delete($);return}u2.clear(),Vf.clear()}function fA(){E6.clear(),c2.clear()}function JA($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:n7(J.capabilities)}]))}var I6=JA(hV());function o7($){let f=EV($);if(!f||!f.baseUrl)return;return{baseUrl:f.baseUrl,modelId:f.modelId,knownModels:f.knownModels,capabilities:n7(f.capabilities)}}async function x6($,f,J){let Q=o7($);if(!Q)return;try{let Z=f?.loadLatestOnInit?await d2(f):void 0,W=Z?gV($,Z):{},j=J&&sV($,f,J)?await oV($,f,J):{},H=Boolean(s.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,Y=H?await aV($,f,H).catch(()=>({})):{},V=await xV($,Q.knownModels,W,j,Y,J?.knownModels);return{...Q,knownModels:V}}catch(Z){if(f?.failOnError)throw Z;return Q}}var g6=N0.BUILT_IN_PROVIDER,QA=N0.BUILT_IN_PROVIDER_IDS,ZA=N0.isBuiltInProviderId,l2=N0.normalizeProviderId,m6=N.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),e7=N.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),$Q=N.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),fQ=N.object({apiKey:N.string().optional(),accessToken:N.string().optional(),refreshToken:N.string().optional(),expiresAt:N.number().int().positive().optional(),accountId:N.string().optional()}),WA=N.enum(["none","low","medium","high","xhigh"]),JQ=N.object({enabled:N.boolean().optional(),effort:WA.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","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()}),XQ=N.object({mode:N.enum(["internal","external"]).optional(),usePromptCache:N.boolean().optional()}),HQ=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()}),E1=N.object({provider:m6,apiKey:N.string().optional(),auth:fQ.optional(),model:N.string().optional(),protocol:e7.optional(),client:$Q.optional(),routingProviderId:m6.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:XQ.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:HQ.optional()});function YQ($){return E1.parse($)}function VQ($){return E1.safeParse($)}function jA($){return $.protocol==="openai-responses"||$.client==="openai"}function f$($,f={}){let J=$.provider,Q=l2(J),Z=f.includeKnownModels!==!1,W=$.reasoning?.effort||"none",j=W==="none"?void 0:W,X=I6[Q],H=Object.assign({},...N0.resolveProviderModelCatalogKeys(Q).map((R)=>N0.getGeneratedModelsForProvider(R))),Y=Object.keys(H)[0],V=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,A=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?N6:T6:X?.baseUrl),B=$.routingProviderId??(jA($)&&Q!==g6.OPENAI_NATIVE?g6.OPENAI_NATIVE:void 0),K=Z?X?.knownModels??(Object.keys(H).length>0?H:void 0):void 0,G={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??Y??"default",...Z?{knownModels:K}:{},apiKey:V,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:A,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(G).filter(([R,F])=>F!==void 0))}function XA($){let f=YQ($);return f$(f)}function HA($){let f=VQ($);if(f.success)return{success:!0,config:f$(f.data)};return{success:!1,error:f.error}}import{SESSION_STATUS_VALUES as YA}from"@cline/shared";var v6=YA,G0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function AQ($){if($===!0)return{};if(!$)return;return $}function BQ($){if($==="user")return"global";return $}class c6{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function KQ($){let{host:f}=$;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:l2(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:BA(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:AA(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function p2($){let f=VA($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,W=$.context?.telemetry??$.telemetry;if(!f&&!J&&!Q&&!Z&&!W)return $.context;return{...$.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...f?{automation:f}:{}}}function VA($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function AA($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function BA($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as m8}from"node:fs";import{basename as i3,isAbsolute as kP,relative as IP}from"node:path";import{createHash as KA}from"node:crypto";import{watch as GA}from"node:fs";import{readdir as PA,readFile as FA}from"node:fs/promises";import{join as DA}from"node:path";function RA($){return KA("sha1").update($).digest("hex")}function FQ($){return Boolean($&&typeof $==="object"&&"code"in $)}function GQ($){return FQ($)&&$.code==="ENOENT"}function PQ($){return FQ($)&&($.code==="EACCES"||$.code==="EPERM")}class Bf{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=GA(f,()=>{let Q=this.watchedTypesByDirectory.get(f);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:f})})}catch(J){if(!GQ(J)&&!PQ(J)){let Q=$.get(f);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[Z,W]of Q.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:W.filePath})}for(let[Z,W]of f.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let Q of $.directories){J.add(Q);let Z=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:X}=W;if(J.add(W.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let H=await FA(X,"utf8"),Y={type:$.type,directoryPath:W.directoryPath,fileName:j,filePath:X,content:H},V=$.parseFile(Y),A=$.resolveId(V,Y).trim();if(!A)continue;f.set(A,{type:$.type,id:A,item:V,filePath:X,fingerprint:RA(H)})}catch(H){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:H,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=$.get(Q);if(Z)Z.add(f);else $.set(Q,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await PA($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:DA($,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch(f){if(GQ(f)||PQ(f))return[];throw f}}}import{readdir as u6,readFile as UA,stat as DQ}from"node:fs/promises";import{basename as t$,dirname as LA,extname as d6,join as U0}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as RQ,resolveRulesConfigSearchPaths as OA,resolveSkillsConfigSearchPaths as zA,resolveWorkflowsConfigSearchPaths as _A,SKILLS_CONFIG_DIRECTORY_NAME as l6,WORKFLOWS_CONFIG_DIRECTORY_NAME as p6}from"@cline/shared/storage";import yA from"yaml";var r2="SKILL.md",NA="managed.json",TA=new Set([".md",".markdown",".txt"]);function r6($){return $.trim().toLowerCase()}function Kf($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"}function i2($){return TA.has(d6($).toLowerCase())}async function i6($){try{let f=await u6($,{withFileTypes:!0}),J=[];for(let Q of f){if(!Q.isDirectory())continue;let Z=U0($,Q.name),W=U0(Z,NA);try{let j=await UA(W,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(Kf(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch(f){if(Kf(f))return[];throw f}}function n6($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=yA.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function n2($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let Q=$.trim();if(!Q&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return Q||void 0}function h1($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function a6($,f){let{data:J,body:Q,parseError:Z}=n6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let X=n2(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:n2(J.description,"description",!1),disabled:h1(J.disabled,"disabled")??(h1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function t6($,f){let{data:J,body:Q,parseError:Z}=n6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=n2(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:h1(J.disabled,"disabled")??(h1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function s6($,f){let{data:J,body:Q,parseError:Z}=n6($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=n2(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:h1(J.disabled,"disabled")??(h1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function o6($){return zA($)}function e6($){return OA($)}function $J($){return _A($)}async function UQ($){if(t$($)===".cline"){let f=await i6($);return(await Promise.all(f.map((Q)=>UQ(U0(Q,l6))))).flat()}try{let f=await u6($,{withFileTypes:!0}),J=[];for(let Q of f){if(Q.isFile()&&Q.name===r2){J.push({directoryPath:$,fileName:Q.name,filePath:U0($,Q.name)});continue}if(Q.isDirectory())J.push({directoryPath:U0($,Q.name),fileName:r2,filePath:U0($,Q.name,r2)})}return J}catch(f){if(Kf(f))return[];throw f}}async function a2($){if(t$($)===".cline"){let f=await i6($);return(await Promise.all(f.map((Q)=>a2(U0(Q,"rules.md"))))).flat()}try{if((await DQ($)).isFile())return[{directoryPath:LA($),fileName:t$($),filePath:$}]}catch(f){if(!Kf(f))throw f}try{let J=(await u6($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&i2(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:U0($,Z.name)})),Q=U0($,"AGENTS.md");try{if((await DQ(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch(f){if(Kf(f))return[];throw f}}async function MA($){if(t$($)===".cline"){let f=await i6($);return(await Promise.all(f.map((Q)=>a2(U0(Q,p6))))).flat()}return a2($)}function fJ($){let f=$?.directories??o6($?.workspacePath),J=$?.workspacePath?U0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...f,J]:f,discoverFiles:UQ,includeFile:(Q)=>Q===r2,parseFile:(Q)=>a6(Q.content,t$(Q.directoryPath)),resolveId:(Q)=>r6(Q.name)}}function JJ($){let f=$?.directories??e6($?.workspacePath),J=$?.workspacePath?U0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:a2,includeFile:(Q,Z)=>Q===".clinerules"||i2(Q)||i2(Z),parseFile:(Q)=>t6(Q.content,t$(Q.filePath,d6(Q.filePath))),resolveId:(Q)=>r6(Q.name)}}function QJ($){let f=$?.directories??$J($?.workspacePath),J=$?.workspacePath?U0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:MA,includeFile:(Q)=>i2(Q),parseFile:(Q)=>s6(Q.content,t$(Q.filePath,d6(Q.filePath))),resolveId:(Q)=>r6(Q.name)}}function LQ($){let f=[fJ($?.skills),JJ($?.rules),QJ($?.workflows)];return new Bf(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as OQ}from"@cline/shared";function qA($,f){if($.description?.trim())return OQ($.description,".");if(f==="workflow")return;return OQ($.instructions,".")}function wA($){return $.disabled!==!0}function zQ($,f){return[...$.getSnapshot(f).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>wA(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:qA(Q.item,f),kind:f})).sort((J,Q)=>J.name.localeCompare(Q.name))}function Gf($){let f=new Map;for(let J of[...zQ($,"workflow"),...zQ($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function _Q($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let Q=J[1];if(!Q)return $;let Z=Q.length+1,W=$.slice(Z),j=Gf(f).find((X)=>X.name===Q);return j?`${j.instructions}${W}`:$}function yQ($){return $.disabled!==!0}function t2($){if($.length===0)return"";return`
46
+ </html>`;function u7($){let f="";for(let J=0;J<$.length;J+=1)f+=String.fromCharCode($[J]??0);return btoa(f).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/g,"")}async function XV($){let J=new TextEncoder().encode($),Q=await crypto.subtle.digest("SHA-256",J);return new Uint8Array(Q)}function HV($=32){let f=new Uint8Array($);return crypto.getRandomValues(f),u7(f)}async function b8(){let $=HV(),f=u7(await XV($));return{verifier:$,challenge:f}}function k8($){return $.endsWith("/")?$.slice(0,-1):$}function t$($,f){return new URL(f,`${k8($)}/`).toString()}function S1($,f={}){let J=$.trim();if(!J)return{};try{let Q=new URL(J);return{code:Q.searchParams.get("code")??void 0,state:Q.searchParams.get("state")??void 0,provider:f.includeProvider?Q.searchParams.get("provider")??void 0:void 0}}catch{}if(f.allowHashCodeState&&J.includes("#")){let[Q,Z]=J.split("#",2);return{code:Q||void 0,state:Z||void 0}}if(J.includes("code=")){let Q=new URLSearchParams(J);return{code:Q.get("code")??void 0,state:Q.get("state")??void 0,provider:f.includeProvider?Q.get("provider")??void 0:void 0}}return{code:J}}function YV($){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 K0($){if(!$)return null;try{let f=$.split(".");if(f.length!==3)return null;let J=f[1];if(!J)return null;let Q=J.replace(/-/g,"+").replace(/_/g,"/"),Z=Q.padEnd(Q.length+(4-Q.length%4)%4,"="),W=YV(Z);if(!W)return null;return JSON.parse(W)}catch{return null}}function h1($){try{let f=JSON.parse($),J=f.error,Q=typeof J==="string"?J:J&&typeof J==="object"&&typeof J.type==="string"?J.type:void 0,Z=typeof f.error_description==="string"?f.error_description:typeof f.message==="string"?f.message:J&&typeof J==="object"&&typeof J.message==="string"?J.message:void 0;return{code:Q,message:Z}}catch{return{}}}function s$($,f){return Date.now()>=$.expires-f}async function C1($){if(!$.onManualCodeInput){let W=await $.waitForCallback();return{code:W?.code,state:W?.state,provider:W?.provider,error:W?.error}}let f,J,Q=$.onManualCodeInput().then((W)=>{f=W,$.cancelWait()}).catch((W)=>{J=W instanceof Error?W:Error(String(W)),$.cancelWait()}),Z=await $.waitForCallback();if(J)throw J;if(Z?.code||Z?.error)return{code:Z.code,state:Z.state,provider:Z.provider,error:Z.error};if(f)return S1(f,$.parseOptions);if(await Q,J)throw J;if(f)return S1(f,$.parseOptions);return{}}var I8={authorize:"/api/v1/auth/authorize",token:"/api/v1/auth/token",register:"/api/v1/auth/register",refresh:"/api/v1/auth/refresh"},p7={deviceAuthorization:"/user_management/authorize/device",authenticate:"/user_management/authenticate"},yf="https://api.workos.com",VV="/auth",c7=Array.from({length:11},($,f)=>48801+f),AV=300000,BV=30000,E1=30000,GV=300,KV=5;class D$ extends Error{status;errorCode;constructor($,f){super($);this.name="ClineOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid|expired|revoked|unauthorized/i.test(this.message);return!1}}function FV($){let f=Date.parse($);if(Number.isNaN(f))throw Error(`Invalid expiresAt value: ${$}`);return f}function wf($,f,J={}){let Q=$.userInfo.clineUserId??J.accountId,Z=$.refreshToken??J.refresh;if(!Z)throw Error("Token response did not include a refresh token");return{access:$.accessToken,refresh:Z,expires:FV($.expiresAt),accountId:Q??void 0,email:$.userInfo.email||J.email,metadata:{provider:f,tokenType:$.tokenType,userInfo:$.userInfo}}}async function Sf($){if(!$)return{};return typeof $==="function"?await $():$}function d7($,f){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return f;return Math.floor($)}async function l7($){await new Promise((f)=>setTimeout(f,$))}function hf($,f){if(!$.success||!$.data?.accessToken)throw Error(f);return $.data}async function r7($,f){let J=await fetch(t$(yf,p7.deviceAuthorization),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({client_id:$}),signal:AbortSignal.timeout(f?.requestTimeoutMs??E1)}),Q=await J.json().catch(()=>({}));if(!J.ok)throw new D$(`Device authorization failed: ${J.status}${Q.error_description?` - ${Q.error_description}`:""}`,{status:J.status,errorCode:Q.error});if(!Q.device_code||!Q.user_code||!Q.verification_uri)throw Error("Invalid WorkOS device authorization response");return{deviceCode:Q.device_code,userCode:Q.user_code,verificationUri:Q.verification_uri,verificationUriComplete:Q.verification_uri_complete,expiresInSeconds:d7(Q.expires_in,GV),pollIntervalSeconds:d7(Q.interval,KV)}}async function i7($){let f=Date.now()+$.expiresInSeconds*1000,J=Math.max(1,$.initialPollIntervalSeconds);while(Date.now()<=f){let Q=await fetch(t$($.workosApiBaseUrl,p7.authenticate),{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"urn:ietf:params:oauth:grant-type:device_code",device_code:$.deviceCode,client_id:$.clientId}),signal:AbortSignal.timeout($.requestTimeoutMs)}),Z=await Q.json().catch(()=>({}));if(Q.ok){if(!Z.access_token||!Z.refresh_token)throw Error("Invalid WorkOS token response");return{accessToken:Z.access_token,refreshToken:Z.refresh_token,tokenType:Z.token_type??"Bearer"}}switch(Z.error){case"authorization_pending":{await l7(J*1000);break}case"slow_down":{J+=1,await l7(J*1000);break}case"access_denied":case"expired_token":case"invalid_grant":throw new D$(Z.error_description||"WorkOS authorization failed",{status:Q.status,errorCode:Z.error});default:throw new D$(`WorkOS token polling failed: ${Q.status}${Z.error_description?` - ${Z.error_description}`:""}`,{status:Q.status,errorCode:Z.error})}$.onProgress?.("Waiting for browser authentication confirmation...")}throw Error("WorkOS device authorization timed out")}async function n7($,f,J){let Q={accessToken:$.accessToken,refreshToken:$.refreshToken},Z=await fetch(t$(f.apiBaseUrl,I8.register),{method:"POST",headers:{"Content-Type":"application/json",...await Sf(f.headers)},body:JSON.stringify(Q),signal:AbortSignal.timeout(f.requestTimeoutMs??E1)});if(!Z.ok){let j=await Z.text().catch(()=>""),X=h1(j);throw new D$(`Token registration failed: ${Z.status}${X.message?` - ${X.message}`:""}`,{status:Z.status,errorCode:X.code})}let W=await Z.json();return wf(hf(W,"Invalid token exchange response"),J??f.provider)}async function PV($,f,J,Q){let Z={grant_type:"authorization_code",code:$,client_type:"extension",redirect_uri:f,provider:Q??J.provider},W=await fetch(t$(J.apiBaseUrl,I8.token),{method:"POST",headers:{"Content-Type":"application/json",...await Sf(J.headers)},body:JSON.stringify(Z),signal:AbortSignal.timeout(J.requestTimeoutMs??E1)});if(!W.ok){let X=await W.text().catch(()=>""),H=h1(X);throw new D$(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let j=await W.json();return wf(hf(j,"Invalid token exchange response"),Q??J.provider)}async function x8($){K$($.telemetry,$.provider??"cline");let f=$.useWorkOSDeviceAuth??!0,J=$.callbackPorts?.length?$.callbackPorts:c7,Q=$.callbackPath??VV,Z=f?null:await e0({ports:J,callbackPath:Q,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),W=Z?.callbackUrl||`http://127.0.0.1:${J[0]??c7[0]}${Q}`;try{let j;if(f){let X=qf().workOsClientId,H=await r7(X,$);$.callbacks.onAuth({url:H.verificationUriComplete??H.verificationUri,instructions:`Enter this code in your browser: ${H.userCode}`});let Y=await i7({clientId:X,deviceCode:H.deviceCode,expiresInSeconds:H.expiresInSeconds,initialPollIntervalSeconds:H.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??E1,workosApiBaseUrl:yf,onProgress:$.callbacks.onProgress});j=await n7(Y,$,$.provider)}else{let X=new URL(t$($.apiBaseUrl,I8.authorize));X.searchParams.set("client_type","extension"),X.searchParams.set("callback_url",W),X.searchParams.set("redirect_uri",W),$.callbacks.onAuth({url:X.toString(),instructions:"Continue the authentication process in your browser."});let H,Y=$.provider,V=await C1({waitForCallback:Z?.waitForCallback??(async()=>null),cancelWait:Z?.cancelWait??(()=>{}),onManualCodeInput:$.callbacks.onManualCodeInput,parseOptions:{includeProvider:!0}});if(V.error)throw Error(`OAuth error: ${V.error}`);if(H=V.code,Y=V.provider??Y,!H){let A=await $.callbacks.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),B=S1(A,{includeProvider:!0});H=B.code,Y=B.provider??Y}if(!H)throw Error("Missing authorization code");j=await PV(H,W,$,Y)}return F$($.telemetry,$.provider??"cline"),U$($.telemetry,{id:j.accountId,email:j.email,provider:$.provider??"cline"}),j}catch(j){throw P$($.telemetry,$.provider??"cline",j instanceof Error?j.message:String(j)),j}finally{Z?.close()}}async function UV($){return await r7(qf().workOsClientId,$)}async function DV($){let f=$.provider??"cline";K$($.telemetry,f);try{let J=await i7({clientId:qf().workOsClientId,deviceCode:$.deviceCode,expiresInSeconds:$.expiresInSeconds,initialPollIntervalSeconds:$.pollIntervalSeconds,requestTimeoutMs:$.requestTimeoutMs??E1,workosApiBaseUrl:yf}),Q=await n7(J,{apiBaseUrl:$.apiBaseUrl,headers:$.headers,requestTimeoutMs:$.requestTimeoutMs,provider:$.provider},$.provider);return F$($.telemetry,f),U$($.telemetry,{id:Q.accountId,email:Q.email,provider:f}),Q}catch(J){throw P$($.telemetry,f,J instanceof Error?J.message:String(J)),J}}async function Cf($,f){let J=await fetch(t$(f.apiBaseUrl,I8.refresh),{method:"POST",headers:{"Content-Type":"application/json",...await Sf(f.headers)},body:JSON.stringify({refreshToken:$.refresh,grantType:"refresh_token"}),signal:AbortSignal.timeout(f.requestTimeoutMs??E1)});if(!J.ok){let W=await J.text().catch(()=>""),j=h1(W);throw new D$(`Token refresh failed: ${J.status}${j.message?` - ${j.message}`:""}`,{status:J.status,errorCode:j.code})}let Q=await J.json(),Z=$.metadata?.provider??f.provider;return wf(hf(Q,"Invalid token refresh response"),Z,$)}async function Ef($,f,J){if(!$)return null;let Q=J?.refreshBufferMs??AV,Z=J?.retryableTokenGraceMs??BV;if(J?.forceRefresh!==!0&&!s$($,Q))return $;try{return await Cf($,f)}catch(j){if(j instanceof D$&&j.isLikelyInvalidGrant())return n$(f.telemetry,f.provider??"cline","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function RV($){return{id:"cline",name:"Cline Account",usesCallbackServer:!($.useWorkOSDeviceAuth??!0),async login(f){return x8({...$,callbacks:f})},async refreshToken(f){return Cf(f,$)},getApiKey(f){return`workos:${f.access}`}}}G0();import{nanoid as LV}from"nanoid";var t={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 m8 extends Error{status;errorCode;constructor($,f){super($);this.name="OpenAICodexOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant/i.test(this.errorCode))return!0;if(this.status===400||this.status===401||this.status===403)return/invalid_grant|revoked|expired|invalid refresh/i.test(this.message);return!1}}async function OV($,f,J=t.redirectUri){let Q=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,code:$,code_verifier:f,redirect_uri:J}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!Q.ok)return{type:"failed"};let Z=await Q.json();if(!Z.access_token||!Z.refresh_token||typeof Z.expires_in!=="number")return{type:"failed"};return{type:"success",access:Z.access_token,refresh:Z.refresh_token,expires:Date.now()+Z.expires_in*1000,email:Z.email,idToken:Z.id_token}}async function zV($){try{let f=await fetch(t.tokenEndpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:$,client_id:t.clientId}),signal:AbortSignal.timeout(t.httpTimeoutMs)});if(!f.ok){let Q=await f.text().catch(()=>""),Z=h1(Q);throw new m8(`Token refresh failed: ${f.status}${Z.message?` - ${Z.message}`:""}`,{status:f.status,errorCode:Z.code})}let J=await f.json();if(!J.access_token||!J.refresh_token||typeof J.expires_in!=="number")return{type:"failed"};return{type:"success",access:J.access_token,refresh:J.refresh_token,expires:Date.now()+J.expires_in*1000,email:J.email,idToken:J.id_token}}catch(f){if(f instanceof m8)throw f;return{type:"failed"}}}async function _V($="pi"){let{verifier:f,challenge:J}=await b8(),Q=LV(32),Z=new URL(t.authorizationEndpoint);return Z.searchParams.set("response_type","code"),Z.searchParams.set("client_id",t.clientId),Z.searchParams.set("redirect_uri",t.redirectUri),Z.searchParams.set("scope",t.scopes),Z.searchParams.set("code_challenge",J),Z.searchParams.set("code_challenge_method","S256"),Z.searchParams.set("state",Q),Z.searchParams.set("id_token_add_organizations","true"),Z.searchParams.set("codex_cli_simplified_flow","true"),Z.searchParams.set("originator",$),{verifier:f,state:Q,url:Z.toString()}}function NV(){try{let $=new URL(t.redirectUri),f=$.port.length>0?Number.parseInt($.port,10):t.callbackPort;return{host:$.hostname||"localhost",port:Number.isFinite(f)?f:t.callbackPort,callbackPath:$.pathname||"/auth/callback",redirectUri:$.toString()}}catch{return{host:"localhost",port:t.callbackPort,callbackPath:"/auth/callback",redirectUri:t.redirectUri}}}function a7($,f){let J=f?K0(f):K0($),Q=J?J:K0($),W=Q?.[t.jwtClaimPath]?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;let j=Q?.organizations;if(Array.isArray(j)&&j.length>0){let H=j[0];if(typeof H?.id==="string"&&H.id.length>0)return H.id}let X=Q?.chatgpt_account_id;if(typeof X==="string"&&X.length>0)return X;return null}function t7($,f){let J=a7($.access,$.idToken)??f?.accountId;if(!J)throw Error("Failed to extract accountId from token");return{access:$.access,refresh:$.refresh||f?.refresh||"",expires:$.expires,accountId:J,email:$.email??f?.email,metadata:{...f?.metadata??{},provider:"openai-codex"}}}async function g8($){K$($.telemetry,"openai-codex");let f=NV(),{verifier:J,state:Q,url:Z}=await _V($.originator),W=await e0({host:f.host,ports:[f.port],callbackPath:f.callbackPath,expectedState:Q});$.onAuth({url:Z,instructions:"Continue the authentication process in your browser."});let j;try{let X=await C1({waitForCallback:W.waitForCallback,cancelWait:W.cancelWait,onManualCodeInput:$.onManualCodeInput,parseOptions:{allowHashCodeState:!0}});if(X.state&&X.state!==Q)throw Error("State mismatch");if(j=X.code,!j){let V=await $.onPrompt({message:"Paste the authorization code (or full redirect URL):"}),A=S1(V,{allowHashCodeState:!0});if(A.state&&A.state!==Q)throw Error("State mismatch");j=A.code}if(!j)throw Error("Missing authorization code");let H=await OV(j,J,f.redirectUri);if(H.type!=="success")throw Error("Token exchange failed");let Y=t7(H);return F$($.telemetry,"openai-codex"),U$($.telemetry,{id:Y.accountId,email:Y.email,provider:"openai-codex"}),Y}catch(X){throw P$($.telemetry,"openai-codex",X instanceof Error?X.message:String(X)),X}finally{W.close()}}async function bf($,f){let J=await zV($);if(J.type!=="success")throw Error("Failed to refresh OpenAI Codex token");let Q=t7(J,f);if(!Q.refresh)throw Error("Failed to refresh OpenAI Codex token: missing refresh token");return Q}async function kf($,f){if(!$)return null;let J=f?.refreshBufferMs??t.refreshBufferMs,Q=f?.retryableTokenGraceMs??t.retryableTokenGraceMs;if(f?.forceRefresh!==!0&&!s$($,J))return $;try{return await bf($.refresh,$)}catch(W){if(W instanceof m8&&W.isLikelyInvalidGrant())return n$(f?.telemetry,"openai-codex","invalid_grant"),null;if($.expires-Date.now()>Q)return $;return null}}function TV($,f=t.refreshBufferMs){return s$($,f)}function MV($){let f=$.accountId??a7($.access);if(!f)throw Error("Failed to extract accountId from token");return{...$,accountId:f,metadata:{...$.metadata??{},provider:"openai-codex"}}}var qV={id:"openai-codex",name:"ChatGPT Plus/Pro (ChatGPT Subscription)",usesCallbackServer:!0,async login($){return g8({onAuth:$.onAuth,onPrompt:$.onPrompt,onProgress:$.onProgress,onManualCodeInput:$.onManualCodeInput})},async refreshToken($){return bf($.refresh,$)},getApiKey($){return $.access}};G0();import{nanoid as s7}from"nanoid";class If{ttlMs;maxEntries;entries=new Map;constructor($,f){this.ttlMs=$;this.maxEntries=f}get($,f=Date.now()){this.pruneExpired(f);let J=this.entries.get($);if(!J)return;return this.entries.delete($),this.entries.set($,J),J.value}set($,f,J=Date.now(),Q=this.ttlMs){this.pruneExpired(J),this.entries.delete($);while(this.entries.size>=this.maxEntries){let Z=this.entries.keys().next().value;if(Z===void 0)break;this.entries.delete(Z)}this.entries.set($,{value:f,expiresAt:J+Q})}pruneExpired($){for(let[f,J]of this.entries)if(J.expiresAt<=$)this.entries.delete(f)}}var yV="a8331954c0cf48ba99b5dd223a14c6ea",wV="https://idcs-9dc693e80d9b469480d7afe00e743931.identity.oraclecloud.com",SV="openid offline_access",mf="https://code-internal.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",hV="c1aba3deed5740659981a752714eba33",CV="https://login-ext.identity.oraclecloud.com",EV="openid offline_access",gf="https://code.aiservice.us-chicago-1.oci.oraclecloud.com/20250206/app/litellm",bV="opc-request-id",kV="/auth/oca",IV=Array.from({length:11},($,f)=>48801+f),xV=300000,mV=30000,o7=30000,gV=600000;class v8 extends Error{status;errorCode;constructor($,f){super($);this.name="OcaOAuthTokenError",this.status=f?.status,this.errorCode=f?.errorCode}isLikelyInvalidGrant(){if(this.errorCode&&/invalid_grant|invalid_token|unauthorized/i.test(this.errorCode))return!0;return this.status===400||this.status===401||this.status===403}}var R$={internal:{clientId:yV,idcsUrl:wV,scopes:SV,baseUrl:mf},external:{clientId:hV,idcsUrl:CV,scopes:EV,baseUrl:gf}},B2=new Map,vV=86400000,uV=300000,cV=32,xf=new If(vV,cV);function e7($){if(typeof $==="function")return $();return $??"internal"}function $Q($){return{internal:{clientId:$?.internal?.clientId??R$.internal.clientId,idcsUrl:$?.internal?.idcsUrl??R$.internal.idcsUrl,scopes:$?.internal?.scopes??R$.internal.scopes,baseUrl:$?.internal?.baseUrl??R$.internal.baseUrl},external:{clientId:$?.external?.clientId??R$.external.clientId,idcsUrl:$?.external?.idcsUrl??R$.external.idcsUrl,scopes:$?.external?.scopes??R$.external.scopes,baseUrl:$?.external?.baseUrl??R$.external.baseUrl}}}function dV($=Date.now()){let f=$-gV;for(let[J,Q]of B2.entries())if(Q.createdAt<f)B2.delete(J)}function lV($,f,J){if(typeof $.expires_in==="number"&&$.expires_in>0)return Date.now()+$.expires_in*1000;let Z=K0(f)?.exp;if(typeof Z==="number"&&Z>0)return Z*1000;let j=K0(J)?.exp;if(typeof j==="number"&&j>0)return j*1000;return Date.now()+3600000}function fQ($,f,J){let Q=$.access_token;if(!Q)throw Error("Token response did not include an access token");let Z=$.refresh_token??J?.refresh;if(!Z)throw Error("Token response did not include a refresh token");let W=K0($.id_token),j=K0(Q),X=W?.sub??j?.sub,H=W?.email??j?.email;return{access:Q,refresh:Z,expires:lV($,Q,$.id_token),accountId:X??J?.accountId,email:H??J?.email,metadata:{...J?.metadata??{},provider:"oca",mode:f,subject:X,idToken:$.id_token}}}async function JQ($,f){let J=k8($),Q=xf.get(J);if(Q)return Q;let Z=`${J}/.well-known/openid-configuration`,W=await fetch(Z,{method:"GET",signal:AbortSignal.timeout(f)});if(!W.ok){let H=`${J}/oauth2/v1/token`;return xf.set(J,H,Date.now(),uV),H}let X=(await W.json()).token_endpoint||`${J}/oauth2/v1/token`;return xf.set(J,X),X}function QQ($){return{code:$.error,message:$.error_description}}async function pV($){let f=B2.get($.state);if(!f)throw Error("No PKCE verifier found for this state");B2.delete($.state);let J=$.mode==="external"?$.config.external:$.config.internal,Q=await JQ(J.idcsUrl,$.requestTimeoutMs),Z=new URLSearchParams({grant_type:"authorization_code",code:$.code,redirect_uri:f.redirectUri,client_id:J.clientId,code_verifier:f.verifier}),W=await fetch(Q,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:Z,signal:AbortSignal.timeout($.requestTimeoutMs)}),j=await W.json();if(!W.ok){let H=QQ(j);throw new v8(`Token exchange failed: ${W.status}${H.message?` - ${H.message}`:""}`,{status:W.status,errorCode:H.code})}let X=K0(j.id_token);if(!j.id_token||!X)throw Error("No ID token received from OCA");if(X.nonce!==f.nonce)throw Error("OIDC nonce verification failed");return fQ(j,$.mode)}function rV($){let f=$.mode==="external"?$.config.external:$.config.internal,J=new URL(`${k8(f.idcsUrl)}/oauth2/v1/authorize`);return J.searchParams.set("client_id",f.clientId),J.searchParams.set("response_type","code"),J.searchParams.set("scope",f.scopes),J.searchParams.set("code_challenge",$.challenge),J.searchParams.set("code_challenge_method","S256"),J.searchParams.set("redirect_uri",$.callbackUrl),J.searchParams.set("state",$.state),J.searchParams.set("nonce",$.nonce),J.toString()}async function u8($){K$($.telemetry,"oca");let f=$Q($.config),J=e7($.mode),Q=$.callbackPorts?.length?$.callbackPorts:IV,Z=$.callbackPath??kV,W=$.requestTimeoutMs??o7,j=await e0({ports:Q,callbackPath:Z,onListening:$.callbacks.onServerListening,onClose:$.callbacks.onServerClose}),X=j.callbackUrl;if(!X)throw Error("Unable to bind local OAuth callback server");let H=s7(16),Y=s7(16),{verifier:V,challenge:A}=await b8();dV(),B2.set(H,{verifier:V,nonce:Y,mode:J,redirectUri:X,createdAt:Date.now()});let B=rV({callbackUrl:X,mode:J,state:H,nonce:Y,challenge:A,config:f});$.callbacks.onAuth({url:B,instructions:"Continue the authentication process in your browser."});try{let G=await C1({waitForCallback:j.waitForCallback,cancelWait:j.cancelWait,onManualCodeInput:$.callbacks.onManualCodeInput}),K=G.code,D=G.state;if(G.error)throw Error(`OAuth error: ${G.error}`);if(!K){if(!$.callbacks.onManualCodeInput)throw Error("Timed out waiting for OCA callback");throw Error("Missing authorization code")}if(!D||D!==H)throw Error("State mismatch");let F=await pV({code:K,state:D,mode:J,config:f,requestTimeoutMs:W});return F$($.telemetry,"oca"),U$($.telemetry,{id:F.accountId,email:F.email,provider:"oca"}),F}catch(G){throw P$($.telemetry,"oca",G instanceof Error?G.message:String(G)),G}finally{j.close()}}async function vf($,f={}){let J=$Q(f.config),Q=f.requestTimeoutMs??o7,Z=$.metadata?.mode,W=Z==="internal"||Z==="external"?Z:e7(f.mode),j=W==="external"?J.external:J.internal,X=await JQ(j.idcsUrl,Q),H=new URLSearchParams({grant_type:"refresh_token",refresh_token:$.refresh,client_id:j.clientId}),Y=await fetch(X,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:H,signal:AbortSignal.timeout(Q)}),V=await Y.json();if(!Y.ok){let A=QQ(V);throw new v8(`Token refresh failed: ${Y.status}${A.message?` - ${A.message}`:""}`,{status:Y.status,errorCode:A.code})}return fQ(V,W,$)}async function uf($,f,J){if(!$)return null;let Q=f?.refreshBufferMs??J?.refreshBufferMs??xV,Z=f?.retryableTokenGraceMs??J?.retryableTokenGraceMs??mV;if(f?.forceRefresh!==!0&&!s$($,Q))return $;try{return await vf($,J)}catch(j){if(j instanceof v8&&j.isLikelyInvalidGrant())return n$(J?.telemetry,"oca","invalid_grant"),null;if($.expires-Date.now()>Z)return $;return null}}function iV($={}){return{id:"oca",name:"Oracle Code Assist",usesCallbackServer:!0,async login(f){return u8({...$,callbacks:f})},async refreshToken(f){return vf(f,$)},getApiKey(f){return f.access}}}async function ZQ($,f){let J=new TextEncoder,Q=async(Y)=>{let V=await crypto.subtle.digest("SHA-256",J.encode(Y));return Array.from(new Uint8Array(V).slice(0,4),(A)=>A.toString(16).padStart(2,"0")).join("")},[Z,W]=await Promise.all([Q(f),Q($)]),j=Math.floor(Date.now()/1000).toString(16).padStart(8,"0"),X=new Uint32Array(1);crypto.getRandomValues(X);let H=(X[0]??0).toString(16).padStart(8,"0");return Z+W+j+H}async function nV($){let f=await ZQ($.taskId,$.accessToken);return{Authorization:`Bearer ${$.accessToken}`,"Content-Type":"application/json",client:$.metadata?.client??"Cline","client-version":$.metadata?.clientVersion??"unknown","client-ide":$.metadata?.clientIde??"unknown","client-ide-version":$.metadata?.clientIdeVersion??"unknown",[bV]:f}}import*as y0 from"@cline/llms";import{z as T}from"zod";import*as $0 from"@cline/llms";function cf($){if(!Array.isArray($))return[];return $.map((f)=>{if(typeof f==="string")return f.trim();if(f&&typeof f==="object"){let J=f;for(let Q of[J.id,J.name,J.model])if(typeof Q==="string"&&Q.trim())return Q.trim()}return""}).filter((f)=>f.length>0)}function aV($,f){let J=cf($);if(J.length>0)return J;if(!$||typeof $!=="object")return[];let Q=$,Z=cf(Q.data??Q.models);if(Z.length>0)return Z;if(Q.models&&typeof Q.models==="object"&&!Array.isArray(Q.models)){let j=Object.keys(Q.models).filter((X)=>X.trim().length>0);if(j.length>0)return j}let W=Q.providers?.[f];if(W&&typeof W==="object"){let X=cf(W.models??W);if(X.length>0)return X}return[]}async function c8($,f){let J=await fetch($,{method:"GET"});if(!J.ok)throw Error(`failed to fetch models from ${$}: HTTP ${J.status}`);return aV(await J.json(),f)}function WQ($){return $.replace(/\/+$/,"")}function d8($,f,J){let Q=J?.trim();if(!Q)return;let Z=$?.trim();if(!Z||!f?.trim())return Q;try{let W=new URL(Q),j=new URL(f),X=new URL(Z);if(W.origin!==j.origin)return Q;let H=WQ(j.pathname),Y=WQ(X.pathname);if(H&&W.pathname.startsWith(`${H}/`)){let V=W.pathname.slice(H.length);X.pathname=`${Y}${V}`}else X.pathname=W.pathname;return X.search=W.search,X.hash=W.hash,X.toString()}catch{return Q}}function tV($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{...J}]))}function sV($){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 oV=Object.values($0.MODEL_COLLECTIONS_BY_PROVIDER_ID).map(($)=>({id:$.provider.id,baseUrl:$.provider.baseUrl??"",modelsSourceUrl:$.provider.modelsSourceUrl,modelId:$.provider.defaultModelId,knownModels:tV($.models),capabilities:$.provider.capabilities?[...$.provider.capabilities]:void 0,env:$.provider.env?[...$.provider.env]:void 0,client:$.provider.client,protocol:$.provider.protocol})),HQ=Object.fromEntries(oV.map(($)=>[$.id,$]));function eV($){return HQ[$]}function $A(){return Object.fromEntries(Object.entries(HQ).filter(([,$])=>sV($)))}function YQ($=[]){let f=$.flatMap((J)=>{switch(J){case"reasoning":case"prompt-cache":case"tools":case"oauth":return[J];default:return[]}});return f.length>0?f:void 0}var VQ="https://models.dev/api.json",fA=600000,AQ=300000,JA=5000,p8=new Map,G2=new Map,lf=new Map,l8=new Map;async function QA(){return $0.getGeneratedProviderModels()}async function ZA($,f={},J={},Q={},Z={},W={}){let j=await QA(),X=$0.resolveProviderModelCatalogKeys($),H=Object.assign({},...X.map((A)=>j[A]??{})),Y=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl),V=Object.keys(Z).length>0;if(Y&&V)return $0.sortModelsByReleaseDate({...Z,...W});if($==="openai-codex")return $0.sortModelsByReleaseDate({...f,...$0.filterOpenAICodexModels(J),...Z,...W});return $0.sortModelsByReleaseDate({...H,...f,...J,...Q,...Z,...W})}function WA($,f){let J=$0.resolveProviderModelCatalogKeys($);return Object.assign({},...J.map((Q)=>f[Q]??{}))}function r8($){let f=$?.trim();return f&&f.length>0?f:""}function pf($){let f=$.apiKey?.trim()||$.accessToken?.trim();return f&&f.length>0?f:void 0}function jA($){let f=2166136261;for(let J=0;J<$.length;J+=1)f^=$.charCodeAt(J),f+=(f<<1)+(f<<4)+(f<<7)+(f<<8)+(f<<24);return(f>>>0).toString(16)}function XA($,f){return`${$}:${r8(f.baseUrl)}:${jA(pf(f)??"")}`}async function i8($,f,J=JA){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await fetch($,{...f,signal:Q.signal})}finally{clearTimeout(Z)}}function o$($,f,J){if(J&&!$.includes(f))$.push(f)}function n8($,f){let J=["streaming","tools"];return o$(J,"images",Boolean(f.supportsImages)),o$(J,"prompt-cache",Boolean(f.supportsPromptCache)),o$(J,"reasoning",Boolean(f.supportsReasoning)),{id:$,name:f.name??$,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxTokens:f.maxTokens,capabilities:J,releaseDate:f.releaseDate,status:"active"}}async function HA($,f){let J=await i8("https://inference.baseten.co/v1/models",{method:"GET",headers:{Authorization:`Bearer ${f}`,"Content-Type":"application/json"}});if(!J.ok)throw Error(`Baseten model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;if(X.includes("whisper")||X.includes("tts")||X.includes("embedding"))continue;let H=j.supported_features??[];W[X]=n8(X,{name:X,contextWindow:j.context_length,maxInputTokens:j.context_length,maxTokens:j.max_completion_tokens,supportsReasoning:H.includes("reasoning")||H.includes("reasoning_effort"),supportsImages:!1})}return W}function jQ($){if(typeof $==="number")return Number.isFinite($)?$:void 0;if(typeof $==="string"){let f=Number($);return Number.isFinite(f)?f:void 0}return}async function YA($,f){let J=await i8("https://api.hicap.ai/v2/openai/models",{method:"GET",headers:{"api-key":f}});if(!J.ok)throw Error(`Hicap model refresh failed: HTTP ${J.status}`);let Z=(await J.json())?.data??[],W={};for(let j of Z){let X=j.id?.trim();if(!X)continue;W[X]=n8(X,{name:X,maxInputTokens:128000,supportsImages:!0,supportsPromptCache:!0})}return W}async function VA($,f){let Q=`${(r8($.baseUrl)||"https://inference.poolside.ai/v1").replace(/\/+$/,"")}/models`,Z=await i8(Q,{method:"GET",headers:{Authorization:`Bearer ${f}`,accept:"application/json"}});if(!Z.ok)throw Error(`Poolside model refresh failed: HTTP ${Z.status}`);let j=(await Z.json())?.data??[],X={};for(let H of j){let Y=H.id?.trim();if(!Y)continue;let V=H.supported_features??[],A=H.supported_sampling_parameters??[],B=H.input_modalities??[],G=["streaming"];o$(G,"tools",V.includes("tools")),o$(G,"reasoning",V.includes("reasoning")),o$(G,"temperature",A.includes("temperature")),o$(G,"images",B.includes("image"));let K={input:jQ(H.pricing?.prompt),output:jQ(H.pricing?.completion)};X[Y]={id:Y,name:H.name??Y,description:H.description,contextWindow:H.context_length,maxInputTokens:H.context_length,maxTokens:H.max_completion_tokens,capabilities:G,pricing:K.input!==void 0||K.output!==void 0?K:void 0,status:"active"}}return X}function AA($){let f=r8($);if(!f)return"http://localhost:4000";return f.endsWith("/v1")?f.slice(0,-3):f}async function BA($,f){let Q=`${AA($.baseUrl)}/v1/model/info`,Z=async(Y)=>i8(Q,{method:"GET",headers:{accept:"application/json",...Y}}),W=await Z({"x-litellm-api-key":f});if(!W.ok)W=await Z({Authorization:`Bearer ${f}`});if(!W.ok)throw Error(`LiteLLM model refresh failed: HTTP ${W.status}`);let X=(await W.json())?.data??[],H={};for(let Y of X){let V=Y.model_name?.trim(),B=Y.litellm_params?.model?.trim()||V;if(!B)continue;let G=Y.model_info,K=n8(B,{name:V??B,maxTokens:G?.max_output_tokens??G?.max_tokens,maxInputTokens:G?.max_input_tokens??G?.max_tokens,supportsImages:G?.supports_vision,supportsPromptCache:G?.supports_prompt_caching,supportsReasoning:G?.supports_reasoning});if(H[B]=K,V)H[V]={...K,id:V,name:V}}return H}var BQ={baseten:HA,hicap:YA,litellm:BA,poolside:VA},XQ=new Map,df=new Map;function GA($,f){return`${$}:${r8(f.baseUrl)}`}async function KA($,f,J){let Q=$0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$],Z=d8(J.baseUrl,Q?.provider.baseUrl,Q?.provider.modelsSourceUrl);if(!Z)return{};let W=f?.cacheTtlMs??AQ,j=GA($,J),X=Date.now(),H=XQ.get(j);if(H&&H.expiresAt>X)return H.data;let Y=df.get(j);if(Y)return Y;let V=c8(Z,$).then((A)=>{let B=Object.fromEntries(A.map((G)=>[G,n8(G,{name:G})]));return XQ.set(j,{data:B,expiresAt:X+W}),B}).finally(()=>{df.delete(j)});return df.set(j,V),V}async function FA($,f){let J=pf(f);if(!J)return{};let Q=BQ[$];if(!Q)return{};return Q(f,J)}function PA($,f,J){if(!J)return!1;if(!BQ[$])return!1;if(f?.loadPrivateOnAuth===!1)return!1;return Boolean(pf(J))}async function UA($,f,J){let Q=f?.cacheTtlMs??AQ,Z=XA($,J),W=Date.now(),j=lf.get(Z);if(j&&j.expiresAt>W)return j.data;let X=l8.get(Z);if(X)return X;let H=FA($,J).then((Y)=>{return lf.set(Z,{data:Y,expiresAt:W+Q}),Y}).finally(()=>{l8.delete(Z)});return l8.set(Z,H),H}async function DA($){return $0.fetchModelsDevProviderModels($,globalThis.fetch)}async function a8($={}){let f=$.url??VQ,J=$.cacheTtlMs??fA,Q=Date.now(),Z=p8.get(f);if(Z&&Z.expiresAt>Q)return Z.data;let W=G2.get(f);if(W)return W;let j=DA(f).then((X)=>{return p8.set(f,{data:X,expiresAt:Q+J}),X}).finally(()=>{G2.delete(f)});return G2.set(f,j),j}function RA($){if($){p8.delete($),G2.delete($);return}p8.clear(),G2.clear()}function LA(){lf.clear(),l8.clear()}function OA($){return Object.fromEntries(Object.entries($).map(([f,J])=>[f,{baseUrl:J.baseUrl,modelId:J.modelId,capabilities:YQ(J.capabilities)}]))}var rf=OA($A());function GQ($){let f=eV($);if(!f)return;return{baseUrl:f.baseUrl||void 0,modelId:f.modelId,knownModels:f.knownModels,capabilities:YQ(f.capabilities)}}async function nf($,f,J){let Q=GQ($);if(!Q)return;try{let Z=f?.loadLatestOnInit?await a8(f):void 0,W=Z?WA($,Z):{},j=J&&PA($,f,J)?await UA($,f,J):{},H=Boolean($0.MODEL_COLLECTIONS_BY_PROVIDER_ID[$]?.provider.modelsSourceUrl)?J??{providerId:$,modelId:Q.modelId,baseUrl:Q.baseUrl}:J,Y=H?await KA($,f,H).catch(()=>({})):{},V=await ZA($,Q.knownModels,W,j,Y,J?.knownModels);return{...Q,knownModels:V}}catch(Z){if(f?.failOnError)throw Z;return Q}}var af=y0.BUILT_IN_PROVIDER,zA=y0.BUILT_IN_PROVIDER_IDS,_A=y0.isBuiltInProviderId,t8=y0.normalizeProviderId,tf=T.string().min(1).regex(/^[a-z0-9][a-z0-9-]*$/i),KQ=T.enum(["anthropic","gemini","openai-chat","openai-responses","openai-r1","ai-sdk"]),FQ=T.enum(["anthropic","ai-sdk","ai-sdk-community","openai","openai-compatible","openai-r1","gemini","bedrock","custom","fetch","vertex"]),PQ=T.object({apiKey:T.string().optional(),accessToken:T.string().optional(),refreshToken:T.string().optional(),expiresAt:T.number().int().positive().optional(),accountId:T.string().optional()}),NA=T.enum(["none","low","medium","high","xhigh"]),UQ=T.object({enabled:T.boolean().optional(),effort:NA.optional(),budgetTokens:T.number().int().positive().optional()}),DQ=T.object({accessKey:T.string().optional(),secretKey:T.string().optional(),sessionToken:T.string().optional(),region:T.string().optional(),profile:T.string().optional(),authentication:T.enum(["iam","api-key","apikey","profile"]).optional(),usePromptCache:T.boolean().optional(),useCrossRegionInference:T.boolean().optional(),useGlobalInference:T.boolean().optional(),endpoint:T.string().url().optional(),customModelBaseId:T.string().optional()}),RQ=T.object({projectId:T.string().optional(),region:T.string().optional()}),LQ=T.object({apiVersion:T.string().optional(),useIdentity:T.boolean().optional()}),OQ=T.object({clientId:T.string().optional(),clientSecret:T.string().optional(),tokenUrl:T.string().url().optional(),resourceGroup:T.string().optional(),deploymentId:T.string().optional(),useOrchestrationMode:T.boolean().optional(),api:T.enum(["orchestration","foundation-models"]).optional(),defaultSettings:T.record(T.string(),T.unknown()).optional()}),zQ=T.object({mode:T.enum(["internal","external"]).optional(),usePromptCache:T.boolean().optional()}),_Q=T.object({loadLatestOnInit:T.boolean().optional(),loadPrivateOnAuth:T.boolean().optional(),url:T.string().url().optional(),cacheTtlMs:T.number().int().positive().optional(),failOnError:T.boolean().optional()}),b1=T.object({provider:tf,apiKey:T.string().optional(),auth:PQ.optional(),model:T.string().optional(),protocol:KQ.optional(),client:FQ.optional(),routingProviderId:tf.optional(),maxTokens:T.number().int().positive().optional(),contextWindow:T.number().int().positive().optional(),baseUrl:T.string().url().optional(),headers:T.record(T.string(),T.string()).optional(),timeout:T.number().int().positive().optional(),reasoning:UQ.optional(),aws:DQ.optional(),gcp:RQ.optional(),azure:LQ.optional(),sap:OQ.optional(),oca:zQ.optional(),region:T.string().optional(),apiLine:T.enum(["china","international"]).optional(),capabilities:T.array(T.enum(["reasoning","prompt-cache","streaming","tools","vision","computer-use","oauth","popular"])).optional(),modelCatalog:_Q.optional()});function NQ($){return b1.parse($)}function TQ($){return b1.safeParse($)}function TA($){return $.protocol==="openai-responses"||$.client==="openai"}function $$($,f={}){let J=$.provider,Q=t8(J),Z=f.includeKnownModels!==!1,W=$.reasoning?.effort||"none",j=W==="none"?void 0:W,X=rf[Q],H=Object.assign({},...y0.resolveProviderModelCatalogKeys(Q).map((D)=>y0.getGeneratedModelsForProvider(D))),Y=Object.keys(H)[0],V=$.auth?.accessToken??$.apiKey??$.auth?.apiKey,A=$.baseUrl??(Q==="oca"?$.oca?.mode==="internal"?mf:gf:X?.baseUrl),B=$.routingProviderId??(TA($)&&Q!==af.OPENAI_NATIVE?af.OPENAI_NATIVE:void 0),G=Z?X?.knownModels??(Object.keys(H).length>0?H:void 0):void 0,K={providerId:J,clientType:$.client,routingProviderId:B,modelId:$.model??X?.modelId??Y??"default",...Z?{knownModels:G}:{},apiKey:V,accessToken:$.auth?.accessToken,refreshToken:$.auth?.refreshToken,accountId:$.auth?.accountId,baseUrl:A,headers:$.headers,timeoutMs:$.timeout,maxOutputTokens:$.maxTokens,maxInputTokens:$.contextWindow,thinking:$.reasoning?.enabled,reasoningEffort:j,thinkingBudgetTokens:$.reasoning?.budgetTokens,region:$.region??$.aws?.region??$.gcp?.region,apiLine:$.apiLine,useCrossRegionInference:$.aws?.useCrossRegionInference,useGlobalInference:$.aws?.useGlobalInference,aws:$.aws?{accessKey:$.aws.accessKey,secretKey:$.aws.secretKey,sessionToken:$.aws.sessionToken,authentication:$.aws.authentication,profile:$.aws.profile,usePromptCache:$.aws.usePromptCache,endpoint:$.aws.endpoint,customModelBaseId:$.aws.customModelBaseId}:void 0,gcp:$.gcp?{projectId:$.gcp.projectId,region:$.gcp.region}:void 0,azure:$.azure,sap:$.sap,oca:$.oca,capabilities:$.capabilities??X?.capabilities,modelCatalog:$.modelCatalog?{loadLatestOnInit:$.modelCatalog.loadLatestOnInit,loadPrivateOnAuth:$.modelCatalog.loadPrivateOnAuth,url:$.modelCatalog.url,cacheTtlMs:$.modelCatalog.cacheTtlMs,failOnError:$.modelCatalog.failOnError}:void 0};return Object.fromEntries(Object.entries(K).filter(([D,F])=>F!==void 0))}function MA($){let f=NQ($);return $$(f)}function qA($){let f=TQ($);if(f.success)return{success:!0,config:$$(f.data)};return{success:!1,error:f.error}}import{SESSION_STATUS_VALUES as yA}from"@cline/shared";var sf=yA,wA=["idle","running","pending"];function SA($){return!wA.includes($)}function f0($){return!SA($)}var F0={CORE:"core",CLI:"cli",SUBAGENT:"subagent",DESKTOP:"desktop",KANBAN:"kanban",API:"api",WEB:"web",VSCODE:"vscode",ENTERPRISE:"enterprise",IDE:"ide",JETBRAINS:"jetbrains",NEOVIM:"neovim",UNKNOWN:"unknown"};function MQ($){if($===!0)return{};if(!$)return;return $}function qQ($){if($==="user")return"global";return $}class of{getService;constructor($){this.getService=$}async start(){await this.getService().start()}async stop(){await this.getService().stop()}async reconcileNow(){await this.getService().reconcileNow()}ingestEvent($){let f=this.getService().ingestEvent($);return{event:f.event,duplicate:f.duplicate,matchedSpecIds:f.matchedSpecs.map((J)=>J.specId),queuedRuns:f.queuedRuns,suppressions:f.suppressions}}listEvents($){return this.getService().listEventLogs($)}getEvent($){return this.getService().getEventLog($)}listSpecs($){return this.getService().listSpecs($)}listRuns($){return this.getService().listRuns($)}}function yQ($){let{host:f}=$;return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:t8(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:EA(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{extensionContext:$.getExtensionContext(),configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content),delivery:Q.delivery});if(!Z)throw Error("ClineCore automation runtime returned no result");return{result:CA(Z)}},async abortSession(J){return await f.abort(J,Error("ClineCore automation abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function s8($){let f=hA($.automationService,$.automation),J=$.context?.client??($.clientName?{name:$.clientName}:void 0),Q=$.context?.user??($.distinctId?{distinctId:$.distinctId}:void 0),Z=$.context?.logger??$.logger,W=$.context?.telemetry??$.telemetry;if(!f&&!J&&!Q&&!Z&&!W)return $.context;return{...$.context??{},...J?{client:J}:{},...Q?{user:Q}:{},...Z?{logger:Z}:{},...W?{telemetry:W}:{},...f?{automation:f}:{}}}function hA($,f){if(!$)return;return{ingestEvent:(J)=>{f.ingestEvent(J)}}}function CA($){return{text:$.text,usage:{inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost},inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function EA($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}import{existsSync as i4}from"node:fs";import{basename as YW,isAbsolute as DP,relative as RP}from"node:path";import{createHash as bA}from"node:crypto";import{watch as kA}from"node:fs";import{readdir as IA,readFile as xA}from"node:fs/promises";import{join as mA}from"node:path";function gA($){return bA("sha1").update($).digest("hex")}function hQ($){return Boolean($&&typeof $==="object"&&"code"in $)}function wQ($){return hQ($)&&$.code==="ENOENT"}function SQ($){return hQ($)&&($.code==="EACCES"||$.code==="EPERM")}class K2{definitions;debounceMs;emitParseErrors;listeners=new Set;recordsByType=new Map;watchersByDirectory=new Map;baseTypesByDirectory=new Map;watchedTypesByDirectory=new Map;discoveredDirectoriesByType=new Map;definitionsByType=new Map;pendingTypes=new Set;flushTimer;refreshQueue=Promise.resolve();started=!1;constructor($,f){if($.length===0)throw Error("UnifiedConfigFileWatcher requires at least one definition.");this.definitions=$,this.debounceMs=f?.debounceMs??75,this.emitParseErrors=f?.emitParseErrors??!1;for(let J of $){if(this.definitionsByType.has(J.type))throw Error(`Duplicate unified config definition type '${J.type}'.`);this.definitionsByType.set(J.type,J),this.recordsByType.set(J.type,new Map),this.discoveredDirectoriesByType.set(J.type,new Set);for(let Q of J.directories){let Z=this.baseTypesByDirectory.get(Q);if(Z)Z.add(J.type);else this.baseTypesByDirectory.set(Q,new Set([J.type]))}}}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}async start(){if(this.started)return;this.started=!0,await this.refreshAll(),this.startDirectoryWatchers()}stop(){if(this.started=!1,this.flushTimer)clearTimeout(this.flushTimer),this.flushTimer=void 0;this.pendingTypes.clear();for(let $ of this.watchersByDirectory.values())$.close();this.watchersByDirectory.clear(),this.watchedTypesByDirectory=new Map}async refreshAll(){await this.enqueueRefresh(async()=>{for(let $ of this.definitions)await this.refreshTypeInternal($)})}async refreshType($){let f=this.definitionsByType.get($);if(!f)throw Error(`Unknown unified config type '${$}'.`);await this.enqueueRefresh(async()=>{await this.refreshTypeInternal(f)})}getSnapshot($){let f=this.recordsByType.get($);return new Map([...f?.entries()??[]].map(([J,Q])=>[J,{...Q}]))}getAllSnapshots(){let $=new Map;for(let[f,J]of this.recordsByType.entries())$.set(f,new Map([...J.entries()].map(([Q,Z])=>[Q,{...Z}])));return $}emit($){for(let f of this.listeners)f($)}enqueueRefresh($){return this.refreshQueue=this.refreshQueue.then($,$),this.refreshQueue}startDirectoryWatchers(){this.syncDirectoryWatchers()}syncDirectoryWatchers(){let $=this.buildDesiredTypesByDirectory();for(let[f,J]of this.watchersByDirectory.entries()){if($.has(f))continue;J.close(),this.watchersByDirectory.delete(f)}this.watchedTypesByDirectory=$;for(let f of $.keys()){if(this.watchersByDirectory.has(f))continue;try{let J=kA(f,()=>{let Q=this.watchedTypesByDirectory.get(f);if(!Q)return;for(let Z of Q)this.pendingTypes.add(Z);this.scheduleFlush()});this.watchersByDirectory.set(f,J),J.on("error",(Q)=>{let Z=this.watchedTypesByDirectory.get(f);if(!Z)return;for(let W of Z)this.emit({kind:"error",type:W,error:Q,filePath:f})})}catch(J){if(!wQ(J)&&!SQ(J)){let Q=$.get(f);if(!Q)continue;for(let Z of Q)this.emit({kind:"error",type:Z,error:J,filePath:f})}}}}scheduleFlush(){if(this.flushTimer)clearTimeout(this.flushTimer);this.flushTimer=setTimeout(()=>{this.flushTimer=void 0;let $=[...this.pendingTypes];this.pendingTypes.clear(),this.enqueueRefresh(async()=>{for(let f of $){let J=this.definitionsByType.get(f);if(!J)continue;await this.refreshTypeInternal(J)}})},this.debounceMs)}async refreshTypeInternal($){let{records:f,discoveredDirectories:J}=await this.loadDefinition($),Q=this.recordsByType.get($.type)??new Map;for(let[Z,W]of Q.entries()){if(f.has(Z))continue;this.emit({kind:"remove",type:$.type,id:Z,filePath:W.filePath})}for(let[Z,W]of f.entries()){let j=Q.get(Z);if(j&&j.filePath===W.filePath&&j.fingerprint===W.fingerprint)continue;this.emit({kind:"upsert",record:{type:W.type,id:Z,item:W.item,filePath:W.filePath}})}if(this.recordsByType.set($.type,f),this.discoveredDirectoriesByType.set($.type,J),this.started)this.syncDirectoryWatchers()}async loadDefinition($){let f=new Map,J=new Set;for(let Q of $.directories){J.add(Q);let Z=$.discoverFiles?await $.discoverFiles(Q):await this.readDirectoryFileCandidates(Q);for(let W of Z){let{fileName:j,filePath:X}=W;if(J.add(W.directoryPath),$.includeFile&&!$.includeFile(j,X))continue;try{let H=await xA(X,"utf8"),Y={type:$.type,directoryPath:W.directoryPath,fileName:j,filePath:X,content:H},V=$.parseFile(Y),A=$.resolveId(V,Y).trim();if(!A)continue;f.set(A,{type:$.type,id:A,item:V,filePath:X,fingerprint:gA(H)})}catch(H){if(this.emitParseErrors)this.emit({kind:"error",type:$.type,error:H,filePath:X})}}}return{records:f,discoveredDirectories:J}}buildDesiredTypesByDirectory(){let $=new Map;for(let[f,J]of this.baseTypesByDirectory.entries())$.set(f,new Set(J));for(let[f,J]of this.discoveredDirectoriesByType.entries())for(let Q of J){let Z=$.get(Q);if(Z)Z.add(f);else $.set(Q,new Set([f]))}return $}async readDirectoryFileCandidates($){try{return(await IA($,{withFileTypes:!0})).filter((J)=>J.isFile()).map((J)=>({directoryPath:$,fileName:J.name,filePath:mA($,J.name)})).sort((J,Q)=>J.fileName.localeCompare(Q.fileName))}catch(f){if(wQ(f)||SQ(f))return[];throw f}}}import{readdir as ef,readFile as vA,stat as CQ}from"node:fs/promises";import{basename as e$,dirname as uA,extname as $J,join as O0}from"node:path";import{RULES_CONFIG_DIRECTORY_NAME as EQ,resolveRulesConfigSearchPaths as cA,resolveSkillsConfigSearchPaths as dA,resolveWorkflowsConfigSearchPaths as lA,SKILLS_CONFIG_DIRECTORY_NAME as fJ,WORKFLOWS_CONFIG_DIRECTORY_NAME as JJ}from"@cline/shared/storage";import pA from"yaml";var o8="SKILL.md",rA="managed.json",iA=new Set([".md",".markdown",".txt"]);function QJ($){return $.trim().toLowerCase()}function F2($){let f=$;return f?.code==="ENOENT"||f?.code==="EACCES"||f?.code==="EPERM"}function e8($){return iA.has($J($).toLowerCase())}async function ZJ($){try{let f=await ef($,{withFileTypes:!0}),J=[];for(let Q of f){if(!Q.isDirectory())continue;let Z=O0($,Q.name),W=O0(Z,rA);try{let j=await vA(W,"utf8"),X=JSON.parse(j);if(X&&typeof X==="object")J.push(Z)}catch(j){if(F2(j))continue;if(j?.name==="SyntaxError")continue;throw j}}return J.sort((Q,Z)=>Q.localeCompare(Z))}catch(f){if(F2(f))return[];throw f}}function WJ($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J;try{let W=pA.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}catch(W){let j=W instanceof Error?W.message:String(W);return{data:{},body:$,hadFrontmatter:!0,parseError:j}}}function $4($,f,J){if($===void 0||$===null){if(J)throw Error(`Missing required frontmatter field '${f}'.`);return}if(typeof $!=="string")throw Error(`Frontmatter field '${f}' must be a string.`);let Q=$.trim();if(!Q&&J)throw Error(`Frontmatter field '${f}' cannot be empty.`);return Q||void 0}function k1($,f){if($===void 0||$===null)return;if(typeof $!=="boolean")throw Error(`Frontmatter field '${f}' must be a boolean.`);return $}function jJ($,f){let{data:J,body:Q,parseError:Z}=WJ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in skill file.");let X=$4(J.name,"name",!1)??f.trim();if(!X)throw Error("Missing skill name.");return{name:X,description:$4(J.description,"description",!1),disabled:k1(J.disabled,"disabled")??(k1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function XJ($,f){let{data:J,body:Q,parseError:Z}=WJ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in rule file.");let j=$4(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing rule name.");return{name:j,disabled:k1(J.disabled,"disabled")??(k1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function HJ($,f){let{data:J,body:Q,parseError:Z}=WJ($);if(Z)throw Error(`Failed to parse YAML frontmatter: ${Z}`);let W=Q.trim();if(!W)throw Error("Missing instructions body in workflow file.");let j=$4(J.name,"name",!1)??f.trim();if(!j)throw Error("Missing workflow name.");return{name:j,disabled:k1(J.disabled,"disabled")??(k1(J.enabled,"enabled")===!1?!0:void 0),instructions:W,frontmatter:J}}function YJ($){return dA($)}function VJ($){return cA($)}function AJ($){return lA($)}async function bQ($){if(e$($)===".cline"){let f=await ZJ($);return(await Promise.all(f.map((Q)=>bQ(O0(Q,fJ))))).flat()}try{let f=await ef($,{withFileTypes:!0}),J=[];for(let Q of f){if(Q.isFile()&&Q.name===o8){J.push({directoryPath:$,fileName:Q.name,filePath:O0($,Q.name)});continue}if(Q.isDirectory())J.push({directoryPath:O0($,Q.name),fileName:o8,filePath:O0($,Q.name,o8)})}return J}catch(f){if(F2(f))return[];throw f}}async function f4($){if(e$($)===".cline"){let f=await ZJ($);return(await Promise.all(f.map((Q)=>f4(O0(Q,"rules.md"))))).flat()}try{if((await CQ($)).isFile())return[{directoryPath:uA($),fileName:e$($),filePath:$}]}catch(f){if(!F2(f))throw f}try{let J=(await ef($,{withFileTypes:!0})).filter((Z)=>Z.isFile()&&e8(Z.name)).map((Z)=>({directoryPath:$,fileName:Z.name,filePath:O0($,Z.name)})),Q=O0($,"AGENTS.md");try{if((await CQ(Q)).isFile()){if(!J.some((j)=>j.fileName==="AGENTS.md"))J.push({directoryPath:$,fileName:"AGENTS.md",filePath:Q})}}catch{}return J}catch(f){if(F2(f))return[];throw f}}async function nA($){if(e$($)===".cline"){let f=await ZJ($);return(await Promise.all(f.map((Q)=>f4(O0(Q,JJ))))).flat()}return f4($)}function BJ($){let f=$?.directories??YJ($?.workspacePath),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"skill",directories:J?[...f,J]:f,discoverFiles:bQ,includeFile:(Q)=>Q===o8,parseFile:(Q)=>jJ(Q.content,e$(Q.directoryPath)),resolveId:(Q)=>QJ(Q.name)}}function GJ($){let f=$?.directories??VJ($?.workspacePath),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"rule",directories:J?[...f,J]:f,discoverFiles:f4,includeFile:(Q,Z)=>Q===".clinerules"||e8(Q)||e8(Z),parseFile:(Q)=>XJ(Q.content,e$(Q.filePath,$J(Q.filePath))),resolveId:(Q)=>QJ(Q.name)}}function KJ($){let f=$?.directories??AJ($?.workspacePath),J=$?.workspacePath?O0($.workspacePath,".cline"):void 0;return{type:"workflow",directories:J?[...f,J]:f,discoverFiles:nA,includeFile:(Q)=>e8(Q),parseFile:(Q)=>HJ(Q.content,e$(Q.filePath,$J(Q.filePath))),resolveId:(Q)=>QJ(Q.name)}}function kQ($){let f=[BJ($?.skills),GJ($?.rules),KJ($?.workflows)];return new K2(f,{debounceMs:$?.debounceMs,emitParseErrors:$?.emitParseErrors})}import{truncateSplit as IQ}from"@cline/shared";function aA($,f){if($.description?.trim())return IQ($.description,".");if(f==="workflow")return;return IQ($.instructions,".")}function tA($){return $.disabled!==!0}function xQ($,f){return[...$.getSnapshot(f).entries()].map(([J,Q])=>({id:J,record:Q})).filter(({record:J})=>tA(J.item)).map(({id:J,record:Q})=>({id:J,name:Q.item.name,instructions:Q.item.instructions,description:aA(Q.item,f),kind:f})).sort((J,Q)=>J.name.localeCompare(Q.name))}function P2($){let f=new Map;for(let J of[...xQ($,"workflow"),...xQ($,"skill")])if(!f.has(J.name))f.set(J.name,J);return[...f.values()].sort((J,Q)=>J.name.localeCompare(Q.name))}function mQ($,f){if(!$.startsWith("/")||$.length<2)return $;let J=$.match(/^\/(\S+)/);if(!J)return $;let Q=J[1];if(!Q)return $;let Z=Q.length+1,W=$.slice(Z),j=P2(f).find((X)=>X.name===Q);return j?`${j.instructions}${W}`:$}function gQ($){return $.disabled!==!0}function J4($){if($.length===0)return"";return`
47
47
 
48
48
  # Rules
49
49
  ${$.map((J)=>`## ${J.name}
50
50
  ${J.instructions}`).join(`
51
51
 
52
- `)}`}function s2($,f){let J=$?.trim(),Q=f?.trim();if(J&&Q)return`${J}
52
+ `)}`}function Q4($,f){let J=$?.trim(),Q=f?.trim();if(J&&Q)return`${J}
53
53
 
54
- ${Q}`;return J||Q||void 0}function SA($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(yQ).sort((J,Q)=>J.name.localeCompare(Q.name))}function NQ($){return t2(SA($))}import{validateWithZod as Yw,zodToJsonSchema as Vw}from"@cline/shared";var Z0={READ_FILES:"read_files",SEARCH_CODEBASE:"search_codebase",RUN_COMMANDS:"run_commands",FETCH_WEB_CONTENT:"fetch_web_content",APPLY_PATCH:"apply_patch",EDITOR:"editor",SKILLS:"skills",ASK:"ask_question",SUBMIT_AND_EXIT:"submit_and_exit"},b1=[Z0.READ_FILES,Z0.SEARCH_CODEBASE,Z0.RUN_COMMANDS,Z0.FETCH_WEB_CONTENT,Z0.APPLY_PATCH,Z0.EDITOR,Z0.SKILLS,Z0.ASK,Z0.SUBMIT_AND_EXIT];import{createTool as J$,validateWithZod as z$,zodToJsonSchema as l0}from"@cline/shared";import{validateWithZod as bQ}from"@cline/shared";import{z as U}from"zod";var L$=6000,ZJ=U.string().describe("The absolute file path of a text file to read content from"),TQ=U.object({start_line:U.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:U.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),s$=U.object({path:ZJ,start_line:TQ.shape.start_line,end_line:TQ.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),o2=U.object({files:U.array(s$).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),MQ=U.union([o2,s$,U.array(s$),U.array(U.string()),U.string(),U.object({files:s$}),U.object({file_paths:U.array(ZJ)}),U.object({file_paths:U.string()}),U.object({paths:U.array(U.union([ZJ,s$]))}),U.object({paths:s$}),U.object({paths:U.string()})]),e2=U.object({queries:U.array(U.string()).describe("Array of regex search queries to execute")}),qQ=U.union([e2,U.array(U.string()),U.string(),U.object({queries:U.string()})]),o$=U.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${L$*2} characters) to avoid timeouts.`),Pf=U.object({commands:U.array(o$).describe("Array of shell commands to execute")}),wQ=U.union([Pf,U.object({commands:o$}),U.object({command:o$}),U.object({cmd:o$}),U.array(U.string()),U.string()]),WJ=U.object({command:U.string().min(1).describe("The executable to run directly without shell parsing."),args:U.array(U.string()).optional().describe("Optional argv list passed directly to the executable.")}),SQ=U.union([o$,WJ]),jJ=U.object({commands:U.array(SQ).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.")}),CQ=U.union([Pf,jJ,U.object({commands:SQ}),U.array(WJ),WJ,U.object({command:o$}),U.object({cmd:o$}),U.array(U.string()),U.string()]),EQ=U.object({url:U.string().describe("The URL to fetch"),prompt:U.string().min(2).describe("Analysis prompt for the fetched content")}),$8=U.object({requests:U.array(EQ).describe("Array of the URLs for the web fetch requests")}),f8=U.object({path:U.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:U.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 ${L$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:U.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 ${L$} 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:U.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),J8=U.object({input:U.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."),hQ=U.union([J8,U.string()]),Q8=U.object({skill:U.string().min(1).describe("Name of the skill to execute."),args:U.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),Z8=U.object({question:U.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:U.array(U.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),W8=U.object({summary:U.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:U.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
54
+ ${Q}`;return J||Q||void 0}function sA($){return[...$.getSnapshot("rule").values()].map((J)=>J.item).filter(gQ).sort((J,Q)=>J.name.localeCompare(Q.name))}function vQ($){return J4(sA($))}import{validateWithZod as aw,zodToJsonSchema as tw}from"@cline/shared";var W0={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"},I1=[W0.READ_FILES,W0.SEARCH_CODEBASE,W0.RUN_COMMANDS,W0.FETCH_WEB_CONTENT,W0.APPLY_PATCH,W0.EDITOR,W0.SKILLS,W0.ASK,W0.SUBMIT_AND_EXIT];import{createTool as f$,validateWithZod as z$,zodToJsonSchema as p0}from"@cline/shared";import{validateWithZod as aQ}from"@cline/shared";import{z as O}from"zod";var L$=6000,FJ=O.string().describe("The absolute file path of a text file to read content from"),uQ=O.object({start_line:O.number().int().positive().nullable().optional().describe("Optional one-based starting line number to read from; use null or omit for the start of the file"),end_line:O.number().int().positive().nullable().optional().describe("Optional one-based ending line number to read through; use null or omit for the end of the file")}).describe("Optional inclusive one-based file line range"),$1=O.object({path:FJ,start_line:uQ.shape.start_line,end_line:uQ.shape.end_line}).describe("A file read request with optional inclusive one-based line bounds"),Z4=O.object({files:O.array($1).describe("Array of file read requests. Omit start_line/end_line or set them to null to return the full file content boundaries; provide integers to return only that inclusive one-based line range. Prefer this tool over running terminal command to get file content for better performance and reliability.")}),cQ=O.union([Z4,$1,O.array($1),O.array(O.string()),O.string(),O.object({files:$1}),O.object({file_paths:O.array(FJ)}),O.object({file_paths:O.string()}),O.object({paths:O.array(O.union([FJ,$1]))}),O.object({paths:$1}),O.object({paths:O.string()})]),W4=O.object({queries:O.array(O.string()).describe("Array of regex search queries to execute")}),dQ=O.union([W4,O.array(O.string()),O.string(),O.object({queries:O.string()})]),f1=O.string().describe(`The non-interactive shell command to execute - MUST keep input short and concise (within ${L$*2} characters) to avoid timeouts.`),U2=O.object({commands:O.array(f1).describe("Array of shell commands to execute")}),lQ=O.union([U2,O.object({commands:f1}),O.object({command:f1}),O.object({cmd:f1}),O.array(O.string()),O.string()]),PJ=O.object({command:O.string().min(1).describe("The executable to run directly without shell parsing."),args:O.array(O.string()).optional().describe("Optional argv list passed directly to the executable.")}),pQ=O.union([f1,PJ]),UJ=O.object({commands:O.array(pQ).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.")}),rQ=O.union([U2,UJ,O.object({commands:pQ}),O.array(PJ),PJ,O.object({command:f1}),O.object({cmd:f1}),O.array(O.string()),O.string()]),iQ=O.object({url:O.string().describe("The URL to fetch"),prompt:O.string().min(2).describe("Analysis prompt for the fetched content")}),j4=O.object({requests:O.array(iQ).describe("Array of the URLs for the web fetch requests")}),X4=O.object({path:O.string().min(1).describe("The absolute file path for the action to be performed on"),old_text:O.string().nullable().optional().describe(`Exact text to replace (must match exactly once). Omit this when creating a missing file or inserting via insert_line. Keep this at or below ${L$} characters when possible; larger payloads should be split across multiple tool calls to avoid timeouts.`),new_text:O.string().describe(`The new content to write when creating a missing file, the replacement text for edits, or the inserted text when insert_line is provided. Keep this at or below ${L$} characters when possible; for large edits, use multiple calls with small chunks of old_text and new_text to iteratively edit the file.`),insert_line:O.number().int().nullable().optional().describe("Optional positive one-based boundary line. When provided, the tool inserts new_text before that line instead of performing a replacement edit; use line_count + 1 to append at EOF.")}).describe("Edit a text file by replacing old_text with new_text, create the file with new_text if it does not exist, or insert new_text at insert_line when insert_line is provided. Prefer using this tool for file edits over shell commands. IMPORTANT: large edits can time out, so use small chunks and multiple calls when possible."),H4=O.object({input:O.string().min(1).describe("The freeform apply_patch payload in the canonical patch grammar (e.g *** Begin Patch, *** Update File:, @@, and *** End Patch).")}).describe("Modify or create a text file by applying patches using the canonical apply_patch diff grammar. Prefer sending the patch body directly rather than wrapping it in shell syntax. IMPORTANT: large patches can time out, so use small chunks and multiple calls when possible."),nQ=O.union([H4,O.string()]),Y4=O.object({skill:O.string().min(1).describe("Name of the skill to execute."),args:O.string().nullable().optional().describe("Arguments for the skill; use null when omitted")}),V4=O.object({question:O.string().min(1).describe('The single question to ask the user. E.g. "How can I help you?"'),options:O.array(O.string().min(1)).min(2).max(5).describe("Array of 2-5 user-selectable answer options for the single question")}),A4=O.object({summary:O.string().min(10).describe("Summarization of the investigation, steps taken, and resolution status to submit at the end of the session. Before submitting, read the problem again along with any provided test's assertions carefully and confirm your fix produces the expected output."),verified:O.boolean().describe(`Have you verified that the issue is resolved to the best of your knowledge, including updating and creating all the requested files and items? 'True' if you have completed the investigation and taken all necessary steps to resolve the issue.
55
55
  'False' if you have done all you can but cannot resolve the issue or if you are stuck and cannot proceed further. =
56
- IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function O$($){if($ instanceof Error)return $.message;return String($)}function kQ($){if(typeof $.old_text==="string"&&$.old_text.length>L$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${L$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>L$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${L$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function d0($,f,J){return Promise.race([$,new Promise((Q,Z)=>{setTimeout(()=>Z(Error(J)),f)})])}function IQ($){let f=bQ(MQ,$);if(typeof f==="string")return[{path:f}];if(Array.isArray(f))return f.map((J)=>typeof J==="string"?{path:J}:J);if("files"in f)return Array.isArray(f.files)?f.files:[f.files];if("file_paths"in f)return(Array.isArray(f.file_paths)?f.file_paths:[f.file_paths]).map((Q)=>({path:Q}));if("paths"in f)return(Array.isArray(f.paths)?f.paths:[f.paths]).map((Q)=>typeof Q==="string"?{path:Q}:Q);return[f]}function j8($){let{path:f,start_line:J,end_line:Q}=$;if(J==null&&Q==null)return f;return`${f}:${J??1}-${Q??"EOF"}`}function xQ($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function gQ($){let f=bQ(CQ,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function XJ($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${J.join(" ")}`}function mQ($,f={}){let J=f.fileReadTimeoutMs??1e4;return J$({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Returns file contents or error messages for each path.",inputSchema:l0(o2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=IQ(Q);return Promise.all(W.map(async(j)=>{let X=xQ(j);if(X)return{query:j8(j),result:"",error:`Invalid file range: ${X}`,success:!1};try{let H=await d0($(j,Z),J,`File read timed out after ${J}ms`);return{query:j8(j),result:H,success:!0}}catch(H){let Y=O$(H);return{query:j8(j),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function vQ($,f={}){let J=f.searchTimeoutMs??30000,Q=f.cwd??process.cwd();return J$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:l0(e2),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=z$(qQ,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(H)=>{try{let Y=await d0($(H,Q,W),J,`Search timed out after ${J}ms`),V=Y.length>0&&!Y.includes("No results found");return{query:H,result:Y,success:V}}catch(Y){let V=O$(Y);return{query:H,result:"",error:`Search failed: ${V}`,success:!1}}}))}})}function cQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.cwd??process.cwd();return J$({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.",inputSchema:l0(Pf),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(wQ,Z),X;if(typeof j==="string")X=[j];else if(Array.isArray(j))X=j;else if("commands"in j)X=Array.isArray(j.commands)?j.commands:[j.commands];else if("command"in j)X=[j.command];else X=[j.cmd];return Promise.all(X.map(async(H)=>{try{let Y=await d0($(H,Q,W),J,`Command timed out after ${J}ms`);return{query:H,result:Y,success:!0}}catch(Y){let V=O$(Y);return{query:H,result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function uQ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.cwd??process.cwd();return J$({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:l0(jJ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=gQ(Z);return Promise.all(j.map(async(X)=>{try{let H=await d0($(X,Q,W),J,`Command timed out after ${J}ms`);return{query:XJ(X),result:H,success:!0}}catch(H){let Y=O$(H);return{query:XJ(X),result:"",error:`Command failed: ${Y}`,success:!1}}}))}})}function dQ($,f={}){let J=f.webFetchTimeoutMs??30000;return J$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:l0($8),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=z$($8,Q);return Promise.all(W.requests.map(async(j)=>{try{let X=await d0($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let H=O$(X);return{query:j.url,result:"",error:`Error fetching web content: ${H}`,success:!1}}}))}})}var CA=`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:
56
+ IMPORTANT: You must run the specific failing test(s) mentioned in the issue or test patch and include the test output in your reasoning. If the test still fails after your fix, you must revise. Do NOT submit with 'true' unless the test output shows the test passing.`)});function O$($){if($ instanceof Error)return $.message;return String($)}function tQ($){if(typeof $.old_text==="string"&&$.old_text.length>L$)return`Editor input too large: old_text was ${$.old_text.length} characters, exceeding the recommended limit of ${L$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;if($.new_text.length>L$)return`Editor input too large: new_text was ${$.new_text.length} characters, exceeding the recommended limit of ${L$}. Split the edit into smaller tool calls so later tool calls are less likely to be truncated or time out.`;return null}function l0($,f,J){return Promise.race([$,new Promise((Q,Z)=>{setTimeout(()=>Z(Error(J)),f)})])}function sQ($){let f=aQ(cQ,$);if(typeof f==="string")return[{path:f}];if(Array.isArray(f))return f.map((J)=>typeof J==="string"?{path:J}:J);if("files"in f)return Array.isArray(f.files)?f.files:[f.files];if("file_paths"in f)return(Array.isArray(f.file_paths)?f.file_paths:[f.file_paths]).map((Q)=>({path:Q}));if("paths"in f)return(Array.isArray(f.paths)?f.paths:[f.paths]).map((Q)=>typeof Q==="string"?{path:Q}:Q);return[f]}function B4($){let{path:f,start_line:J,end_line:Q}=$;if(J==null&&Q==null)return f;return`${f}:${J??1}-${Q??"EOF"}`}function oQ($){let{start_line:f,end_line:J}=$;if(f==null||J==null||f<=J)return null;return`start_line must be less than or equal to end_line (received start_line: ${f}, end_line: ${J})`}function eQ($){let f=aQ(rQ,$);if(typeof f==="string")return[f];if(Array.isArray(f))return f;if("commands"in f)return Array.isArray(f.commands)?f.commands:[f.commands];if("command"in f)return"args"in f?[f]:[f.command];if("cmd"in f)return[f.cmd];return[f]}function DJ($){if(typeof $==="string")return $;let f=$.args??[];if(f.length===0)return $.command;let J=f.map((Q)=>/[\s"]/u.test(Q)?JSON.stringify(Q):Q);return`${$.command} ${J.join(" ")}`}function $Z($,f={}){let J=f.fileReadTimeoutMs??1e4;return f$({name:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided. Binary files that are not image and large files are not supported. Returns file contents or error messages for each path. ",inputSchema:p0(Z4),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Q,Z)=>{let W=sQ(Q);return Promise.all(W.map(async(j)=>{let X=oQ(j);if(X)return{query:B4(j),result:"",error:`Invalid file range: ${X}`,success:!1};try{let H=await l0($(j,Z),J,`File read timed out after ${J}ms`);return{query:B4(j),result:H,success:!0}}catch(H){let Y=O$(H);return{query:B4(j),result:"",error:`Error reading file: ${Y}`,success:!1}}}))}})}function fZ($,f={}){let J=f.searchTimeoutMs??30000,Q=f.cwd??process.cwd();return f$({name:"search_codebase",description:"Perform regex pattern searches across the codebase. Supports multiple parallel searches. Use for finding code patterns, function definitions, class names, imports, etc.",inputSchema:p0(W4),timeoutMs:J*2,retryable:!0,maxRetries:1,execute:async(Z,W)=>{let j=z$(dQ,Z),X=Array.isArray(j)?j:typeof j==="object"?Array.isArray(j.queries)?j.queries:[j.queries]:[j];return Promise.all(X.map(async(H)=>{try{let Y=await l0($(H,Q,W),J,`Search timed out after ${J}ms`),V=Y.length>0&&!Y.includes("No results found");return{query:H,result:Y,success:V}}catch(Y){let V=O$(Y);return{query:H,result:"",error:`Search failed: ${V}`,success:!1}}}))}})}function JZ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.cwd??process.cwd();return f$({name:"run_commands",description:"Run shell commands from the root of the workspace. Use for listing files, checking git status, running builds, executing tests, etc. Commands should be properly shell-escaped and targeted to avoid error or timeout. For long-running commands, run them in background and redirect output to a tmp file that you can read from later.",inputSchema:p0(U2),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(lQ,Z),X;if(typeof j==="string")X=[j];else if(Array.isArray(j))X=j;else if("commands"in j)X=Array.isArray(j.commands)?j.commands:[j.commands];else if("command"in j)X=[j.command];else X=[j.cmd];return Promise.all(X.map(async(H)=>{try{let Y=await l0($(H,Q,W),J,`Command timed out after ${J}ms`);return{query:H,result:Y,success:!0}}catch(Y){let V=O$(Y);return{query:H,result:"",error:`Command failed: ${V}`,success:!1}}}))}})}function QZ($,f={}){let J=f.bashTimeoutMs??30000,Q=f.cwd??process.cwd();return f$({name:"run_commands",description:"Run shell commands from the root of the workspacein Windows environment. Use for listing files, checking git status, running builds, executing tests, etc. Prefer structured { command, args } entries for portability; plain string commands should be properly shell-escaped.",inputSchema:p0(UJ),timeoutMs:J*2,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=eQ(Z);return Promise.all(j.map(async(X)=>{try{let H=await l0($(X,Q,W),J,`Command timed out after ${J}ms`);return{query:DJ(X),result:H,success:!0}}catch(H){let Y=O$(H);return{query:DJ(X),result:"",error:`Command failed: ${Y}`,success:!1}}}))}})}function ZZ($,f={}){let J=f.webFetchTimeoutMs??30000;return f$({name:"fetch_web_content",description:"Fetch content from URLs and analyze them using the provided prompts. Use for retrieving documentation, API references, or any web content. Each request includes a URL and a prompt describing what information to extract.",inputSchema:p0(j4),timeoutMs:J*2,retryable:!0,maxRetries:2,execute:async(Q,Z)=>{let W=z$(j4,Q);return Promise.all(W.requests.map(async(j)=>{try{let X=await l0($(j.url,j.prompt,Z),J,`Web fetch timed out after ${J}ms`);return{query:j.url,result:X,success:!0}}catch(X){let H=O$(X);return{query:j.url,result:"",error:`Error fetching web content: ${H}`,success:!1}}}))}})}var oA=`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:
57
57
 
58
58
  *** Begin Patch
59
59
  *** Update File: path/to/file.ts
@@ -89,83 +89,83 @@ Example:
89
89
  </div>
90
90
  );
91
91
  }
92
- *** End Patch`;function lQ($,f={}){let J=f.applyPatchTimeoutMs??30000,Q=f.cwd??process.cwd();return J$({name:"apply_patch",description:CA,inputSchema:l0(J8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(hQ,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await d0($({input:X},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(H){return{query:"apply_patch",result:"",error:`apply_patch failed: ${O$(H)}`,success:!1}}}})}function pQ($,f={}){let J=f.editorTimeoutMs??30000,Q=f.cwd??process.cwd();return J$({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:l0(f8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(f8,Z),X=j.insert_line==null?"edit":"insert",H=kQ(j);if(H)return{query:`${X}:${j.path}`,result:"",error:H,success:!1};try{let Y=await d0($(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:Y,success:!0}}catch(Y){let V=O$(Y);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${V}`,success:!1}}}})}function k1($,f={}){let J=f.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=J$({name:"skills",description:Q,inputSchema:l0(Q8),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=z$(Q8,W);return d0($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(W&&W.length>0)return`${Q} Available skills: ${W.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),Z}function rQ($){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:l0(Z8),retryable:!1,maxRetries:0,execute:async(f,J)=>{let Q=z$(Z8,f);return $(Q.question,Q.options,J)}}}function iQ($,f={}){let J=f.submitTimeoutMs??15000;return J$({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. Provide a summary of the investigation and confirm the issue is resolved.",inputSchema:l0(W8),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=z$(W8,Q);return d0($(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function I1($){let{executors:f,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:H=!0,enableAskQuestion:Y=!0,enableSubmitAndExit:V=!1,...A}=$,B=[];if(J&&f.readFile)B.push(mQ(f.readFile,A));if(Q&&f.search)B.push(vQ(f.search,A));if(Z&&f.bash)if(process.platform==="win32")B.push(uQ(f.bash,A));else B.push(cQ(f.bash,A));if(W&&f.webFetch)B.push(dQ(f.webFetch,A));if(X&&f.editor)B.push(pQ(f.editor,A));else if(j&&f.applyPatch)B.push(lQ(f.applyPatch,A));if(H&&f.skills)B.push(k1(f.skills,A));let K=V?f.submit:void 0;if(Y&&f.askQuestion&&!K)B.push(rQ(f.askQuestion));if(K)B.push(iQ(K,A));return B}import*as M0 from"node:fs/promises";import*as q0 from"node:path";var k={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},aQ=["%%bash","apply_patch","EOF","```"];class f0 extends Error{constructor($){super($);this.name="DiffError"}}function T0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class HJ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(k.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(k.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(k.UPDATE)){this.parseUpdate($.substring(k.UPDATE.length).trim());return}if($?.startsWith(k.DELETE)){this.parseDelete($.substring(k.DELETE.length).trim());return}if($?.startsWith(k.ADD)){this.parseAdd($.substring(k.ADD.length).trim());return}throw new f0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new f0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(k.MOVE)?(this.lines[this.index++]??"").substring(k.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new f0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",Q=this.parseUpdateFile(J,$);Q.movePath=f,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},Q=$.split(`
93
- `),Z=0,W=[k.END,k.UPDATE,k.DELETE,k.ADD,k.END_FILE];while(!W.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],X=j?.startsWith("@@ ")?j.substring(3):void 0;if(X!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new f0(`Invalid Line:
94
- ${this.lines[this.index]}`);if(X?.trim()){let F=T0(X.trim());for(let P=Z;P<Q.length;P++){let D=Q[P];if(D&&(T0(D)===F||T0(D.trim())===F)){if(Z=P+1,T0(D.trim())===F&&T0(D)!==F)this.fuzz++;break}}}let[Y,V,A,B]=bA(this.lines,this.index),[K,G,R]=hA(Q,Y,Z,B);if(K===-1){let F=Y.join(`
95
- `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${R.toFixed(2)}). Chunk skipped.`,context:F.length>200?`${F.substring(0,200)}...`:F}),this.index=A}else{this.fuzz+=G;for(let F of V)F.origIndex+=K,J.chunks.push(F);Z=K+Y.length,this.index=A}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new f0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new f0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[k.END,k.UPDATE,k.DELETE,k.ADD];while(this.hasMoreLines()&&!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new f0(`Invalid Add File line (missing '+'): ${Q}`);f.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
96
- `),chunks:[]}}}function nQ($,f){let J=$.length>f.length?$:f,Q=$.length>f.length?f:$;if(J.length===0)return 1;let Z=EA(Q,J);return(J.length-Z)/J.length}function EA($,f){let J=f.length+1,Q=$.length+1,Z=Array(J*Q).fill(0),W=(X,H)=>Z[X*Q+H]??0,j=(X,H,Y)=>{Z[X*Q+H]=Y};for(let X=0;X<=f.length;X++)j(X,0,X);for(let X=0;X<=$.length;X++)j(0,X,X);for(let X=1;X<=f.length;X++)for(let H=1;H<=$.length;H++)if(f[X-1]===$[H-1])j(X,H,W(X-1,H-1));else j(X,H,1+Math.min(W(X-1,H-1),W(X,H-1),W(X-1,H)));return W(f.length,$.length)}function hA($,f,J,Q){if(f.length===0)return[J,0,1];let Z=0,W=(j)=>{let X=T0(f.join(`
97
- `));for(let Y=j;Y<$.length;Y++){let V=T0($.slice(Y,Y+f.length).join(`
98
- `));if(V===X)return[Y,0,1];let A=nQ(V,X);if(A>Z)Z=A}for(let Y=j;Y<$.length;Y++){let V=T0($.slice(Y,Y+f.length).map((B)=>B.trimEnd()).join(`
99
- `)),A=T0(f.map((B)=>B.trimEnd()).join(`
100
- `));if(V===A)return[Y,1,1]}for(let Y=j;Y<$.length;Y++){let V=T0($.slice(Y,Y+f.length).map((B)=>B.trim()).join(`
101
- `)),A=T0(f.map((B)=>B.trim()).join(`
102
- `));if(V===A)return[Y,100,1]}let H=0.66;for(let Y=j;Y<$.length;Y++){let V=T0($.slice(Y,Y+f.length).join(`
103
- `)),A=nQ(V,X);if(A>=H)return[Y,1000,A];if(A>Z)Z=A}return[-1,0,Z]};if(Q){let[j,X,H]=W($.length-f.length);if(j!==-1)return[j,X,H];return[j,X,H]=W(J),[j,X+1e4,H]}return W(J)}function bA($,f){let J=f,Q=[],Z=[],W=[],j=[],X="keep",H=["@@",k.END,k.UPDATE,k.DELETE,k.ADD,k.END_FILE];while(J<$.length){let Y=$[J];if(!Y||H.some((B)=>Y.startsWith(B.trim())))break;if(Y==="***")break;if(Y.startsWith("***"))throw new f0(`Invalid line: ${Y}`);J++;let V=X,A=Y;if(A[0]==="+")X="add";else if(A[0]==="-")X="delete";else if(A[0]===" ")X="keep";else X="keep",A=` ${A}`;if(A=A.slice(1),X==="keep"&&V!==X){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(X==="delete")Z.push(A),Q.push(A);else if(X==="add")W.push(A);else Q.push(A)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<$.length&&$[J]===k.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function YJ($,f,J){let Q=q0.isAbsolute(f),Z=Q?q0.normalize(f):q0.resolve($,f);if(!J||Q)return Z;let W=q0.relative($,Z);if(W.startsWith("..")||q0.isAbsolute(W))throw new f0(`Path must stay within cwd: ${f}`);return Z}function kA($){return $.split(`
104
- `).map((f)=>f.replace(/\r$/,""))}function tQ($){if($.trim()==="")return!1;return aQ.some((f)=>$.startsWith(f))}function IA($){let f=0,J=$.length;while(f<J&&tQ($[f]??""))f++;while(J>f&&tQ($[J-1]??""))J--;return $.slice(f,J)}function xA($){let f=kA($),J=f.findIndex((j)=>j.startsWith(k.BEGIN)),Q=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(k.END)){Q=j;break}if(J!==-1||Q!==-1){if(J===-1||Q===-1||Q<J)throw new f0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,Q+1)}}let Z=IA(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[k.BEGIN,...Z,k.END]}}function gA($,f){let J=new Set;for(let Q of $)for(let Z of f)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function mA($,f,J){if(f.length===0)return $;let Q=$.split(`
105
- `),Z=[],W=0;for(let j of f){if(j.origIndex>Q.length)throw new f0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${Q.length}`);if(W>j.origIndex)throw new f0(`${J}: currentIndex ${W} > chunk.origIndex ${j.origIndex}`);Z.push(...Q.slice(W,j.origIndex)),Z.push(...j.insLines),W=j.origIndex+j.delLines.length}return Z.push(...Q.slice(W)),Z.join(`
106
- `)}async function vA($,f,J,Q){let Z=gA($,[k.UPDATE,k.DELETE]),W={};for(let j of Z){let X=YJ(f,j,Q),H;try{H=await M0.readFile(X,J)}catch{throw new f0(`File not found: ${j}`)}W[j]=H.replace(/\r\n/g,`
107
- `)}return W}function cA($,f){let J={};for(let[Q,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:f[Q]};break;case"add":if(Z.newFile===void 0)throw new f0("ADD action without file content");J[Q]={type:"add",newContent:Z.newFile};break;case"update":J[Q]={type:"update",oldContent:f[Q],newContent:mA(f[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}async function uA($,f,J,Q){let Z=[];for(let[W,j]of Object.entries($)){let X=YJ(f,W,Q);switch(j.type){case"delete":await M0.rm(X,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new f0(`Cannot create ${W} with no content`);await M0.mkdir(q0.dirname(X),{recursive:!0}),await M0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break;case"update":{if(j.newContent===void 0)throw new f0(`UPDATE change for ${W} has no new content`);if(j.movePath){let H=YJ(f,j.movePath,Q);await M0.mkdir(q0.dirname(H),{recursive:!0}),await M0.writeFile(H,j.newContent,{encoding:J}),await M0.rm(X,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await M0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function X8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(Q,Z,W)=>{let j=xA(Q.input),X=await vA(j.lines,Z,f,J),H=new HJ(j.lines,X),{patch:Y,fuzz:V}=H.parse(),A=cA(Y,X),B=await uA(A,Z,f,J),K=["Successfully applied patch to the following files:"];for(let G of B)K.push(G);if(V>0)K.push(`Note: Patch applied with fuzz factor ${V}`);if(Y.warnings&&Y.warnings.length>0)for(let G of Y.warnings)K.push(`Warning (${G.path}): ${G.message}`);return K.join(`
108
- `)}}import{spawn as sQ}from"node:child_process";import{getDefaultShell as dA,getShellArgs as lA}from"@cline/shared";function pA($,f,J,Q,Z){return new Promise((W,j)=>{let X=process.platform==="win32",H=sQ($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X}),Y=H.pid,V="",A="",B=0,K=!1,G=!1,R=(L)=>{if(G)return;G=!0,L()},F=()=>{if(!Y)return;if(X){sQ("taskkill",["/pid",String(Y),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-Y,"SIGKILL")}catch{H.kill("SIGKILL")}},P=(L)=>{K=!0,F(),R(()=>j(L))},D=setTimeout(()=>P(Error(`Command timed out after ${J}ms`)),J),O=()=>P(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",O);let _=()=>{clearTimeout(D),f.signal?.removeEventListener("abort",O)};H.stdout?.on("data",(L)=>{if(B+=L.length,B<=Q)V+=L.toString()}),H.stderr?.on("data",(L)=>{if(B+=L.length,B<=Q)A+=L.toString()}),H.on("close",(L)=>{if(_(),K)return;let z=Z?V+(A?`
92
+ *** End Patch`;function WZ($,f={}){let J=f.applyPatchTimeoutMs??30000,Q=f.cwd??process.cwd();return f$({name:"apply_patch",description:oA,inputSchema:p0(H4),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(nQ,Z),X=typeof j==="string"?j:j.input;try{return{query:"apply_patch",result:await l0($({input:X},Q,W),J,`apply_patch timed out after ${J}ms`),success:!0}}catch(H){return{query:"apply_patch",result:"",error:`apply_patch failed: ${O$(H)}`,success:!1}}}})}function jZ($,f={}){let J=f.editorTimeoutMs??30000,Q=f.cwd??process.cwd();return f$({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:p0(X4),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Z,W)=>{let j=z$(X4,Z),X=j.insert_line==null?"edit":"insert",H=tQ(j);if(H)return{query:`${X}:${j.path}`,result:"",error:H,success:!1};try{let Y=await l0($(j,Q,W),J,`Editor operation timed out after ${J}ms`);return{query:`${X}:${j.path}`,result:Y,success:!0}}catch(Y){let V=O$(Y);return{query:`${X}:${j.path}`,result:"",error:`Editor operation failed: ${V}`,success:!1}}}})}function x1($,f={}){let J=f.skillsTimeoutMs??15000,Q='Execute a skill within the main conversation. When users ask you to perform tasks, check if any available skills match. When users reference a slash command, invoke it with this tool. Input: `skill` (required) and optional `args`. Example: `skill: "pdf"`, `skill: "commit", args: "-m \\"Fix bug\\""`, `skill: "review-pr", args: "123"`, `skill: "ms-office-suite:pdf"`. When a skill matches the user\'s request, invoking this tool is a blocking requirement before any other response. Never mention a skill without invoking this tool.',Z=f$({name:"skills",description:Q,inputSchema:p0(Y4),timeoutMs:J,retryable:!1,maxRetries:0,execute:async(W,j)=>{let X=z$(Y4,W);return l0($(X.skill,X.args||void 0,j),J,`Skills operation timed out after ${J}ms`)}});return Object.defineProperty(Z,"description",{get(){let W=$.configuredSkills?.filter((j)=>!j.disabled).map((j)=>j.name);if(W&&W.length>0)return`${Q} Available skills: ${W.join(", ")}.`;return Q},enumerable:!0,configurable:!0}),Z}function XZ($){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:p0(V4),retryable:!1,maxRetries:0,execute:async(f,J)=>{let Q=z$(V4,f);return $(Q.question,Q.options,J)}}}function HZ($,f={}){let J=f.submitTimeoutMs??15000;return f$({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:p0(A4),lifecycle:{completesRun:!0},timeoutMs:J,retryable:!1,maxRetries:0,execute:async(Q,Z)=>{let W=z$(A4,Q);return l0($(W.summary,W.verified,Z),J,`submit_and_exit timed out after ${J}ms`)}})}function m1($){let{executors:f,enableReadFiles:J=!0,enableSearch:Q=!0,enableBash:Z=!0,enableWebFetch:W=!0,enableApplyPatch:j=!1,enableEditor:X=!0,enableSkills:H=!0,enableAskQuestion:Y=!0,enableSubmitAndExit:V=!1,...A}=$,B=[];if(J&&f.readFile)B.push($Z(f.readFile,A));if(Q&&f.search)B.push(fZ(f.search,A));if(Z&&f.bash)if(process.platform==="win32")B.push(QZ(f.bash,A));else B.push(JZ(f.bash,A));if(W&&f.webFetch)B.push(ZZ(f.webFetch,A));if(X&&f.editor)B.push(jZ(f.editor,A));else if(j&&f.applyPatch)B.push(WZ(f.applyPatch,A));if(H&&f.skills)B.push(x1(f.skills,A));let G=V?f.submit:void 0;if(Y&&f.askQuestion&&!G)B.push(XZ(f.askQuestion));if(G)B.push(HZ(G,A));return B}import*as S0 from"node:fs/promises";import*as h0 from"node:path";var x={BEGIN:"*** Begin Patch",END:"*** End Patch",ADD:"*** Add File: ",UPDATE:"*** Update File: ",DELETE:"*** Delete File: ",MOVE:"*** Move to: ",SECTION:"@@",END_FILE:"*** End of File"},VZ=["%%bash","apply_patch","EOF","```"];class J0 extends Error{constructor($){super($);this.name="DiffError"}}function w0($){let f={"‐":"-","‑":"-","‒":"-","–":"-","—":"-","−":"-","“":'"',"”":'"',"„":'"',"«":'"',"»":'"',"‘":"'","’":"'","‛":"'"," ":" "," ":" "};return $.normalize("NFC").replace(/./gu,(J)=>f[J]??J).replace(/\\`/g,"`").replace(/\\'/g,"'").replace(/\\"/g,'"')}class RJ{lines;currentFiles;patch={actions:{},warnings:[]};index=0;fuzz=0;currentPath;constructor($,f){this.lines=$;this.currentFiles=f}parse(){this.skipBeginSentinel();while(this.hasMoreLines()&&!this.isEndMarker())this.parseNextAction();if(this.patch.warnings?.length===0)delete this.patch.warnings;return{patch:this.patch,fuzz:this.fuzz}}addWarning($){if(!this.patch.warnings)this.patch.warnings=[];this.patch.warnings.push($)}skipBeginSentinel(){if(this.lines[this.index]?.startsWith(x.BEGIN))this.index++}hasMoreLines(){return this.index<this.lines.length}isEndMarker(){return this.lines[this.index]?.startsWith(x.END)??!1}parseNextAction(){let $=this.lines[this.index];if($?.startsWith(x.UPDATE)){this.parseUpdate($.substring(x.UPDATE.length).trim());return}if($?.startsWith(x.DELETE)){this.parseDelete($.substring(x.DELETE.length).trim());return}if($?.startsWith(x.ADD)){this.parseAdd($.substring(x.ADD.length).trim());return}throw new J0(`Unknown line while parsing: ${$}`)}checkDuplicate($,f){if($ in this.patch.actions)throw new J0(`Duplicate ${f} for file: ${$}`)}parseUpdate($){this.checkDuplicate($,"update"),this.currentPath=$,this.index++;let f=this.lines[this.index]?.startsWith(x.MOVE)?(this.lines[this.index++]??"").substring(x.MOVE.length).trim():void 0;if(!($ in this.currentFiles))throw new J0(`Update File Error: Missing File: ${$}`);let J=this.currentFiles[$]??"",Q=this.parseUpdateFile(J,$);Q.movePath=f,this.patch.actions[$]=Q,this.currentPath=void 0}parseUpdateFile($,f){let J={type:"update",chunks:[]},Q=$.split(`
93
+ `),Z=0,W=[x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(!W.some((j)=>this.lines[this.index]?.startsWith(j.trim()))){let j=this.lines[this.index],X=j?.startsWith("@@ ")?j.substring(3):void 0;if(X!==void 0||(j==="@@"?j:void 0)!==void 0)this.index++;else if(Z!==0)throw new J0(`Invalid Line:
94
+ ${this.lines[this.index]}`);if(X?.trim()){let F=w0(X.trim());for(let P=Z;P<Q.length;P++){let U=Q[P];if(U&&(w0(U)===F||w0(U.trim())===F)){if(Z=P+1,w0(U.trim())===F&&w0(U)!==F)this.fuzz++;break}}}let[Y,V,A,B]=fB(this.lines,this.index),[G,K,D]=$B(Q,Y,Z,B);if(G===-1){let F=Y.join(`
95
+ `);this.addWarning({path:this.currentPath||f,chunkIndex:J.chunks.length,message:`Could not find matching context (similarity: ${D.toFixed(2)}). Chunk skipped.`,context:F.length>200?`${F.substring(0,200)}...`:F}),this.index=A}else{this.fuzz+=K;for(let F of V)F.origIndex+=G,J.chunks.push(F);Z=G+Y.length,this.index=A}}return J}parseDelete($){if(this.checkDuplicate($,"delete"),!($ in this.currentFiles))throw new J0(`Delete File Error: Missing File: ${$}`);this.patch.actions[$]={type:"delete",chunks:[]},this.index++}parseAdd($){if(this.checkDuplicate($,"add"),$ in this.currentFiles)throw new J0(`Add File Error: File already exists: ${$}`);this.index++;let f=[],J=[x.END,x.UPDATE,x.DELETE,x.ADD];while(this.hasMoreLines()&&!J.some((Q)=>this.lines[this.index]?.startsWith(Q.trim()))){let Q=this.lines[this.index++];if(Q===void 0)break;if(!Q.startsWith("+"))throw new J0(`Invalid Add File line (missing '+'): ${Q}`);f.push(Q.substring(1))}this.patch.actions[$]={type:"add",newFile:f.join(`
96
+ `),chunks:[]}}}function YZ($,f){let J=$.length>f.length?$:f,Q=$.length>f.length?f:$;if(J.length===0)return 1;let Z=eA(Q,J);return(J.length-Z)/J.length}function eA($,f){let J=f.length+1,Q=$.length+1,Z=Array(J*Q).fill(0),W=(X,H)=>Z[X*Q+H]??0,j=(X,H,Y)=>{Z[X*Q+H]=Y};for(let X=0;X<=f.length;X++)j(X,0,X);for(let X=0;X<=$.length;X++)j(0,X,X);for(let X=1;X<=f.length;X++)for(let H=1;H<=$.length;H++)if(f[X-1]===$[H-1])j(X,H,W(X-1,H-1));else j(X,H,1+Math.min(W(X-1,H-1),W(X,H-1),W(X-1,H)));return W(f.length,$.length)}function $B($,f,J,Q){if(f.length===0)return[J,0,1];let Z=0,W=(j)=>{let X=w0(f.join(`
97
+ `));for(let Y=j;Y<$.length;Y++){let V=w0($.slice(Y,Y+f.length).join(`
98
+ `));if(V===X)return[Y,0,1];let A=YZ(V,X);if(A>Z)Z=A}for(let Y=j;Y<$.length;Y++){let V=w0($.slice(Y,Y+f.length).map((B)=>B.trimEnd()).join(`
99
+ `)),A=w0(f.map((B)=>B.trimEnd()).join(`
100
+ `));if(V===A)return[Y,1,1]}for(let Y=j;Y<$.length;Y++){let V=w0($.slice(Y,Y+f.length).map((B)=>B.trim()).join(`
101
+ `)),A=w0(f.map((B)=>B.trim()).join(`
102
+ `));if(V===A)return[Y,100,1]}let H=0.66;for(let Y=j;Y<$.length;Y++){let V=w0($.slice(Y,Y+f.length).join(`
103
+ `)),A=YZ(V,X);if(A>=H)return[Y,1000,A];if(A>Z)Z=A}return[-1,0,Z]};if(Q){let[j,X,H]=W($.length-f.length);if(j!==-1)return[j,X,H];return[j,X,H]=W(J),[j,X+1e4,H]}return W(J)}function fB($,f){let J=f,Q=[],Z=[],W=[],j=[],X="keep",H=["@@",x.END,x.UPDATE,x.DELETE,x.ADD,x.END_FILE];while(J<$.length){let Y=$[J];if(!Y||H.some((B)=>Y.startsWith(B.trim())))break;if(Y==="***")break;if(Y.startsWith("***"))throw new J0(`Invalid line: ${Y}`);J++;let V=X,A=Y;if(A[0]==="+")X="add";else if(A[0]==="-")X="delete";else if(A[0]===" ")X="keep";else X="keep",A=` ${A}`;if(A=A.slice(1),X==="keep"&&V!==X){if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});Z=[],W=[]}if(X==="delete")Z.push(A),Q.push(A);else if(X==="add")W.push(A);else Q.push(A)}if(W.length||Z.length)j.push({origIndex:Q.length-Z.length,delLines:Z,insLines:W});if(J<$.length&&$[J]===x.END_FILE)return J++,[Q,j,J,!0];return[Q,j,J,!1]}function LJ($,f,J){let Q=h0.isAbsolute(f),Z=Q?h0.normalize(f):h0.resolve($,f);if(!J||Q)return Z;let W=h0.relative($,Z);if(W.startsWith("..")||h0.isAbsolute(W))throw new J0(`Path must stay within cwd: ${f}`);return Z}function JB($){return $.split(`
104
+ `).map((f)=>f.replace(/\r$/,""))}function AZ($){if($.trim()==="")return!1;return VZ.some((f)=>$.startsWith(f))}function QB($){let f=0,J=$.length;while(f<J&&AZ($[f]??""))f++;while(J>f&&AZ($[J-1]??""))J--;return $.slice(f,J)}function ZB($){let f=JB($),J=f.findIndex((j)=>j.startsWith(x.BEGIN)),Q=-1;for(let j=f.length-1;j>=0;j--)if(f[j]?.startsWith(x.END)){Q=j;break}if(J!==-1||Q!==-1){if(J===-1||Q===-1||Q<J)throw new J0("Invalid patch text - incomplete sentinels. Try breaking it into smaller patches.");return{lines:f.slice(J,Q+1)}}let Z=QB(f);while(Z.length>0&&Z[0]==="")Z.shift();while(Z.length>0&&Z[Z.length-1]==="")Z.pop();return{lines:[x.BEGIN,...Z,x.END]}}function WB($,f){let J=new Set;for(let Q of $)for(let Z of f)if(Q.startsWith(Z)){J.add(Q.substring(Z.length).trim());break}return[...J]}function jB($,f,J){if(f.length===0)return $;let Q=$.split(`
105
+ `),Z=[],W=0;for(let j of f){if(j.origIndex>Q.length)throw new J0(`${J}: chunk.origIndex ${j.origIndex} > lines.length ${Q.length}`);if(W>j.origIndex)throw new J0(`${J}: currentIndex ${W} > chunk.origIndex ${j.origIndex}`);Z.push(...Q.slice(W,j.origIndex)),Z.push(...j.insLines),W=j.origIndex+j.delLines.length}return Z.push(...Q.slice(W)),Z.join(`
106
+ `)}async function XB($,f,J,Q){let Z=WB($,[x.UPDATE,x.DELETE]),W={};for(let j of Z){let X=LJ(f,j,Q),H;try{H=await S0.readFile(X,J)}catch{throw new J0(`File not found: ${j}`)}W[j]=H.replace(/\r\n/g,`
107
+ `)}return W}function HB($,f){let J={};for(let[Q,Z]of Object.entries($.actions))switch(Z.type){case"delete":J[Q]={type:"delete",oldContent:f[Q]};break;case"add":if(Z.newFile===void 0)throw new J0("ADD action without file content");J[Q]={type:"add",newContent:Z.newFile};break;case"update":J[Q]={type:"update",oldContent:f[Q],newContent:jB(f[Q]??"",Z.chunks,Q),movePath:Z.movePath};break}return J}async function YB($,f,J,Q){let Z=[];for(let[W,j]of Object.entries($)){let X=LJ(f,W,Q);switch(j.type){case"delete":await S0.rm(X,{force:!0}),Z.push(`${W}: [deleted]`);break;case"add":if(j.newContent===void 0)throw new J0(`Cannot create ${W} with no content`);await S0.mkdir(h0.dirname(X),{recursive:!0}),await S0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break;case"update":{if(j.newContent===void 0)throw new J0(`UPDATE change for ${W} has no new content`);if(j.movePath){let H=LJ(f,j.movePath,Q);await S0.mkdir(h0.dirname(H),{recursive:!0}),await S0.writeFile(H,j.newContent,{encoding:J}),await S0.rm(X,{force:!0}),Z.push(`${W} -> ${j.movePath}`)}else await S0.writeFile(X,j.newContent,{encoding:J}),Z.push(W);break}}}return Z}function G4($={}){let{encoding:f="utf-8",restrictToCwd:J=!0}=$;return async(Q,Z,W)=>{let j=ZB(Q.input),X=await XB(j.lines,Z,f,J),H=new RJ(j.lines,X),{patch:Y,fuzz:V}=H.parse(),A=HB(Y,X),B=await YB(A,Z,f,J),G=["Successfully applied patch to the following files:"];for(let K of B)G.push(K);if(V>0)G.push(`Note: Patch applied with fuzz factor ${V}`);if(Y.warnings&&Y.warnings.length>0)for(let K of Y.warnings)G.push(`Warning (${K.path}): ${K.message}`);return G.join(`
108
+ `)}}import{spawn as BZ}from"node:child_process";import{getDefaultShell as VB,getShellArgs as AB}from"@cline/shared";function BB($,f,J,Q,Z){return new Promise((W,j)=>{let X=process.platform==="win32",H=BZ($.executable,$.args,{cwd:$.cwd,env:{...process.env,...$.env},stdio:["pipe","pipe","pipe"],detached:!X}),Y=H.pid,V="",A="",B=0,G=!1,K=!1,D=(R)=>{if(K)return;K=!0,R()},F=()=>{if(!Y)return;if(X){BZ("taskkill",["/pid",String(Y),"/T","/F"],{stdio:"ignore",shell:!0,windowsHide:!0}).unref();return}try{process.kill(-Y,"SIGKILL")}catch{H.kill("SIGKILL")}},P=(R)=>{G=!0,F(),D(()=>j(R))},U=setTimeout(()=>P(Error(`Command timed out after ${J}ms`)),J),z=()=>P(Error("Command was aborted"));if(f.signal)f.signal.addEventListener("abort",z);let _=()=>{clearTimeout(U),f.signal?.removeEventListener("abort",z)};H.stdout?.on("data",(R)=>{if(B+=R.length,B<=Q)V+=R.toString()}),H.stderr?.on("data",(R)=>{if(B+=R.length,B<=Q)A+=R.toString()}),H.on("close",(R)=>{if(_(),G)return;let L=Z?V+(A?`
109
109
  [stderr]
110
- ${A}`:""):V;if(B>Q)z+=`
110
+ ${A}`:""):V;if(B>Q)L+=`
111
111
 
112
- [Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(L!==0)R(()=>j(Error(A||`Command exited with code ${L}`)));else R(()=>W(z))}),H.on("error",(L)=>{_(),R(()=>j(Error(`Failed to execute command: ${L.message}`)))})})}function H8($={}){let{shell:f=dA(process.platform),timeoutMs:J=30000,maxOutputBytes:Q=1e6,env:Z={},combineOutput:W=!0}=$;return(j,X,H)=>{let Y=typeof j!=="string";return pA({executable:Y?j.command:f,args:Y?j.args??[]:lA(f,j),cwd:X,env:Z},H,J,Q,W)}}import*as m0 from"node:fs/promises";import*as g0 from"node:path";function rA($,f,J){let Q=g0.isAbsolute(f),Z=Q?g0.normalize(f):g0.resolve($,f);if(!J)return Z;if(Q)return Z;let W=g0.relative($,Z);if(W.startsWith("..")||g0.isAbsolute(W))throw Error(`Path must stay within cwd: ${f}`);return Z}function iA($,f){if(f.length===0)return 0;return $.split(f).length-1}function nA($,f,J){let Q=$.split(`
112
+ [Output truncated: ${B} bytes total, showing first ${Q} bytes]`;if(R!==0)D(()=>j(Error(A||`Command exited with code ${R}`)));else D(()=>W(L))}),H.on("error",(R)=>{_(),D(()=>j(Error(`Failed to execute command: ${R.message}`)))})})}function K4($={}){let{shell:f=VB(process.platform),timeoutMs:J=30000,maxOutputBytes:Q=1e6,env:Z={},combineOutput:W=!0}=$;return(j,X,H)=>{let Y=typeof j!=="string";return BB({executable:Y?j.command:f,args:Y?j.args??[]:AB(f,j),cwd:X,env:Z},H,J,Q,W)}}import*as c0 from"node:fs/promises";import*as u0 from"node:path";function GB($,f,J){let Q=u0.isAbsolute(f),Z=Q?u0.normalize(f):u0.resolve($,f);if(!J)return Z;if(Q)return Z;let W=u0.relative($,Z);if(W.startsWith("..")||u0.isAbsolute(W))throw Error(`Path must stay within cwd: ${f}`);return Z}function KB($,f){if(f.length===0)return 0;return $.split(f).length-1}function FB($,f,J){let Q=$.split(`
113
113
  `),Z=f.split(`
114
114
  `),W=Math.max(Q.length,Z.length),j=["```diff"],X=0;for(let H=0;H<W;H++){if(X>=J){j.push("... diff truncated ...");break}let Y=Q[H],V=Z[H];if(Y===V)continue;let A=H+1;if(Y!==void 0)j.push(`-${A}: ${Y}`),X++;if(V!==void 0&&X<J)j.push(`+${A}: ${V}`),X++}return j.push("```"),j.join(`
115
- `)}async function aA($,f,J){return await m0.mkdir(g0.dirname($),{recursive:!0}),await m0.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function tA($){try{return await m0.access($),!0}catch{return!1}}async function sA($,f,J,Q,Z){let W=await m0.readFile($,Q),j=iA(W,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=W.replace(f,J??"");await m0.writeFile($,X,{encoding:Q});let H=nA(W,X,Z);return`Edited ${$}
116
- ${H}`}async function oA($,f,J,Q){let W=(await m0.readFile($,Q)).split(`
115
+ `)}async function PB($,f,J){return await c0.mkdir(u0.dirname($),{recursive:!0}),await c0.writeFile($,f,{encoding:J}),`File created successfully at: ${$}`}async function UB($){try{return await c0.access($),!0}catch{return!1}}async function DB($,f,J,Q,Z){let W=await c0.readFile($,Q),j=KB(W,f);if(j===0)throw Error(`No replacement performed: text not found in ${$}.`);if(j>1)throw Error(`No replacement performed: multiple occurrences of text found in ${$}.`);let X=W.replace(f,J??"");await c0.writeFile($,X,{encoding:Q});let H=FB(W,X,Z);return`Edited ${$}
116
+ ${H}`}async function RB($,f,J,Q){let W=(await c0.readFile($,Q)).split(`
117
117
  `),j=W.length+1;if(f<1||f>j)throw Error(`Invalid insert_line: ${f}. insert_line must be a positive one-based boundary line in the range 1-${j}. Use ${j} to append at EOF.`);let X=f-1;return W.splice(X,0,...J.split(`
118
- `)),await m0.writeFile($,W.join(`
119
- `),{encoding:Q}),`Inserted content at line ${f} in ${$}.`}function Y8($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=$;return async(Z,W,j)=>{let X=rA(W,Z.path,J);if(Z.insert_line!=null)return oA(X,Z.insert_line,Z.new_text,f);if(!await tA(X))return aA(X,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return sA(X,Z.old_text,Z.new_text,f,Q)}}import*as Ff from"node:fs/promises";import*as _$ from"node:path";var eA=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),$B={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function V8($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:Q}={...$B,...$};return async(Z,W)=>{let{path:j,start_line:X,end_line:H}=Z,Y=_$.isAbsolute(j)?_$.normalize(j):_$.resolve(process.cwd(),j),V=_$.extname(Y).toLowerCase(),A=eA.get(V),B=await Ff.stat(Y);if(!B.isFile())throw Error(`Path is not a file: ${Y}`);if(B.size>f)throw Error(`File too large: ${B.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(A){if(W.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let D=await Ff.readFile(Y);return[{type:"text",text:"Successfully read image"},{type:"image",data:D.toString("base64"),mediaType:A}]}let G=(await Ff.readFile(Y,J)).split(`
120
- `),R=Math.max((X??1)-1,0),F=Math.min(H??G.length,G.length),P=G.slice(R,F);if(Q){let D=String(G.length).length;return P.map((O,_)=>`${String(R+_+1).padStart(D," ")} | ${O}`).join(`
121
- `)}return P.join(`
122
- `)}}import{spawn as ZZ}from"node:child_process";import*as WZ from"node:fs/promises";import*as K8 from"node:path";import{spawn as fB}from"node:child_process";import{readdir as JB}from"node:fs/promises";import AJ from"node:path";import{isMainThread as $Z,parentPort as oQ,Worker as QB}from"node:worker_threads";var ZB=15000,WB=600000,jB=1000,XB=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function eQ($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var x1=new Map;function HB($){if(x1.size<=1)return;for(let[f,J]of x1.entries()){if(J.pending)continue;if($-J.lastAccessedAt>WB)x1.delete(f)}}function YB($,f){return AJ.relative($,f).split(AJ.sep).join("/")}async function VB($){let J=(await new Promise((Q,Z)=>{let W=fB("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",X="";W.stdout.on("data",(H)=>{j+=H.toString()}),W.stderr.on("data",(H)=>{X+=H.toString()}),W.on("error",Z),W.on("close",(H)=>{if(H===0){Q(j);return}Z(Error(X||`rg exited with code ${H}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function fZ($,f,J){let Q;try{Q=await JB(f,{withFileTypes:!0})}catch(Z){if(eQ(Z))return;throw Z}for(let Z of Q){let W=AJ.join(f,Z.name);if(Z.isDirectory()){if(XB.has(Z.name))continue;try{await fZ($,W,J)}catch(j){if(eQ(j))continue;throw j}continue}if(Z.isFile())J.add(YB($,W))}}async function AB($){let f=new Set;return await fZ($,$,f),f}async function A8($){try{return await VB($)}catch{return AB($)}}function BB(){if($Z||!oQ)return;let $=oQ;$.on("message",(f)=>{if(f.type!=="index")return;A8(f.cwd).then((J)=>{let Q={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(Q)})})}class JZ{worker=new QB(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},jB);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),W(X)}})}),Q={type:"index",requestId:f,cwd:$};return this.worker.postMessage(Q),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}BB();var VJ;function KB(){if(!$Z)return null;if(VJ===void 0)VJ=new JZ;return VJ}async function GB($){let f=KB();if(!f)return A8($);try{let J=await f.requestIndex($);if(J===null)return A8($);return new Set(J)}catch{return A8($)}}async function e$($,f={}){let J=f.ttlMs??ZB,Q=Date.now();HB(Q);let Z=x1.get($);if(Z&&J>0&&Q-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=Q,Z.files;if(Z?.pending)return Z.lastAccessedAt=Q,Z.pending;let W=GB($).then((j)=>{return x1.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return x1.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function QZ($,f={}){await e$($,{...f,ttlMs:0})}import{stat as PB}from"node:fs/promises";import $1 from"node:path";var FB=/[),.:;!?`'"]+$/,DB=/^[(`'"]+/;function RB($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of f){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(DB,"").replace(FB,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function UB($,f){let J=$.replace(/\\/g,"/"),Q=$1.isAbsolute(J)?$1.resolve(J):$1.resolve(f,J),Z=$1.relative(f,Q);if(Z.startsWith("..")||$1.isAbsolute(Z))return;return Z.split($1.sep).join("/")}async function B8($,f,J={}){let Q=RB($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,X=await e$(f,{ttlMs:J.ttlMs}),H=[],Y=[],V=[],A=0;for(let B of Q){if(Z&&V.length>=Z){Y.push(B);continue}let K=UB(B,f);if(!K||!X.has(K)){Y.push(B);continue}if(!W||!j){H.push(K);continue}let G=$1.join(f,K);try{if(!(await PB(G)).isFile()){Y.push(B);continue}let F=A+W;if(F>j){Y.push(B);continue}A=F,H.push(K)}catch{Y.push(B)}}return{prompt:$,mentions:Q,matchedFiles:H,ignoredMentions:Y}}var LB=["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"],OB=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],f1=null;function zB(){if(f1!==null)return Promise.resolve(f1);return new Promise(($)=>{let f=ZZ("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{f1=J===0,$(f1)}),f.on("error",()=>{f1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(f1===null)f1=!1,$(!1)},1000)})}function _B($,f,J,Q,Z=5000,W){return new Promise((j)=>{let X=ZZ("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),H="",Y=!1,V=()=>{if(!X.killed)X.kill("SIGTERM")},A=setTimeout(()=>{if(!Y)Y=!0,V(),j(null)},Z),B=(K)=>{if(!Y)Y=!0,clearTimeout(A),V(),j(K)};if(W?.aborted){V(),j(null);return}W?.addEventListener("abort",()=>{B(null)}),X.stdout.on("data",(K)=>{H+=K.toString()}),X.stderr.on("data",()=>{}),X.on("close",(K)=>{if(K===0||K===1){try{let G=[],R=H.split(`
123
- `).filter((F)=>F.trim());for(let F of R){if(G.length>=J)break;let P=JSON.parse(F);if(P.type==="match"){let D=P.data,O=[];if(P.data.submatches&&P.data.submatches.length>0){let _=P.data.submatches[0];G.push({file:D.path.text,line:D.line_number,column:(_?.start??0)+1,match:_?.match?.text??"",context:O})}}else if(P.type==="context"&&G.length>0){let D=G[G.length-1],O=P.data.line_number===D.line?">":" ";D.context.push(`${O} ${P.data.line_number}: ${P.data.lines?.text??P.data.line?.text??""}`)}}B(G.length>0?G:null)}catch{B(null)}return}B(null)}),X.on("error",()=>{B(null)})})}function yB($,f,J,Q){let Z=$.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let H=0;H<Z.length-1;H++)if(f.has(Z[H]??""))return!1;let X=K8.posix.extname(W).slice(1).toLowerCase();return J.has(X)||!X&&!W.startsWith(".")}function G8($={}){let{includeExtensions:f=LB,excludeDirs:J=OB,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=$,j=new Set(J),X=new Set(f.map((H)=>H.toLowerCase()));return async(H,Y,V)=>{if(V.signal?.aborted)throw Error("Search operation aborted");let A=await zB(),B=null;if(A)B=await _B(H,Y,Q,Z,5000,V.signal);if(B){let D=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${H}`,""];for(let O of B)D.push(`${O.file}:${O.line}:${O.column}`),D.push(...O.context),D.push("");if(B.length>=Q)D.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return D.join(`
124
- `)}let K;try{K=new RegExp(H,"gim")}catch(D){throw Error(`Invalid regex pattern: ${H}. ${D instanceof Error?D.message:""}`)}let G=[],R=0,F=await e$(Y);for(let D of F){if(V.signal?.aborted)throw Error("Search operation aborted");if(!yB(D,j,X,W))continue;if(G.length>=Q)break;R++;let O=K8.join(Y,D);try{let L=(await WZ.readFile(O,"utf-8")).split(`
125
- `);for(let z=0;z<L.length;z++){let y=L[z];K.lastIndex=0;let T=K.exec(y);while(T!==null){if(G.length>=Q)break;let e=Math.max(0,z-Z),$0=Math.min(L.length-1,z+Z),a=[];for(let m=e;m<=$0;m++){let V0=m===z?">":" ";a.push(`${V0} ${m+1}: ${L[m]}`)}if(G.push({file:D,line:z+1,column:T.index+1,match:T[0],context:a}),T.index===K.lastIndex)K.lastIndex++;T=K.exec(y)}}}catch{}}if(G.length===0)return`No results found for pattern: ${H}
126
- Searched ${R} files.`;let P=[`Found ${G.length} result${G.length===1?"":"s"} for pattern: ${H}`,`Searched ${R} files.`,""];for(let D of G)P.push(`${D.file}:${D.line}:${D.column}`),P.push(...D.context),P.push("");if(G.length>=Q)P.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return P.join(`
127
- `)}}function NB($){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,`
118
+ `)),await c0.writeFile($,W.join(`
119
+ `),{encoding:Q}),`Inserted content at line ${f} in ${$}.`}function F4($={}){let{encoding:f="utf-8",restrictToCwd:J=!0,maxDiffLines:Q=200}=$;return async(Z,W,j)=>{let X=GB(W,Z.path,J);if(Z.insert_line!=null)return RB(X,Z.insert_line,Z.new_text,f);if(!await UB(X))return PB(X,Z.new_text,f);if(Z.old_text==null)throw Error("Parameter `old_text` is required when editing an existing file without `insert_line`");return DB(X,Z.old_text,Z.new_text,f,Q)}}import*as D2 from"node:fs/promises";import*as _$ from"node:path";import{resolveExistingFilePath as LB}from"@cline/shared/storage";var OB=new Map([[".gif","image/gif"],[".png","image/png"],[".jpg","image/jpeg"],[".jpeg","image/jpeg"],[".webp","image/webp"]]),zB={maxFileSizeBytes:1e7,encoding:"utf-8",includeLineNumbers:!0};function P4($={}){let{maxFileSizeBytes:f,encoding:J,includeLineNumbers:Q}={...zB,...$};return async(Z,W)=>{let{path:j,start_line:X,end_line:H}=Z,Y=_$.isAbsolute(j)?_$.normalize(j):_$.resolve(process.cwd(),j),V=LB(Y)??Y,A=_$.extname(V).toLowerCase(),B=OB.get(A),G=await D2.stat(V);if(!G.isFile())throw Error(`Path is not a file: ${V}`);if(G.size>f)throw Error(`File too large: ${G.size} bytes (max: ${f} bytes). Consider reading specific sections or using a different approach.`);if(B){if(W.metadata?.modelSupportsImages!==!0)throw Error("Current model does not support image input");let z=await D2.readFile(V);return[{type:"text",text:"Successfully read image"},{type:"image",data:z.toString("base64"),mediaType:B}]}let D=(await D2.readFile(V,J)).split(`
120
+ `),F=Math.max((X??1)-1,0),P=Math.min(H??D.length,D.length),U=D.slice(F,P);if(Q){let z=String(D.length).length;return U.map((_,R)=>`${String(F+R+1).padStart(z," ")} | ${_}`).join(`
121
+ `)}return U.join(`
122
+ `)}}import{spawn as RZ}from"node:child_process";import*as LZ from"node:fs/promises";import*as R4 from"node:path";import{spawn as _B}from"node:child_process";import{readdir as NB}from"node:fs/promises";import zJ from"node:path";import{isMainThread as FZ,parentPort as GZ,Worker as TB}from"node:worker_threads";var MB=15000,qB=600000,yB=1000,wB=new Set([".git","node_modules","dist","build",".next","coverage",".turbo",".cache","target","out"]);function KZ($){let f=$&&typeof $==="object"&&"code"in $?String($.code??""):"";return f==="EACCES"||f==="EPERM"||f==="ENOENT"}var g1=new Map;function SB($){if(g1.size<=1)return;for(let[f,J]of g1.entries()){if(J.pending)continue;if($-J.lastAccessedAt>qB)g1.delete(f)}}function hB($,f){return zJ.relative($,f).split(zJ.sep).join("/")}async function CB($){let J=(await new Promise((Q,Z)=>{let W=_B("rg",["--files","--hidden","-g","!.git"],{cwd:$,stdio:["ignore","pipe","pipe"]}),j="",X="";W.stdout.on("data",(H)=>{j+=H.toString()}),W.stderr.on("data",(H)=>{X+=H.toString()}),W.on("error",Z),W.on("close",(H)=>{if(H===0){Q(j);return}Z(Error(X||`rg exited with code ${H}`))})})).split(/\r?\n/).map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>Q.replace(/\\/g,"/"));return new Set(J)}async function PZ($,f,J){let Q;try{Q=await NB(f,{withFileTypes:!0})}catch(Z){if(KZ(Z))return;throw Z}for(let Z of Q){let W=zJ.join(f,Z.name);if(Z.isDirectory()){if(wB.has(Z.name))continue;try{await PZ($,W,J)}catch(j){if(KZ(j))continue;throw j}continue}if(Z.isFile())J.add(hB($,W))}}async function EB($){let f=new Set;return await PZ($,$,f),f}async function U4($){try{return await CB($)}catch{return EB($)}}function bB(){if(FZ||!GZ)return;let $=GZ;$.on("message",(f)=>{if(f.type!=="index")return;U4(f.cwd).then((J)=>{let Q={type:"indexResult",requestId:f.requestId,files:Array.from(J)};$.postMessage(Q)}).catch((J)=>{let Q={type:"indexResult",requestId:f.requestId,error:J instanceof Error?J.message:"Failed to build file index"};$.postMessage(Q)})})}class UZ{worker=new TB(new URL(import.meta.url));nextRequestId=0;pending=new Map;constructor(){this.worker.unref(),this.worker.on("message",($)=>{if($.type!=="indexResult")return;let f=this.pending.get($.requestId);if(!f)return;if(this.pending.delete($.requestId),$.error){f.reject(Error($.error));return}f.resolve($.files??[])}),this.worker.on("error",($)=>{this.flushPending($)}),this.worker.on("exit",($)=>{if($!==0)this.flushPending(Error(`File index worker exited with code ${$}`))})}requestIndex($){let f=++this.nextRequestId,J=new Promise((Z,W)=>{let j=setTimeout(()=>{this.pending.delete(f),Z(null)},yB);j.unref(),this.pending.set(f,{resolve:(X)=>{clearTimeout(j),Z(X)},reject:(X)=>{clearTimeout(j),W(X)}})}),Q={type:"index",requestId:f,cwd:$};return this.worker.postMessage(Q),J}flushPending($){for(let[f,J]of this.pending.entries())J.reject($),this.pending.delete(f)}}bB();var OJ;function kB(){if(!FZ)return null;if(OJ===void 0)OJ=new UZ;return OJ}async function IB($){let f=kB();if(!f)return U4($);try{let J=await f.requestIndex($);if(J===null)return U4($);return new Set(J)}catch{return U4($)}}async function J1($,f={}){let J=f.ttlMs??MB,Q=Date.now();SB(Q);let Z=g1.get($);if(Z&&J>0&&Q-Z.lastBuiltAt<=J&&Z.files.size>0)return Z.lastAccessedAt=Q,Z.files;if(Z?.pending)return Z.lastAccessedAt=Q,Z.pending;let W=IB($).then((j)=>{return g1.set($,{files:j,lastBuiltAt:Date.now(),lastAccessedAt:Date.now(),pending:null}),j});return g1.set($,{files:Z?.files??new Set,lastBuiltAt:Z?.lastBuiltAt??0,lastAccessedAt:Q,pending:W}),W}async function DZ($,f={}){await J1($,{...f,ttlMs:0})}import{stat as xB}from"node:fs/promises";import Q1 from"node:path";var mB=/[),.:;!?`'"]+$/,gB=/^[(`'"]+/;function vB($){let f=$.matchAll(/(^|[\s])@([^\s]+)/g),J=[];for(let Q of f){let Z=(Q[2]??"").trim();if(Z.length===0)continue;let W=Z.replace(gB,"").replace(mB,"");if(W.length===0||W.includes("@"))continue;J.push(W)}return Array.from(new Set(J))}function uB($,f){let J=$.replace(/\\/g,"/"),Q=Q1.isAbsolute(J)?Q1.resolve(J):Q1.resolve(f,J),Z=Q1.relative(f,Q);if(Z.startsWith("..")||Q1.isAbsolute(Z))return;return Z.split(Q1.sep).join("/")}async function D4($,f,J={}){let Q=vB($);if(Q.length===0)return{prompt:$,mentions:[],matchedFiles:[],ignoredMentions:[]};let{maxFiles:Z,maxFileBytes:W,maxTotalBytes:j}=J,X=await J1(f,{ttlMs:J.ttlMs}),H=[],Y=[],V=[],A=0;for(let B of Q){if(Z&&V.length>=Z){Y.push(B);continue}let G=uB(B,f);if(!G||!X.has(G)){Y.push(B);continue}if(!W||!j){H.push(G);continue}let K=Q1.join(f,G);try{if(!(await xB(K)).isFile()){Y.push(B);continue}let F=A+W;if(F>j){Y.push(B);continue}A=F,H.push(G)}catch{Y.push(B)}}return{prompt:$,mentions:Q,matchedFiles:H,ignoredMentions:Y}}var cB=["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"],dB=["node_modules",".git","dist","build",".next","coverage","__pycache__",".venv","venv",".cache",".turbo",".output","out","target","bin","obj"],Z1=null;function lB(){if(Z1!==null)return Promise.resolve(Z1);return new Promise(($)=>{let f=RZ("rg",["--version"],{stdio:["ignore","pipe","pipe"]});f.on("close",(J)=>{Z1=J===0,$(Z1)}),f.on("error",()=>{Z1=!1,$(!1)}),setTimeout(()=>{if(!f.killed)f.kill("SIGTERM");if(Z1===null)Z1=!1,$(!1)},1000)})}function pB($,f,J,Q,Z=5000,W){return new Promise((j)=>{let X=RZ("rg",["--json",`--context=${Q}`,"--max-count=1","-i",$],{cwd:f,stdio:["ignore","pipe","pipe"]}),H="",Y=!1,V=()=>{if(!X.killed)X.kill("SIGTERM")},A=setTimeout(()=>{if(!Y)Y=!0,V(),j(null)},Z),B=(G)=>{if(!Y)Y=!0,clearTimeout(A),V(),j(G)};if(W?.aborted){V(),j(null);return}W?.addEventListener("abort",()=>{B(null)}),X.stdout.on("data",(G)=>{H+=G.toString()}),X.stderr.on("data",()=>{}),X.on("close",(G)=>{if(G===0||G===1){try{let K=[],D=H.split(`
123
+ `).filter((F)=>F.trim());for(let F of D){if(K.length>=J)break;let P=JSON.parse(F);if(P.type==="match"){let U=P.data,z=[];if(P.data.submatches&&P.data.submatches.length>0){let _=P.data.submatches[0];K.push({file:U.path.text,line:U.line_number,column:(_?.start??0)+1,match:_?.match?.text??"",context:z})}}else if(P.type==="context"&&K.length>0){let U=K[K.length-1],z=P.data.line_number===U.line?">":" ";U.context.push(`${z} ${P.data.line_number}: ${P.data.lines?.text??P.data.line?.text??""}`)}}B(K.length>0?K:null)}catch{B(null)}return}B(null)}),X.on("error",()=>{B(null)})})}function rB($,f,J,Q){let Z=$.split("/"),W=Z[Z.length-1]??"";if(Z.length-1>Q)return!1;for(let H=0;H<Z.length-1;H++)if(f.has(Z[H]??""))return!1;let X=R4.posix.extname(W).slice(1).toLowerCase();return J.has(X)||!X&&!W.startsWith(".")}function L4($={}){let{includeExtensions:f=cB,excludeDirs:J=dB,maxResults:Q=100,contextLines:Z=2,maxDepth:W=20}=$,j=new Set(J),X=new Set(f.map((H)=>H.toLowerCase()));return async(H,Y,V)=>{if(V.signal?.aborted)throw Error("Search operation aborted");let A=await lB(),B=null;if(A)B=await pB(H,Y,Q,Z,5000,V.signal);if(B){let U=[`Found ${B.length} result${B.length===1?"":"s"} for pattern: ${H}`,""];for(let z of B)U.push(`${z.file}:${z.line}:${z.column}`),U.push(...z.context),U.push("");if(B.length>=Q)U.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return U.join(`
124
+ `)}let G;try{G=new RegExp(H,"gim")}catch(U){throw Error(`Invalid regex pattern: ${H}. ${U instanceof Error?U.message:""}`)}let K=[],D=0,F=await J1(Y);for(let U of F){if(V.signal?.aborted)throw Error("Search operation aborted");if(!rB(U,j,X,W))continue;if(K.length>=Q)break;D++;let z=R4.join(Y,U);try{let R=(await LZ.readFile(z,"utf-8")).split(`
125
+ `);for(let L=0;L<R.length;L++){let N=R[L];G.lastIndex=0;let M=G.exec(N);while(M!==null){if(K.length>=Q)break;let o=Math.max(0,L-Z),e=Math.min(R.length-1,L+Z),a=[];for(let v=o;v<=e;v++){let V0=v===L?">":" ";a.push(`${V0} ${v+1}: ${R[v]}`)}if(K.push({file:U,line:L+1,column:M.index+1,match:M[0],context:a}),M.index===G.lastIndex)G.lastIndex++;M=G.exec(N)}}}catch{}}if(K.length===0)return`No results found for pattern: ${H}
126
+ Searched ${D} files.`;let P=[`Found ${K.length} result${K.length===1?"":"s"} for pattern: ${H}`,`Searched ${D} files.`,""];for(let U of K)P.push(`${U.file}:${U.line}:${U.column}`),P.push(...U.context),P.push("");if(K.length>=Q)P.push(`(Showing first ${Q} results. Refine your search for more specific results.)`);return P.join(`
127
+ `)}}function iB($){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,`
128
128
  `).replace(/<[^>]+>/g," ").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#(\d+);/g,(f,J)=>String.fromCharCode(parseInt(J,10))).replace(/\s+/g," ").replace(/\n\s+/g,`
129
129
  `).replace(/\n{3,}/g,`
130
130
 
131
- `).trim()}function P8($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=$;return async(j,X,H)=>{let Y;try{Y=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(Y.protocol))throw Error(`Invalid protocol: ${Y.protocol}. Only http and https are supported.`);let V=new AbortController,A=setTimeout(()=>V.abort(),f),B;if(H.signal)B=()=>V.abort(),H.signal.addEventListener("abort",B);try{let K=await fetch(j,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:W?"follow":"manual",signal:V.signal});if(clearTimeout(A),!W&&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 F=[],P=0;while(!0){let{done:y,value:T}=await R.read();if(y)break;if(P+=T.length,P>J)throw R.cancel(),Error(`Response too large: exceeded ${J} bytes`);F.push(T)}let D=new Uint8Array(P),O=0;for(let y of F)D.set(y,O),O+=y.length;let _=new TextDecoder("utf-8").decode(D),L;if(G.includes("text/html")||G.includes("application/xhtml"))L=NB(_);else if(G.includes("application/json"))try{let y=JSON.parse(_);L=JSON.stringify(y,null,2)}catch{L=_}else L=_;let z=[`URL: ${j}`,`Content-Type: ${G}`,`Size: ${P} bytes`,"","--- Content ---",L.slice(0,50000)];if(L.length>50000)z.push(`
132
- [Content truncated: showing first 50000 of ${L.length} characters]`);return z.push("","--- Analysis Request ---",`Prompt: ${X}`),z.join(`
133
- `)}catch(K){if(clearTimeout(A),K instanceof Error){if(K.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw K}throw Error(`Fetch failed: ${String(K)}`)}finally{if(H.signal&&B)H.signal.removeEventListener("abort",B)}}}function F8($={}){return{readFile:V8($.fileRead),search:G8($.search),bash:H8($.bash),webFetch:P8($.webFetch),applyPatch:X8($.applyPatch),editor:Y8($.editor)}}var TB={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"},Df=[{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 jZ($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((Q)=>J.includes(Q.toLowerCase()))}function MB($,f,J,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return jZ(f,$.providerIdIncludes)&&jZ(J,$.modelIdIncludes)}function Rf($,f,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!MB(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let W={};for(let[j,X]of Z.entries())W[TB[j]]=X;return W}var p0={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 y$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function XZ($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let Q of b1)J[Q]=f;return J}function HZ($,f){let J=p0[$],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return I1({...W,...f})}import{createTool as LK,zodToJsonSchema as OK}from"@cline/shared";import{z as OJ}from"zod";import{createAgentRuntime as AK}from"@cline/agents";import{createContributionRegistry as BK}from"@cline/shared";import{createGateway as qB,MODEL_COLLECTIONS_BY_PROVIDER_ID as wB}from"@cline/llms";function BJ($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return wB[$.providerId]?.models??void 0}function SB($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function CB($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:SB(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function YZ($,f,J){let Q=$.providerConfig,Z=Q?.providerId===$.providerId?Q:void 0,W={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:BJ($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};return qB({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,models:W.knownModels?Object.entries(W.knownModels).map(([j,X])=>CB(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as VZ}from"@cline/shared";var EB=50000,hB=6000000,AZ=8000,bB=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),kB=new Set(["read","read_files"]),J1="[outdated - see the latest file content]",BZ="Tool execution was interrupted before a result was produced.",IB=($)=>`
131
+ `).trim()}function O4($={}){let{timeoutMs:f=30000,maxResponseBytes:J=5000000,userAgent:Q="Mozilla/5.0 (compatible; AgentBot/1.0)",headers:Z={},followRedirects:W=!0}=$;return async(j,X,H)=>{let Y;try{Y=new URL(j)}catch{throw Error(`Invalid URL: ${j}`)}if(!["http:","https:"].includes(Y.protocol))throw Error(`Invalid protocol: ${Y.protocol}. Only http and https are supported.`);let V=new AbortController,A=setTimeout(()=>V.abort(),f),B;if(H.signal)B=()=>V.abort(),H.signal.addEventListener("abort",B);try{let G=await fetch(j,{method:"GET",headers:{"User-Agent":Q,Accept:"text/html,application/xhtml+xml,application/xml;q=0.9,text/plain;q=0.8,*/*;q=0.7","Accept-Language":"en-US,en;q=0.9",...Z},redirect:W?"follow":"manual",signal:V.signal});if(clearTimeout(A),!W&&G.status>=300&&G.status<400)return`Redirect to: ${G.headers.get("location")}`;if(!G.ok)throw Error(`HTTP ${G.status}: ${G.statusText}`);let K=G.headers.get("content-type")||"",D=G.body?.getReader();if(!D)throw Error("Failed to read response body");let F=[],P=0;while(!0){let{done:N,value:M}=await D.read();if(N)break;if(P+=M.length,P>J)throw D.cancel(),Error(`Response too large: exceeded ${J} bytes`);F.push(M)}let U=new Uint8Array(P),z=0;for(let N of F)U.set(N,z),z+=N.length;let _=new TextDecoder("utf-8").decode(U),R;if(K.includes("text/html")||K.includes("application/xhtml"))R=iB(_);else if(K.includes("application/json"))try{let N=JSON.parse(_);R=JSON.stringify(N,null,2)}catch{R=_}else R=_;let L=[`URL: ${j}`,`Content-Type: ${K}`,`Size: ${P} bytes`,"","--- Content ---",R.slice(0,50000)];if(R.length>50000)L.push(`
132
+ [Content truncated: showing first 50000 of ${R.length} characters]`);return L.push("","--- Analysis Request ---",`Prompt: ${X}`),L.join(`
133
+ `)}catch(G){if(clearTimeout(A),G instanceof Error){if(G.name==="AbortError")throw Error(`Request timed out after ${f}ms`);throw G}throw Error(`Fetch failed: ${String(G)}`)}finally{if(H.signal&&B)H.signal.removeEventListener("abort",B)}}}function z4($={}){return{readFile:P4($.fileRead),search:L4($.search),bash:K4($.bash),webFetch:O4($.webFetch),applyPatch:G4($.applyPatch),editor:F4($.editor)}}var nB={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"},R2=[{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 OZ($,f){if(!f||f.length===0)return!0;let J=$.toLowerCase();return f.some((Q)=>J.includes(Q.toLowerCase()))}function aB($,f,J,Q){if($.mode&&$.mode!=="any"&&$.mode!==Q)return!1;return OZ(f,$.providerIdIncludes)&&OZ(J,$.modelIdIncludes)}function L2($,f,J,Q){if(!Q||Q.length===0)return{};let Z=new Map;for(let j of Q){if(!aB(j,$,f,J))continue;for(let X of j.disableTools??[])Z.set(X,!1);for(let X of j.enableTools??[])Z.set(X,!0)}let W={};for(let[j,X]of Z.entries())W[nB[j]]=X;return W}var r0={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 N$($){if($.mode==="plan")return"plan";if($.mode==="yolo")return"yolo";return"act"}function zZ($){if($!=="yolo")return{};let f={enabled:!0,autoApprove:!0},J={"*":f};for(let Q of I1)J[Q]=f;return J}function _Z($,f){let J=r0[$],{enableSpawnAgent:Q,enableAgentTeams:Z,...W}=J;return m1({...W,...f})}import{createTool as lG,zodToJsonSchema as pG}from"@cline/shared";import{z as CJ}from"zod";import{createAgentRuntime as kG}from"@cline/agents";import{createContributionRegistry as IG}from"@cline/shared";import{createGateway as tB,MODEL_COLLECTIONS_BY_PROVIDER_ID as sB}from"@cline/llms";function oB($){let f=Object.fromEntries(Object.entries($).filter(([,J])=>J!==void 0));return Object.keys(f).length>0?f:void 0}function eB($){let f={region:$.region,apiLine:$.apiLine,openRouterProviderSorting:$.openRouterProviderSorting,modelCatalog:$.modelCatalog};if($.providerId==="bedrock")Object.assign(f,{authentication:$.aws?.authentication,profile:$.aws?.profile,accessKeyId:$.aws?.accessKey,secretAccessKey:$.aws?.secretKey,sessionToken:$.aws?.sessionToken,usePromptCache:$.aws?.usePromptCache,useCrossRegionInference:$.useCrossRegionInference,useGlobalInference:$.useGlobalInference,endpoint:$.aws?.endpoint,customModelBaseId:$.aws?.customModelBaseId});if($.providerId==="vertex"){let J=$.gcp?.region??$.region;Object.assign(f,{project:$.gcp?.projectId,projectId:$.gcp?.projectId,location:J,region:J})}return oB(f)}function _J($){let f=$.providerConfig;if(f?.knownModels)return f.knownModels;if($.knownModels)return $.knownModels;return sB[$.providerId]?.models??void 0}function $G($){if(!$?.length)return;let f=new Set;for(let J of $)switch(J){case"tools":case"reasoning":case"prompt-cache":case"images":f.add(J);break;case"structured_output":f.add("structured-output");break;default:f.add("text")}return f.add("text"),[...f]}function fG($,f){return{id:$,name:f.name??$,description:f.description,contextWindow:f.contextWindow,maxInputTokens:f.maxInputTokens,maxOutputTokens:f.maxTokens,capabilities:$G(f.capabilities),metadata:{family:f.family,pricing:f.pricing,status:f.status,releaseDate:f.releaseDate}}}function NZ($,f,J){let Q=$.providerConfig,Z=Q?.providerId===$.providerId?Q:void 0,W={...Z??{},providerId:$.providerId,modelId:$.modelId,apiKey:$.apiKey??Z?.apiKey,baseUrl:$.baseUrl??Z?.baseUrl,headers:$.headers??Z?.headers,knownModels:_J($),maxOutputTokens:$.maxTokensPerTurn,reasoningEffort:$.reasoningEffort,thinkingBudgetTokens:$.thinkingBudgetTokens,thinking:$.thinking,logger:f,extensionContext:$.extensionContext};return tB({providerConfigs:[{providerId:W.providerId,apiKey:W.apiKey,baseUrl:W.baseUrl,headers:W.headers,options:eB(W),models:W.knownModels?Object.entries(W.knownModels).map(([j,X])=>fG(j,X)):void 0}],logger:f,telemetry:J??$.telemetry??$.extensionContext?.telemetry}).createAgentModel({providerId:W.providerId,modelId:W.modelId},{maxTokens:W.maxOutputTokens})}import{normalizeUserInput as TZ}from"@cline/shared";var JG=50000,QG=6000000,MZ=8000,ZG=new Set(["read","read_files","search","search_codebase","bash","run_commands"]),WG=new Set(["read","read_files"]),W1="[outdated - see the latest file content]",qZ="Tool execution was interrupted before a result was produced.",jG=($)=>`
134
134
 
135
135
  ...[truncated ${$} chars]...
136
136
 
137
- `,xB=($)=>`
137
+ `,XG=($)=>`
138
138
 
139
139
  ...[truncated ${$} chars to fit provider request budget]...
140
140
 
141
- `;class GJ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=EB,f=bB,J=hB){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=VZ(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let X=this.transformBlock(j,Q.role);if(X!==j)Z=!0;return X});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=VZ($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),Q=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===$.content?$:{...$,content:Q}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let Q=$[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(W.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(W.id,X)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let X=this.getReadLocators(W);for(let H of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(H),W.tool_use_id),this.isFullFileRead(H))this.latestFullContentOwnerByPathCache.set(H.path,W.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(X)=>{let H=J.at(-1);if(this.shouldMergeUserAfterToolResults(H,X)){J[J.length-1]={...H,content:[...H.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(X.content)){let H=X.content.filter((V)=>V.type==="tool_result"),Y=X.content.filter((V)=>V.type!=="tool_result");if(H.length>0){let V=this.appendMissingToolResults({...X,role:"user",content:H},Q);if(j(V),Q.size>0)Q.clear();Z=!0}if(Y.length>0||H.length===0){if(H.length===0)W();let V=H.length>0?{...X,content:Y}:X;if(j(V),V.role==="assistant")this.trackMissingToolCalls(V,f,Q)}continue}W(),j(X)}return W(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")f.add(Q.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||f.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${BZ} Tool: ${$}.`:BZ}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],Q=this.extractLocatorFromReadRequest(f);if(Q)J.push(Q);if(Array.isArray(f.files))for(let Z of f.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let Q of $){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((W)=>this.toReadLocatorKey(W))),Q=new Set(f.map((W)=>W.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??J1;let Z=0;for(let W of $)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return $.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:J1}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:J1}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:J1};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(Q)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=J1;else if(typeof Q.content==="string")Q.content=J1;else Q.result=J1;return Q}isReadTool($){return!!$&&kB.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let Q=this.truncateMiddle(f.content);return Q===f.content?f:{...f,content:Q}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return KJ($,this.maxToolResultChars,IB)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>mB(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if(f<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=AZ)continue;let j=f-this.maxTotalTextBytes,X=Math.max(AZ,W-j),H=gB(Z.get(),X,xB);Z.set(H),f-=W-L0(H)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=L0(J.content);continue}for(let Q of J.content)if(Q.type==="text")f+=L0(Q.text);else if(Q.type==="thinking")f+=L0(Q.thinking);else if(Q.type==="file")f+=L0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")f+=L0(Q.content);else for(let Z of Q.content)if(Z.type==="text")f+=L0(Z.text);else if(Z.type==="file")f+=L0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){f.push({byteLength:L0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")f.push({byteLength:L0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")f.push({byteLength:L0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return f.sort((J,Q)=>Q.byteLength-J.byteLength)}}function L0($){return Buffer.byteLength($,"utf8")}function KJ($,f,J){if($.length<=f)return $;let Q=J($.length-f),Z=Math.max(0,Math.floor((f-Q.length)/2)),W=Math.max(0,$.length-Z*2),j=J(W),X=Math.max(0,Math.floor((f-j.length)/2)),H=$.slice(0,X),Y=X>0?$.slice(-X):"";return`${H}${j}${Y}`}function gB($,f,J){if(L0($)<=f)return $;let Q=0,Z=$.length,W=KJ($,0,J);while(Q<=Z){let j=Q+Z>>>1,X=KJ($,j,J);if(L0(X)<=f)W=X,Q=j+1;else Z=j-1}return W}function mB($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function PJ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class FJ{messages=[];conversationId=PJ();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=PJ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=PJ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function vB($){let f=uB($.content),J=[],Q=$.id??pB(),Z=0,W=[],j=()=>{if(W.length===0)return;let X=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:W.map(dB),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:KZ($.metrics)}),W=[]};if(f.length===0)return J.push({id:Q,role:$.role,content:[],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:KZ($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){W.push(X);continue}j(),J.push({id:`${Q}_tool_${X.tool_use_id}`,role:"tool",content:[FZ(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function D8($){return $.flatMap(vB)}function cB($){let f=$.content.map(DZ).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:lB($.metrics)}}function g1($){return $.map(cB)}function PZ($){let f=[];for(let J of $){let Q=J.content.map(DZ).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=f[f.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}f.push({role:Z,content:Q})}return f}function uB($){if(typeof $==="string")return $.length>0?[{type:"text",text:$}]:[];return[...$]}function dB($){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 FZ($)}}function FZ($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:"",output:$.content,isError:$.is_error}}function DZ($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:$.metadata?.signature};case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,content:J,is_error:$.isError}}}}function KZ($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function lB($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var GZ=0;function pB(){return GZ+=1,`msg_${Date.now().toString(36)}_${GZ.toString(36)}`}function RZ($){let{agentConfig:f}=$,J=rB(f),Q=iB(f),Z=$.hooks,W=nB(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:W,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function rB($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function iB($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function nB($){if($===void 0)return;return $>=2?"parallel":"sequential"}function aB(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function tB($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function DJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(DJ);let f={};for(let J of Object.keys($).sort())f[J]=DJ($[J]);return f}function sB($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(DJ($))}catch{return String($)}}function oB($,f,J,Q){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var UZ={softThreshold:3,hardThreshold:5};class RJ{config;state=aB();constructor($){this.config={softThreshold:$?.softThreshold??UZ.softThreshold,hardThreshold:$?.hardThreshold??UZ.hardThreshold}}inspect($){let f=sB($.input),J=oB(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){tB(this.state)}}class UJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await $K({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:eB({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function eB($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let Q=$.stopReason?.trim();if(Q)f.push(`Decision: ${Q}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function $K($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function fK($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function JK($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function QK($){return $.content.find((f)=>f.type==="tool-result")}function ZK($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function WK($){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 LJ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=fK($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let Q=JK($);if(Q!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=QK($.message),Z=Q?.output,W=WK(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,X=($.totalCost??0)-W;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:ZK($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function KK($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function GK($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function PK($,f){let J=$.trim(),Q=f.map((Z)=>Z.trim()).filter(Boolean).join(`
141
+ `;class TJ{maxToolResultChars;targetToolNames;maxTotalTextBytes;indexedMessageCount=0;indexedTailRef;toolNameByIdCache=new Map;readLocatorsByToolUseIdCache=new Map;latestReadToolUseByLocatorCache=new Map;latestFullContentOwnerByPathCache=new Map;readResultLocatorCache=new WeakMap;constructor($=JG,f=ZG,J=QG){this.maxToolResultChars=$;this.targetToolNames=f;this.maxTotalTextBytes=J}buildForApi($){this.reindex($);let J=this.addMissingToolResults($).map((Q)=>{if(!Array.isArray(Q.content)){if(Q.role==="user"&&typeof Q.content==="string"){let j=TZ(Q.content);if(j!==Q.content)return{...Q,content:j}}return Q}let Z=!1,W=Q.content.map((j)=>{let X=this.transformBlock(j,Q.role);if(X!==j)Z=!0;return X});return Z?{...Q,content:W}:Q});return this.truncateToTotalTextBudget(J)}transformBlock($,f){if(f==="user"&&$.type==="text"&&typeof $.text==="string"){let Z=TZ($.text);if(Z!==$.text)return{...$,text:Z};return $}if($.type==="file"){let Z=this.truncateMiddle($.content);return Z===$.content?$:{...$,content:Z}}if($.type!=="tool_result")return $;let J=this.toolNameByIdCache.get($.tool_use_id),Q=$.content;if(this.isReadTool(J)&&$.is_error!==!0){let Z=this.getReadLocators($);if(Z.length>0){let W=Z.filter((j)=>this.isOutdatedReadLocator(j,$.tool_use_id));if(W.length>0)Q=this.replaceOutdatedReadContent(Q,W)}}if(this.shouldTruncateTool(J))Q=this.truncateToolResultContent(Q);return Q===$.content?$:{...$,content:Q}}reindex($){let f=this.indexedMessageCount===0||$.length>=this.indexedMessageCount&&$[this.indexedMessageCount-1]===this.indexedTailRef;if($.length<this.indexedMessageCount||!f)this.resetIndexes();for(let J=this.indexedMessageCount;J<$.length;J++){let Q=$[J];if(!Array.isArray(Q.content))continue;for(let Z=0;Z<Q.content.length;Z++){let W=Q.content[Z];if(W.type==="file")this.latestFullContentOwnerByPathCache.set(W.path,`file:${J}:${Z}`);else if(W.type==="tool_use"){let j=W.name.toLowerCase();if(this.toolNameByIdCache.set(W.id,j),this.isReadTool(j)){let X=this.extractLocatorsFromReadToolInput(W.input);if(X.length>0)this.readLocatorsByToolUseIdCache.set(W.id,X)}}else if(W.type==="tool_result"){let j=this.toolNameByIdCache.get(W.tool_use_id);if(!this.isReadTool(j)||W.is_error===!0)continue;let X=this.getReadLocators(W);for(let H of X)if(this.latestReadToolUseByLocatorCache.set(this.toReadLocatorKey(H),W.tool_use_id),this.isFullFileRead(H))this.latestFullContentOwnerByPathCache.set(H.path,W.tool_use_id)}}}this.indexedMessageCount=$.length,this.indexedTailRef=$.length>0?$[$.length-1]:void 0}addMissingToolResults($){let f=this.collectToolResultIds($),J=[],Q=new Map,Z=!1,W=()=>{if(Q.size===0)return;j(this.createMissingToolResultMessage(Q)),Q.clear(),Z=!0},j=(X)=>{let H=J.at(-1);if(this.shouldMergeUserAfterToolResults(H,X)){J[J.length-1]={...H,content:[...H.content,...this.contentBlocksForUserMerge(X.content)]},Z=!0;return}J.push(X)};for(let X of $){if(this.isToolResultOnlyMessage(X)){if(j(this.appendMissingToolResults(X,Q)),Q.size>0)Q.clear(),Z=!0;continue}if(Array.isArray(X.content)){let H=X.content.filter((V)=>V.type==="tool_result"),Y=X.content.filter((V)=>V.type!=="tool_result");if(H.length>0){let V=this.appendMissingToolResults({...X,role:"user",content:H},Q);if(j(V),Q.size>0)Q.clear();Z=!0}if(Y.length>0||H.length===0){if(H.length===0)W();let V=H.length>0?{...X,content:Y}:X;if(j(V),V.role==="assistant")this.trackMissingToolCalls(V,f,Q)}continue}W(),j(X)}return W(),Z?J:$}appendMissingToolResults($,f){if(f.size===0||!Array.isArray($.content))return $;return{...$,role:"user",content:[...$.content,...this.createMissingToolResultBlocks(f)]}}shouldMergeUserAfterToolResults($,f){return $?.role==="user"&&f.role==="user"&&this.isToolResultOnlyMessage($)&&this.contentBlocksForUserMerge(f.content).length>0}contentBlocksForUserMerge($){return typeof $==="string"?$.length>0?[{type:"text",text:$}]:[]:$}collectToolResultIds($){let f=new Set;for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content)if(Q.type==="tool_result")f.add(Q.tool_use_id)}return f}isToolResultOnlyMessage($){return $.role==="user"&&Array.isArray($.content)&&$.content.length>0&&$.content.every((f)=>f.type==="tool_result")}trackMissingToolCalls($,f,J){if(!Array.isArray($.content))return;for(let Q of $.content){if(Q.type!=="tool_use"||f.has(Q.id))continue;J.set(Q.id,Q.name)}}createMissingToolResultMessage($){return{role:"user",content:this.createMissingToolResultBlocks($)}}createMissingToolResultBlocks($){return Array.from($,([f,J])=>({type:"tool_result",tool_use_id:f,name:J,content:[{type:"text",text:this.formatMissingToolResultText(J)}],is_error:!0}))}formatMissingToolResultText($){return $?`${qZ} Tool: ${$}.`:qZ}resetIndexes(){this.indexedMessageCount=0,this.indexedTailRef=void 0,this.toolNameByIdCache.clear(),this.readLocatorsByToolUseIdCache.clear(),this.latestReadToolUseByLocatorCache.clear(),this.latestFullContentOwnerByPathCache.clear(),this.readResultLocatorCache=new WeakMap}getReadLocators($){let f=$,J=this.readResultLocatorCache.get(f);if(J===void 0)J=this.extractReadLocatorsFromToolResultContent($.content),this.readResultLocatorCache.set(f,J);if(J.length>0)return J;return this.readLocatorsByToolUseIdCache.get($.tool_use_id)??[]}extractLocatorsFromReadToolInput($){if(!$||typeof $!=="object")return[];let f=$,J=[],Q=this.extractLocatorFromReadRequest(f);if(Q)J.push(Q);if(Array.isArray(f.files))for(let Z of f.files){let W=this.extractLocatorFromReadRequest(Z);if(W)J.push(W)}if(Array.isArray(f.file_paths)){for(let Z of f.file_paths)if(typeof Z==="string"&&Z.length>0)J.push({path:Z,startLine:null,endLine:null})}return this.dedupeReadLocators(J)}extractReadLocatorsFromToolResultContent($){if(typeof $==="string")return this.tryParseReadLocators($);for(let f of $){if(f.type!=="text")continue;let J=this.tryParseReadLocators(f.text);if(J.length>0)return J}return[]}tryParseReadLocators($){try{return this.extractLocatorsFromParsedReadResult(JSON.parse($))}catch{return[]}}extractLocatorsFromParsedReadResult($){if(Array.isArray($)){let J=[];for(let Q of $){let Z=this.extractLocatorFromResultEntry(Q);if(Z)J.push(Z)}return this.dedupeReadLocators(J)}let f=this.extractLocatorFromResultEntry($);return f?[f]:[]}extractLocatorFromReadRequest($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(!J)return;return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)}}extractLocatorFromResultEntry($){if(!$||typeof $!=="object")return;let f=$,J=this.extractPath(f);if(J)return{path:J,startLine:this.extractLineNumber(f.start_line),endLine:this.extractLineNumber(f.end_line)};if(typeof f.query==="string"&&f.query.length>0)return this.parseReadQuery(f.query);return}extractPath($){let f=[$.path,$.file_path,$.filePath];for(let J of f)if(typeof J==="string"&&J.length>0)return J;return}extractLineNumber($){return typeof $==="number"&&Number.isInteger($)?$:null}parseReadQuery($){let f=/^(.*):(\d+)-(EOF|\d+)$/.exec($);if(!f)return{path:$,startLine:null,endLine:null};return{path:f[1],startLine:Number(f[2]),endLine:f[3]==="EOF"?null:Number(f[3])}}dedupeReadLocators($){let f=new Map;for(let J of $)f.set(this.toReadLocatorKey(J),J);return Array.from(f.values())}toReadLocatorKey($){if(this.isFullFileRead($))return $.path;return`${$.path}:${$.startLine??1}-${$.endLine??"EOF"}`}isFullFileRead($){return $.startLine==null&&$.endLine==null}isOutdatedReadLocator($,f){let J=this.latestFullContentOwnerByPathCache.get($.path);if(J&&J!==f)return!0;return this.latestReadToolUseByLocatorCache.get(this.toReadLocatorKey($))!==f}replaceOutdatedReadContent($,f){let J=new Set(f.map((W)=>this.toReadLocatorKey(W))),Q=new Set(f.map((W)=>W.path));if(typeof $==="string")return this.replaceOutdatedInString($,J)??W1;let Z=0;for(let W of $)if(W.type==="text")Z+=this.countOutdatedImageEntries(W.text,J);return $.map((W)=>{if(W.type==="file"){if(!Q.has(W.path))return W;return{...W,content:W1}}if(W.type==="image"){if(Z===0)return W;return Z-=1,{type:"text",text:W1}}if(W.type!=="text")return W;let j=this.replaceOutdatedInString(W.text,J);if(j===null)return{...W,text:W1};return j===W.text?W:{...W,text:j}})}countOutdatedImageEntries($,f){let J;try{J=JSON.parse($)}catch{return 0}let Q=Array.isArray(J)?J:[J],Z=0;for(let W of Q){if(!W||typeof W!=="object")continue;let j=W,X=this.extractLocatorFromResultEntry(j);if(!X)continue;if(!f.has(this.toReadLocatorKey(X)))continue;if(j.result==="Successfully read image"||j.content==="Successfully read image")Z+=1}return Z}replaceOutdatedInString($,f){let J;try{J=JSON.parse($)}catch{return null}let Q=Array.isArray(J)?J.map((Z)=>this.replaceOutdatedReadEntry(Z,f)):this.replaceOutdatedReadEntry(J,f);return JSON.stringify(Q)}replaceOutdatedReadEntry($,f){if(!$||typeof $!=="object")return $;let J=this.extractLocatorFromResultEntry($);if(!J||!f.has(this.toReadLocatorKey(J)))return $;let Q={...$};if(typeof Q.result==="string")Q.result=W1;else if(typeof Q.content==="string")Q.content=W1;else Q.result=W1;return Q}isReadTool($){return!!$&&WG.has($)}shouldTruncateTool($){return!!$&&this.targetToolNames.has($)}truncateToolResultContent($){if(typeof $==="string")return this.truncateMiddle($);return $.map((f)=>{if(f.type==="file"){let Q=this.truncateMiddle(f.content);return Q===f.content?f:{...f,content:Q}}if(f.type!=="text")return f;let J=this.truncateMiddle(f.text);return J===f.text?f:{...f,text:J}})}truncateMiddle($){return NJ($,this.maxToolResultChars,jG)}truncateToTotalTextBudget($){if(this.maxTotalTextBytes<=0)return $;let f=this.countMessageTextBytes($);if(f<=this.maxTotalTextBytes)return $;let J=$.map((Z)=>{if(!Array.isArray(Z.content))return Z;return{...Z,content:Z.content.map((W)=>YG(W))}}),Q=this.collectTruncationCandidates(J);for(let Z of Q){if(f<=this.maxTotalTextBytes)break;let W=Z.byteLength;if(W<=MZ)continue;let j=f-this.maxTotalTextBytes,X=Math.max(MZ,W-j),H=HG(Z.get(),X,XG);Z.set(H),f-=W-z0(H)}return J}countMessageTextBytes($){let f=0;for(let J of $){if(typeof J.content==="string"){f+=z0(J.content);continue}for(let Q of J.content)if(Q.type==="text")f+=z0(Q.text);else if(Q.type==="thinking")f+=z0(Q.thinking);else if(Q.type==="file")f+=z0(Q.content);else if(Q.type==="tool_result"){if(typeof Q.content==="string")f+=z0(Q.content);else for(let Z of Q.content)if(Z.type==="text")f+=z0(Z.text);else if(Z.type==="file")f+=z0(Z.content)}}return f}collectTruncationCandidates($){let f=[];for(let J of $){if(!Array.isArray(J.content))continue;for(let Q of J.content){if(Q.type!=="tool_result")continue;let Z=this.toolNameByIdCache.get(Q.tool_use_id);if(!this.shouldTruncateTool(Z))continue;if(typeof Q.content==="string"){f.push({byteLength:z0(Q.content),get:()=>Q.content,set:(W)=>{Q.content=W}});continue}for(let W of Q.content)if(W.type==="text")f.push({byteLength:z0(W.text),get:()=>W.text,set:(j)=>{W.text=j}});else if(W.type==="file")f.push({byteLength:z0(W.content),get:()=>W.content,set:(j)=>{W.content=j}})}}return f.sort((J,Q)=>Q.byteLength-J.byteLength)}}function z0($){return Buffer.byteLength($,"utf8")}function NJ($,f,J){if($.length<=f)return $;let Q=J($.length-f),Z=Math.max(0,Math.floor((f-Q.length)/2)),W=Math.max(0,$.length-Z*2),j=J(W),X=Math.max(0,Math.floor((f-j.length)/2)),H=$.slice(0,X),Y=X>0?$.slice(-X):"";return`${H}${j}${Y}`}function HG($,f,J){if(z0($)<=f)return $;let Q=0,Z=$.length,W=NJ($,0,J);while(Q<=Z){let j=Q+Z>>>1,X=NJ($,j,J);if(z0(X)<=f)W=X,Q=j+1;else Z=j-1}return W}function YG($){if($.type!=="tool_result"||typeof $.content==="string")return{...$};return{...$,content:$.content.map((f)=>({...f}))}}function MJ(){return`conv_${Date.now()}_${Math.random().toString(36).slice(2,9)}`}class qJ{messages=[];conversationId=MJ();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=MJ(),this.sessionStarted=!1}clearHistory(){this.messages=[],this.conversationId=MJ(),this.sessionStarted=!1}restore($){this.messages=[...$],this.sessionStarted=!1}isSessionStarted(){return this.sessionStarted}markSessionStarted(){this.sessionStarted=!0}}function VG($){let f=BG($.content),J=[],Q=$.id??FG(),Z=0,W=[],j=()=>{if(W.length===0)return;let X=Z===0?Q:`${Q}_part_${Z}`;Z+=1,J.push({id:X,role:$.role,content:W.map(GG),createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:yZ($.metrics)}),W=[]};if(f.length===0)return J.push({id:Q,role:$.role,content:[],createdAt:$.ts??Date.now(),metadata:$.metadata,modelInfo:$.modelInfo,metrics:yZ($.metrics)}),J;for(let X of f){if(X.type!=="tool_result"){W.push(X);continue}j(),J.push({id:`${Q}_tool_${X.tool_use_id}`,role:"tool",content:[hZ(X)],createdAt:$.ts??Date.now(),metadata:$.metadata})}return j(),J}function _4($){return $.flatMap(VG)}function AG($){let f=$.content.map(CZ).filter((J)=>J!==void 0);return{id:$.id,role:$.role==="tool"?"user":$.role,content:f,ts:$.createdAt,metadata:$.metadata,modelInfo:$.modelInfo,metrics:KG($.metrics)}}function v1($){return $.map(AG)}function SZ($){let f=[];for(let J of $){let Q=J.content.map(CZ).filter((j)=>j!==void 0),Z=J.role==="tool"?"user":J.role,W=f[f.length-1];if(Z==="user"&&Q.length>0&&Q.every((j)=>j.type==="tool_result")&&W?.role==="user"&&Array.isArray(W.content)&&W.content.every((j)=>j.type==="tool_result")){W.content.push(...Q);continue}f.push({role:Z,content:Q})}return f}function BG($){if(typeof $==="string")return $.length>0?[{type:"text",text:$}]:[];return[...$]}function GG($){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 hZ($)}}function hZ($){return{type:"tool-result",toolCallId:$.tool_use_id,toolName:$.name,output:$.content,isError:$.is_error}}function CZ($){switch($.type){case"text":return{type:"text",text:$.text};case"reasoning":{if($.redacted===!0)return{type:"redacted_thinking",data:$.metadata?.data??""};let f=$.metadata;return{type:"thinking",thinking:$.text,signature:f?.signature,details:f?.details}}case"image":return typeof $.image==="string"?{type:"image",data:$.image,mediaType:$.mediaType??"image/png"}:void 0;case"file":return{type:"file",path:$.path,content:$.content};case"tool-call":return{type:"tool_use",id:$.toolCallId,name:$.toolName,input:$.input??{},signature:$.metadata?.signature};case"tool-result":{let f=$.output,J=typeof f==="string"?f:Array.isArray(f)?f:JSON.stringify(f);return{type:"tool_result",tool_use_id:$.toolCallId,name:$.toolName,content:J,is_error:$.isError}}}}function yZ($){if(!$)return;return{inputTokens:$.inputTokens??0,outputTokens:$.outputTokens??0,cacheReadTokens:$.cacheReadTokens??0,cacheWriteTokens:$.cacheWriteTokens??0,cost:$.cost}}function KG($){if(!$)return;return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,cost:$.cost}}var wZ=0;function FG(){return wZ+=1,`msg_${Date.now().toString(36)}_${wZ.toString(36)}`}function EZ($){let{agentConfig:f}=$,J=PG(f),Q=UG(f),Z=$.hooks,W=DG(f.maxParallelToolCalls);return{sessionId:$.sessionId??f.sessionId,agentId:$.agentId,conversationId:$.conversationId,parentAgentId:$.parentAgentId,agentRole:$.agentRole,systemPrompt:$.systemPrompt??f.systemPrompt,messageModelInfo:Q,model:$.model,modelOptions:J,tools:$.tools,hooks:Z,prepareTurn:$.prepareTurn,consumePendingUserMessage:f.consumePendingUserMessage,plugins:$.plugins,logger:$.logger??f.logger,telemetry:$.telemetry??f.telemetry,initialMessages:$.initialMessages,completionPolicy:f.completionPolicy,maxIterations:f.maxIterations,toolExecution:W,toolPolicies:f.toolPolicies,toolContextMetadata:$.toolContextMetadata,requestToolApproval:f.requestToolApproval}}function PG($){let f={};if($.thinking!==void 0)f.thinking=$.thinking;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;if($.maxTokensPerTurn!==void 0)f.maxTokensPerTurn=$.maxTokensPerTurn;if($.apiTimeoutMs!==void 0)f.apiTimeoutMs=$.apiTimeoutMs;return Object.keys(f).length>0?f:void 0}function UG($){let f=$.providerConfig?.family;return{id:$.modelId,provider:$.providerId,family:f}}function DG($){if($===void 0)return;return $>=2?"parallel":"sequential"}function RG(){return{lastToolName:"",lastToolSignature:"",consecutiveIdenticalCount:0}}function LG($){$.lastToolName="",$.lastToolSignature="",$.consecutiveIdenticalCount=0}function yJ($){if($==null||typeof $!=="object")return $;if(Array.isArray($))return $.map(yJ);let f={};for(let J of Object.keys($).sort())f[J]=yJ($[J]);return f}function OG($){if($==null)return"null";if(typeof $==="string")return $;if(typeof $!=="object")return String($);try{return JSON.stringify(yJ($))}catch{return String($)}}function zG($,f,J,Q){if(f===$.lastToolName&&J===$.lastToolSignature)$.consecutiveIdenticalCount++;else $.consecutiveIdenticalCount=1;return $.lastToolName=f,$.lastToolSignature=J,{softWarning:$.consecutiveIdenticalCount===Q.softThreshold,hardEscalation:$.consecutiveIdenticalCount>=Q.hardThreshold}}var bZ={softThreshold:3,hardThreshold:5};class wJ{config;state=RG();constructor($){this.config={softThreshold:$?.softThreshold??bZ.softThreshold,hardThreshold:$?.hardThreshold??bZ.hardThreshold}}inspect($){let f=OG($.input),J=zG(this.state,$.name,f,this.config);if(J.hardEscalation)return{kind:"hard",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; stopping to avoid a loop.`};if(J.softWarning)return{kind:"soft",message:`Detected ${this.state.consecutiveIdenticalCount} consecutive identical calls to \`${$.name}\`; consider trying a different approach.`};return{kind:"ok"}}reset(){LG(this.state)}}class SJ{consecutiveMistakes=0;options;constructor($){this.options=$}async record($){let f=this.options.maxConsecutiveMistakes,J=$.forceAtLimit&&f?f:this.consecutiveMistakes+1;this.consecutiveMistakes=J;let Q=$.details?.trim()||`consecutive mistake (${$.reason})`;if(this.options.emit({type:"error",error:Error(Q),recoverable:!0,iteration:$.iteration}),this.options.log("warn","Recorded consecutive mistake",{agentId:this.options.agentId,conversationId:this.options.getConversationId(),runId:this.options.getActiveRunId(),iteration:$.iteration,reason:$.reason,details:$.details,consecutiveMistakes:J,maxConsecutiveMistakes:this.options.maxConsecutiveMistakes}),!f||J<f)return{action:"continue"};let Z=await NG({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details},this.options.onLimitReached);if(Z.action==="continue"){let W=Z.guidance?.trim();if(W)this.options.appendRecoveryNotice(W,$.reason);return this.consecutiveMistakes=0,{action:"continue",guidance:W}}return{action:"stop",reason:Z.reason?.trim()||void 0,message:_G({iteration:$.iteration,consecutiveMistakes:J,maxConsecutiveMistakes:f,reason:$.reason,details:$.details,stopReason:Z.reason})}}reset(){this.consecutiveMistakes=0}get value(){return this.consecutiveMistakes}}function _G($){let f=[`Stopped after ${$.consecutiveMistakes}/${$.maxConsecutiveMistakes} consecutive mistakes (${$.reason}) at iteration ${$.iteration}.`],J=$.details?.trim();if(J)f.push(`Error: ${J}`);let Q=$.stopReason?.trim();if(Q)f.push(`Decision: ${Q}`);return f.push("Session state was preserved. Send a new prompt to resume from the latest state."),f.join(" ")}async function NG($,f){if(!f)return{action:"stop",reason:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`};try{return await f($)}catch(J){return{action:"stop",reason:J instanceof Error?J.message:`maximum consecutive mistakes reached (${$.maxConsecutiveMistakes})`}}}function TG($){let f=$.content.filter((J)=>J.type==="text");if(f.length===0)return;return f.map((J)=>J.text).join("")}function MG($){let f=$.content.filter((J)=>J.type==="reasoning");if(f.length===0)return;return{reasoning:f.map((J)=>J.text).join(""),redacted:f.some((J)=>J.redacted===!0)}}function qG($){return $.content.find((f)=>f.type==="tool-result")}function yG($){switch($){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}function wG($){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 hJ{lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0};toolStartedAt=new Map;translate($){switch($.type){case"run-started":return[];case"message-added":return[];case"turn-started":return[{type:"iteration_start",iteration:$.iteration}];case"turn-finished":return[{type:"iteration_end",iteration:$.iteration,hadToolCalls:$.toolCallCount>0,toolCallCount:$.toolCallCount}];case"assistant-text-delta":return[{type:"content_start",contentType:"text",text:$.text,accumulated:$.accumulatedText}];case"assistant-reasoning-delta":return[{type:"content_start",contentType:"reasoning",reasoning:$.text,redacted:$.redacted===!0}];case"assistant-message":return this.translateAssistantMessage($.message);case"tool-started":return this.translateToolStarted($);case"tool-updated":return[{type:"content_update",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,update:$.update}];case"tool-finished":return this.translateToolFinished($);case"usage-updated":return this.translateUsage($.usage);case"status-notice":return[{type:"notice",noticeType:"status",displayRole:"status",message:$.message,reason:$.metadata?.reason==="auto_compaction"?"auto_compaction":void 0,metadata:$.metadata}];case"run-finished":return this.translateRunFinished($.result);case"run-failed":return[{type:"error",error:$.error,recoverable:!1,iteration:$.snapshot.iteration}];default:return $}}reset(){this.lastUsage={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0},this.toolStartedAt.clear()}translateAssistantMessage($){let f=[],J=TG($);if(J!==void 0)f.push({type:"content_end",contentType:"text",text:J});let Q=MG($);if(Q!==void 0)f.push({type:"content_end",contentType:"reasoning",reasoning:Q.reasoning});return f}translateToolStarted($){return this.toolStartedAt.set($.toolCall.toolCallId,Date.now()),[{type:"content_start",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,input:$.toolCall.input}]}translateToolFinished($){let f=this.toolStartedAt.get($.toolCall.toolCallId),J=f===void 0?void 0:Date.now()-f;this.toolStartedAt.delete($.toolCall.toolCallId);let Q=qG($.message),Z=Q?.output,W=wG(Q);return[{type:"content_end",contentType:"tool",toolName:$.toolCall.toolName,toolCallId:$.toolCall.toolCallId,output:Z,error:W,durationMs:J}]}translateUsage($){let f=$.inputTokens-this.lastUsage.inputTokens,J=$.outputTokens-this.lastUsage.outputTokens,Q=$.cacheReadTokens-this.lastUsage.cacheReadTokens,Z=$.cacheWriteTokens-this.lastUsage.cacheWriteTokens,W=this.lastUsage.totalCost??0,X=($.totalCost??0)-W;return this.lastUsage={inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheReadTokens:$.cacheReadTokens,cacheWriteTokens:$.cacheWriteTokens,totalCost:$.totalCost},[{type:"usage",inputTokens:Math.max(0,f),outputTokens:Math.max(0,J),cacheReadTokens:Q===0?void 0:Math.max(0,Q),cacheWriteTokens:Z===0?void 0:Math.max(0,Z),cost:X===0?void 0:X,totalInputTokens:$.inputTokens,totalOutputTokens:$.outputTokens,totalCacheReadTokens:$.cacheReadTokens===0?void 0:$.cacheReadTokens,totalCacheWriteTokens:$.cacheWriteTokens===0?void 0:$.cacheWriteTokens,totalCost:$.totalCost}]}translateRunFinished($){let f={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens===0?void 0:$.usage.cacheReadTokens,cacheWriteTokens:$.usage.cacheWriteTokens===0?void 0:$.usage.cacheWriteTokens,totalCost:$.usage.totalCost};return[{type:"done",reason:yG($.status),text:$.outputText,iterations:$.iterations,usage:f}]}}function xG($){if(typeof $==="string")return $;if($ instanceof Error)return $.message;try{return JSON.stringify($)}catch{return String($)}}async function mG($){let J=(typeof $.content==="function"?await $.content():$.content).trim();return J.length>0?J:void 0}function gG($,f){let J=$.trim(),Q=f.map((Z)=>Z.trim()).filter(Boolean).join(`
142
142
 
143
143
  `);if(J&&Q)return`${J}
144
144
 
145
- ${Q}`;return J||Q}function FK($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let Q of f){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of f)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of f){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of f){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of f){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of f){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of f)await Q.onEvent?.(J)}}}class N${config;agentId;parentAgentId;logger;telemetry;conversation;mistakeTracker;loopTracker;loopDetectionDisabled;messageBuilder;contributionRegistry;extensionsInitialized=!1;listeners=new Set;createAgentRuntimeImpl;activeRunId=null;running=!1;abortRequested=!1;abortReason;activeRuntime=null;activeRunPromise=null;eventAdapter=new LJ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??AK,this.conversation=new FJ($.initialMessages),this.messageBuilder=new GJ,this.contributionRegistry=BK({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new UJ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,X)=>DK(this.logger,W,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new RJ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of $)if(!f.has(Q.name))J.push(Q),f.add(Q.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await GK(f);if(J)$.push(J)}return PK(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let P=await UK(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:P})}let Q=await this.composeSystemPrompt(),Z=YZ(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let P of W)j.set(P.name,P);for(let P of this.config.tools)j.set(P.name,P);let X=this.conversation.getConversationId(),H=OZ(this.config),Y=Array.from(j.values()),V=D8(this.conversation.getMessages()),A=RZ({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,Y),initialMessages:V,systemPrompt:Q}),B=this.createAgentRuntimeImpl(A);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let K=B.subscribe((P)=>{this.handleRuntimeEvent(P)}),G,R;try{if($.isContinue)G=await B.continue(void 0);else G=await B.run("")}catch(P){R=P instanceof Error?P:Error(String(P))}finally{K();try{await this.activeTrackerWork}catch(P){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:P})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(G&&G.messages.length>0){let P=g1(G.messages);this.conversation.replaceMessages(P)}let F=new Date;try{return this.buildLegacyResult({runResult:G,thrownError:R,startedAt:f,endedAt:F})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=FK([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let Q=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=g1(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:D8(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(PZ($));return D8(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)f=await Q.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((H)=>H.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?KK(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(g1($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=g1(f).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:f});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:Q,endedAt:Z}=$,W=Z.getTime()-Q.getTime(),j=J?"error":RK(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",H=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?g1(f.messages):this.conversation.getMessages(),V=OZ(this.config);if(J)throw J;return{text:X,usage:H,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:Q,endedAt:Z,durationMs:W}}}function DK($,f,J,Q){if(!$)return;if(f==="debug"){$.debug(J,Q);return}if(f==="error"&&$.error){$.error(J,Q);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...Q,severity:Z})}function RK($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function UK($,f,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => LZ);return Z($,f,J,Q)}function OZ($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=BJ($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as zZ}from"@cline/shared";function _Z($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zZ({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
146
- ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function yZ($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return zZ({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function R8($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function Lf($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?_Z($.prompt,f):yZ($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function U8($){let f=Lf($),J=new N$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var zK=OJ.object({systemPrompt:OJ.string().describe("System prompt defining the sub-agent's behavior"),task:OJ.string().describe("Task for the sub-agent to complete")});function m1($){return LK({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:OK(zK),execute:async(f,J)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=U8({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:X,input:f})}catch{}try{let H=await Z.run(f.task),Y={text:H.text,iterations:H.iterations,finishReason:H.finishReason,usage:{inputTokens:H.usage.inputTokens,outputTokens:H.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,result:Y,agentResult:H})}catch{}return Y}catch(H){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,error:H instanceof Error?H:Error(String(H))})}catch{}throw H}},timeoutMs:300000,retryable:!1})}import{createTool as J0,TEAM_AWAIT_TIMEOUT_MS as _K,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as yK,TEAM_RUN_TEXT_PREVIEW_LIMIT as NK,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as TK,TeamAttachOutcomeFragmentInputSchema as NZ,TeamAwaitRunsInputSchema as TZ,TeamBroadcastInputSchema as MZ,TeamBroadcastToolResultSchema as MK,TeamCancelRunInputSchema as qZ,TeamCancelRunToolResultSchema as qK,TeamCleanupInputSchema as wZ,TeamCleanupToolResultSchema as wK,TeamCreateOutcomeInputSchema as SZ,TeamCreateOutcomeToolResultSchema as SK,TeamFinalizeOutcomeInputSchema as CZ,TeamFinalizeOutcomeToolResultSchema as CK,TeamListOutcomesInputSchema as EZ,TeamListRunsInputSchema as hZ,TeamMailboxMessageToolResultSchema as EK,TeamMissionLogInputSchema as bZ,TeamMissionLogToolResultSchema as hK,TeamOutcomeFragmentToolResultSchema as kZ,TeamOutcomeToolResultSchema as bK,TeamReadMailboxInputSchema as IZ,TeamReviewOutcomeFragmentInputSchema as xZ,TeamRunTaskInputSchema as gZ,TeamRunTaskToolResultSchema as zJ,TeamRunToolSummarySchema as _J,TeamSendMessageInputSchema as mZ,TeamSendMessageToolResultSchema as kK,TeamShutdownTeammateInputSchema as vZ,TeamSimpleAgentStatusToolResultSchema as cZ,TeamSpawnTeammateInputSchema as uZ,TeamStatusInputSchema as dZ,TeamStatusToolResultSchema as IK,TeamTaskInputSchema as lZ,TeamTaskToolResultSchema as Of,validateWithZod as w,zodToJsonSchema as Q0}from"@cline/shared";function pZ($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function Q1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function xK($){let f=$.result;if(!f)return;return{textPreview:pZ(f.text,NK),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function L8($){return $?.toISOString()}function yJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:pZ($.message,yK),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:L8($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:L8($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:L8($.heartbeatAt),lastProgressAt:L8($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:xK($)}}function gK($){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 O8=["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 rZ($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...zf({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:Lf({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function z8($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,Q=zf({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let W of $.restoredTeammates??[]){if($.runtime.isTeammateActive(W.agentId))continue;rZ({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function zf($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,Z=[];if(J)Z.push(J0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Q0(uZ),execute:async(j)=>{let X=w(uZ,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let H={agentId:X.agentId,rolePrompt:X.rolePrompt};if(rZ({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:H}),!Q)$.onLeadToolsUnlocked?.(zf({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return w(cZ,{agentId:X.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(J0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Q0(vZ),execute:async(j)=>{let X=w(vZ,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),w(cZ,{agentId:X.agentId,status:"stopped"})}})),Z.push(J0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Q0(dZ),execute:async(j)=>{return w(dZ,j),w(IK,$.runtime.getSnapshot())}})),Z.push(J0({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:Q0(lZ),execute:async(j)=>{let X=w(lZ,j);switch(X.action){case"create":{let H=new Set(TK.create??[]),Y=Object.entries(j).filter(([A,B])=>H.has(A)&&B!=null).map(([A])=>A),V=$.runtime.createTask({title:Q1(X.title,"title"),description:Q1(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return w(Of,{action:"create",taskId:V.id,status:V.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return w(Of,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let H=$.runtime.claimTask(Q1(X.taskId,"taskId"),$.requesterId);return w(Of,{action:"claim",taskId:H.id,status:H.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let H=$.runtime.completeTask(Q1(X.taskId,"taskId"),$.requesterId,Q1(X.summary,"summary"));return w(Of,{action:"complete",taskId:H.id,status:H.status})}case"block":{let H=$.runtime.blockTask(Q1(X.taskId,"taskId"),$.requesterId,Q1(X.reason,"reason"));return w(Of,{action:"block",taskId:H.id,status:H.status})}}}}));let W=new Map;return Z.push(J0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Q0(gZ),execute:async(j)=>{let X=w(gZ,j);if(X.runMode==="async"){let V=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return w(zJ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${V.id}.`,runId:V.id})}let H=W.get(X.agentId);if(H){let V=await H;return w(zJ,{...V,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((V)=>w(zJ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{W.delete(X.agentId)});return W.set(X.agentId,Y),await Y}})),Z.push(J0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Q0(qZ),execute:async(j)=>{let X=w(qZ,j),H=$.runtime.cancelRun(X.runId,X.reason);return w(qK,{runId:H.id,status:H.status})}})),Z.push(J0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Q0(hZ),execute:async(j)=>w(_J.array(),$.runtime.listRuns(w(hZ,j)).map(yJ))})),Z.push(J0({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:Q0(TZ),timeoutMs:_K,execute:async(j)=>{let X=w(TZ,j);if(X.runId){let V=await $.runtime.awaitRun(X.runId);return gK(V),w(_J,yJ(V))}let H=await $.runtime.awaitAllRuns(),Y=H.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(Y.length>0){let V=Y.map((A)=>`${A.id}:${A.status}${A.error?`(${A.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return w(_J.array(),H.map(yJ))}})),Z.push(J0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Q0(mZ),execute:async(j)=>{let X=w(mZ,j),H=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return w(kK,{id:H.id,toAgentId:H.toAgentId})}})),Z.push(J0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Q0(MZ),execute:async(j)=>{let X=w(MZ,j),H=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return w(MK,{delivered:H.length})}})),Z.push(J0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Q0(IZ),execute:async(j)=>{let X=w(IZ,j);return w(EK.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(J0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Q0(bZ),execute:async(j)=>{let X=w(bZ,j),H=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return w(hK,{id:H.id})}})),Z.push(J0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Q0(wZ),execute:async(j)=>{if(w(wZ,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),w(wK,{status:"cleaned"})}})),Z.push(J0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Q0(SZ),execute:async(j)=>{let X=w(SZ,j),H=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return w(SK,{outcomeId:H.id,status:H.status,requiredSections:H.requiredSections})}})),Z.push(J0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Q0(NZ),execute:async(j)=>{let X=w(NZ,j),H=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return w(kZ,{fragmentId:H.id,status:H.status})}})),Z.push(J0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Q0(xZ),execute:async(j)=>{let X=w(xZ,j),H=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return w(kZ,{fragmentId:H.id,status:H.status})}})),Z.push(J0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Q0(CZ),execute:async(j)=>{let X=w(CZ,j),H=$.runtime.finalizeOutcome(X.outcomeId);return w(CK,{outcomeId:H.id,status:H.status})}})),Z.push(J0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Q0(EZ),execute:async(j)=>{return w(EZ,j),w(bK.array(),$.runtime.listOutcomes())}})),Z}function iZ($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}var mK=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:m1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...O8]}],vK={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function cK($){return $==="plan"||$==="yolo"?$:"act"}function aZ($){let f=cK($.mode),J=p0[y$({mode:f})],Q=Rf($.providerId??"",$.modelId??"",f,Df);return{mode:f,flags:{...J,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function nZ($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=aZ(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=vK[$];return Q?J[Q]===!0:!1}function uK($,f){if($.id==="editor"){let{flags:J}=aZ(f),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:nZ($.id,f),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:nZ($.id,f)}}function _f($={}){return mK.map((f)=>uK(f,$))}function tZ($={}){return _f($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function sZ($){if(!$.enabled)return new Set;let f=_f($.availabilityContext),J=new Set(f.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function NJ($,f={}){return _f(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function oZ($,f={}){return NJ($,f)}function yf($={}){let{executorOptions:f={},executors:J,...Q}=$,Z={...F8(f),...J??{}};return I1({...Q,executors:Z})}function _8($){return $.trim().replace(/^\/+/,"").toLowerCase()}function dK($){if(!$||$.length===0)return;let f=$.map(_8).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function lK($,f,J){if(!J)return!0;let Q=_8($),Z=_8(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function Nf($,f){let J=dK(f);return[...$.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>lK(Z.id,Z.name,J))}function pK($,f){return Nf($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function rK($,f,J){let Q=_8(f);if(!Q)return{error:"Missing skill name."};let Z=Nf($,J),W=Z.find((V)=>V.id===Q);if(W){let{skill:V}=W;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:W.id,skill:V}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=Z.filter(({id:V})=>{if(V===j)return!0;return V.endsWith(`:${j}`)}),H=X.filter(({skill:V})=>V.disabled!==!0);if(H.length===1){let{id:V,skill:A}=H[0];return{id:V,skill:A}}if(H.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${H.map(({id:V})=>V).join(", ")}`};if(X.length===1){let{skill:V}=X[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:V})=>V).join(", ")}`};let Y=pK($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function iK($,f=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await f;let X=rK($,W,J);if("error"in X)return X.error;let{id:H,skill:Y}=X;if(Q.has(H))return`Skill "${Y.name}" is already running.`;Q.add(H);try{let V=j?.trim(),A=V?`
145
+ ${Q}`;return J||Q}function vG($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return{};return{beforeRun:async(J)=>{for(let Q of f){let Z=await Q.beforeRun?.(J);if(Z?.stop)return Z}return},afterRun:async(J)=>{for(let Q of f)await Q.afterRun?.(J)},beforeModel:async(J)=>{let Q=J.request,Z;for(let W of f){let j=await W.beforeModel?.({...J,request:Q});if(!j)continue;if(j.stop)return j;Z={...Z,...j,options:{...Z?.options??{},...j.options??{}}},Q={...Q,...j.messages?{messages:j.messages}:{},...j.tools?{tools:j.tools}:{},...j.options?{options:{...Q.options??{},...j.options}}:{}}}return Z},afterModel:async(J)=>{for(let Q of f){let Z=await Q.afterModel?.(J);if(Z?.stop)return Z}return},beforeTool:async(J)=>{let Q=J.input,Z;for(let W of f){let j=await W.beforeTool?.({...J,input:Q});if(!j)continue;if(j.stop||j.skip)return j;if(Z={...Z,...j},Object.hasOwn(j,"input"))Q=j.input}return Z},afterTool:async(J)=>{let Q=J.result,Z;for(let W of f){let j=await W.afterTool?.({...J,result:Q});if(!j)continue;if(j.stop)return j;if(Z={...Z,...j},j.result)Q=j.result}return Z},onEvent:async(J)=>{for(let Q of f)await Q.onEvent?.(J)}}}class T${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 hJ;shutdownCalled=!1;currentRunToolCalls=[];currentRunUsage={inputTokens:0,outputTokens:0};toolStartedAt=new Map;toolInputs=new Map;currentTurnSuccessfulTools=0;currentTurnFailedTools=0;currentTurnFailureDetails=[];activeTrackerWork=Promise.resolve();trackerAbortInFlight=!1;constructor($,f={}){this.config=$,this.agentId=`agent_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,this.parentAgentId=$.parentAgentId,this.logger=f.logger??$.logger,this.telemetry=f.telemetry??$.telemetry,this.createAgentRuntimeImpl=f.createAgentRuntimeImpl??kG,this.conversation=new qJ($.initialMessages),this.messageBuilder=new TJ,this.contributionRegistry=IG({extensions:$.extensions?[...$.extensions]:[],setupContext:{session:$.extensionContext?.session,client:$.extensionContext?.client,user:$.extensionContext?.user,workspaceInfo:$.extensionContext?.workspace,automation:$.extensionContext?.automation,logger:$.extensionContext?.logger??this.logger,telemetry:$.extensionContext?.telemetry??this.telemetry}}),this.contributionRegistry.resolve(),this.contributionRegistry.validate();let J=$.execution?.maxConsecutiveMistakes??6;this.mistakeTracker=new SJ({maxConsecutiveMistakes:J,onLimitReached:$.onConsecutiveMistakeLimitReached,emit:(W)=>this.emitLegacyEvent(W),log:(W,j,X)=>uG(this.logger,W,j,X),agentId:this.agentId,getConversationId:()=>this.conversation.getConversationId(),getActiveRunId:()=>this.activeRunId??"",appendRecoveryNotice:(W,j)=>{this.conversation.appendMessage({role:"user",content:[{type:"text",text:W}]})}});let Q=$.execution?.loopDetection;this.loopDetectionDisabled=Q===!1;let Z=Q===!1||Q===void 0?void 0:Q;this.loopTracker=new wJ(Z)}getAgentId(){return this.agentId}getConversationId(){return this.conversation.getConversationId()}getMessages(){return this.conversation.getMessages()}canStartRun(){return!this.running&&!this.shutdownCalled}getExtensionRegistry(){return this.contributionRegistry.getRegistrySnapshot()}addTools($){if($.length===0)return;let f=new Set(this.config.tools.map((Q)=>Q.name)),J=[...this.config.tools];for(let Q of $)if(!f.has(Q.name))J.push(Q),f.add(Q.name);this.config={...this.config,tools:J}}updateConnection($){let f={...this.config};if($.providerId!==void 0)f.providerId=$.providerId;if($.modelId!==void 0)f.modelId=$.modelId;if($.apiKey!==void 0)f.apiKey=$.apiKey;if($.baseUrl!==void 0)f.baseUrl=$.baseUrl;if($.headers!==void 0)f.headers=$.headers;if($.providerConfig!==void 0)f.providerConfig=$.providerConfig;if($.reasoningEffort!==void 0)f.reasoningEffort=$.reasoningEffort;if($.thinking!==void 0)f.thinking=$.thinking;if($.thinkingBudgetTokens!==void 0)f.thinkingBudgetTokens=$.thinkingBudgetTokens;this.config=f}clearHistory(){this.conversation.clearHistory(),this.resetConversationBoundaryTrackers()}restore($){this.conversation.restore($),this.resetConversationBoundaryTrackers()}resetConversationBoundaryTrackers(){this.mistakeTracker.reset(),this.loopTracker.reset()}subscribeEvents($){return this.listeners.add($),()=>{this.listeners.delete($)}}abort($){let f=typeof $==="string"?$:$ instanceof Error?$.message:$===void 0?void 0:String($);if(this.abortRequested=!0,this.abortReason=f,this.activeRunPromise)this.activeRunPromise.catch(()=>{});this.activeRuntime?.abort(f)}async shutdown($,f){if(this.running){if(!this.abortRequested||!this.activeRunPromise)throw Error(`SessionRuntime.shutdown called while a run is in progress (agentId=${this.agentId})`);await this.activeRunPromise}if(this.shutdownCalled)return;this.shutdownCalled=!0}run($,f,J){return this.conversation.resetForRun(),this.resetConversationBoundaryTrackers(),this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!1})}continue($,f,J){return this.executeRun({userMessage:$,userImages:f,userFiles:J,isContinue:!0})}async composeSystemPrompt(){let $=[];for(let f of this.contributionRegistry.getRegisteredRules()){let J=await mG(f);if(J)$.push(J)}return gG(this.config.systemPrompt,$)}executeRun($){let f;return f=this.executeRunInternal($).finally(()=>{if(this.activeRunPromise===f)this.activeRunPromise=null}),this.activeRunPromise=f,f}async executeRunInternal($){if(this.shutdownCalled)throw Error(`SessionRuntime.run called after shutdown (agentId=${this.agentId})`);if(this.running)throw Error(`SessionRuntime state is "running"; call canStartRun() first (agentId=${this.agentId})`);this.running=!0,this.abortRequested=!1,this.abortReason=void 0,this.activeRunId=`run_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,await this.ensureExtensionsInitialized(),this.eventAdapter.reset(),this.currentRunToolCalls=[],this.currentRunUsage={inputTokens:0,outputTokens:0},this.toolStartedAt.clear(),this.toolInputs.clear(),this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[],this.activeTrackerWork=Promise.resolve(),this.trackerAbortInFlight=!1;let f=new Date,J=$.userMessage;if(J!==void 0){let P=await dG(J,$.userImages,$.userFiles,this.config.userFileContentLoader);this.conversation.appendMessage({role:"user",content:P})}let Q=await this.composeSystemPrompt(),Z=NZ(this.config,this.logger,this.telemetry),W=this.contributionRegistry.getRegisteredTools(),j=new Map;for(let P of W)j.set(P.name,P);for(let P of this.config.tools)j.set(P.name,P);let X=this.conversation.getConversationId(),H=IZ(this.config),Y=Array.from(j.values()),V=_4(this.conversation.getMessages()),A=EZ({agentConfig:this.config,sessionId:this.config.sessionId,agentId:this.agentId,conversationId:X,parentAgentId:this.parentAgentId,model:Z,logger:this.logger,telemetry:this.telemetry,tools:Y,toolContextMetadata:{modelSupportsImages:H?.capabilities?.includes("images")??!0,...this.config.toolContextMetadata},hooks:this.createRuntimeHooks(),prepareTurn:this.createRuntimePrepareTurn(H,Y),initialMessages:V,systemPrompt:Q}),B=this.createAgentRuntimeImpl(A);if(this.activeRuntime=B,this.abortRequested)B.abort(this.abortReason);let G=B.subscribe((P)=>{this.handleRuntimeEvent(P)}),K,D;try{if($.isContinue)K=await B.continue(void 0);else K=await B.run("")}catch(P){D=P instanceof Error?P:Error(String(P))}finally{G();try{await this.activeTrackerWork}catch(P){this.logger?.error?.("SessionRuntime tracker work failed during drain",{agentId:this.agentId,error:P})}this.activeRuntime=null,this.running=!1,this.abortRequested=!1,this.abortReason=void 0}if(K&&K.messages.length>0){let P=v1(K.messages);this.conversation.replaceMessages(P)}let F=new Date;try{return this.buildLegacyResult({runResult:K,thrownError:D,startedAt:f,endedAt:F})}finally{this.activeRunId=null}}async ensureExtensionsInitialized(){if(this.extensionsInitialized)return;try{await this.contributionRegistry.initialize()}catch($){if(this.config.hookErrorMode==="throw")throw $;this.emitLegacyEvent({type:"error",error:$ instanceof Error?$:Error(String($)),recoverable:!0,iteration:0})}this.extensionsInitialized=!0}createRuntimeHooks(){let $=vG([this.config.hooks,...this.contributionRegistry.getValidatedExtensions().map((f)=>f.hooks)]);return{...$,beforeModel:async(f)=>{let J=await $.beforeModel?.(f);if(J?.stop)return J;let Q=J?.messages??f.request.messages,Z=await this.prepareMessagesForModelRequest(Q);return{...J,messages:Z}}}}createRuntimePrepareTurn($,f){let J=this.config.prepareTurn;if(!J)return;return async(Q)=>{let Z=v1(Q.messages),W=await this.prepareProviderMessagesForApi(Z),j=await J({agentId:Q.agentId,conversationId:Q.conversationId??this.conversation.getConversationId(),parentAgentId:Q.parentAgentId??null,iteration:Q.iteration,messages:Z,apiMessages:W,abortSignal:Q.signal??new AbortController().signal,systemPrompt:Q.systemPrompt??"",tools:f,model:{id:this.config.modelId,provider:this.config.providerId,info:$},emitStatusNotice:Q.emitStatusNotice});if(!j)return;return{...j.messages?{messages:_4(j.messages)}:{},...j.systemPrompt!==void 0?{systemPrompt:j.systemPrompt}:{}}}}async prepareMessagesForModelRequest($){let f=await this.prepareProviderMessagesForApi(SZ($));return _4(f)}async prepareProviderMessagesForApi($){let f=$,J=this.contributionRegistry.getRegistrySnapshot().messageBuilder;for(let Q of J)f=await Q.build(f);return this.messageBuilder.buildForApi(f)}handleRuntimeEvent($){switch($.type){case"message-added":case"assistant-message":{this.syncConversationFromRuntimeMessage($.snapshot.messages,[$.message]);break}case"turn-started":{this.currentTurnSuccessfulTools=0,this.currentTurnFailedTools=0,this.currentTurnFailureDetails=[];break}case"tool-started":{this.toolStartedAt.set($.toolCall.toolCallId,new Date),this.toolInputs.set($.toolCall.toolCallId,$.toolCall.input),this.inspectLoopForToolCall($.toolCall.toolName,$.toolCall.input,$.iteration);break}case"tool-finished":{let f=this.toolStartedAt.get($.toolCall.toolCallId),J=new Date,Q=this.toolInputs.get($.toolCall.toolCallId);this.toolStartedAt.delete($.toolCall.toolCallId),this.toolInputs.delete($.toolCall.toolCallId);let Z=$.message.content.find((H)=>H.type==="tool-result"),W=Z?.type==="tool-result"&&Z.isError===!0,j=W?xG(Z?.type==="tool-result"?Z.output:void 0):void 0,X={id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:Q,output:Z?.type==="tool-result"?Z.output:void 0,error:j,durationMs:f===void 0?0:J.getTime()-f.getTime(),startedAt:f??J,endedAt:J};if(this.currentRunToolCalls.push(X),W){if(this.currentTurnFailedTools+=1,j)this.currentTurnFailureDetails.push(`[${$.toolCall.toolName}] ${j}`)}else this.currentTurnSuccessfulTools+=1;break}case"turn-finished":{let f=this.currentTurnFailedTools,J=this.currentTurnSuccessfulTools;if(f>0&&J===0){let Q=this.currentTurnFailureDetails.join("; ");this.enqueueMistakeRecord({iteration:$.iteration,reason:"tool_execution_failed",details:`${f} tool call(s) failed${Q?`: ${Q}`:""}`})}else if(J>0)this.mistakeTracker.reset();break}case"usage-updated":{this.currentRunUsage={inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,cacheReadTokens:$.usage.cacheReadTokens>0?$.usage.cacheReadTokens:void 0,cacheWriteTokens:$.usage.cacheWriteTokens>0?$.usage.cacheWriteTokens:void 0,totalCost:$.usage.totalCost};break}default:break}for(let f of this.eventAdapter.translate($))this.emitLegacyEvent(f)}syncConversationFromRuntimeMessage($,f){if($.length>0){this.conversation.replaceMessages(v1($));return}if(f.length===0)return;let J=new Set(this.conversation.getMessages().map((Z)=>Z.id).filter((Z)=>typeof Z==="string")),Q=v1(f).filter((Z)=>!Z.id||!J.has(Z.id));if(Q.length===0)return;this.conversation.replaceMessages([...this.conversation.getMessages(),...Q])}emitLegacyEvent($){for(let f of this.listeners)try{f($)}catch(J){this.logger?.error?.("SessionRuntime event listener threw",{agentId:this.agentId,error:J})}}inspectLoopForToolCall($,f,J){if(this.trackerAbortInFlight||this.loopDetectionDisabled)return;let Q=this.loopTracker.inspect({name:$,input:f});if(Q.kind==="ok")return;if(Q.kind==="soft"){if(Q.message)this.conversation.appendMessage({role:"user",content:[{type:"text",text:Q.message}]});return}this.enqueueMistakeRecord({iteration:J,reason:"tool_execution_failed",forceAtLimit:!0,details:Q.message??`Detected repeated tool calls to \`${$}\`; stopping to avoid a loop.`})}enqueueMistakeRecord($){if(this.trackerAbortInFlight)return;this.activeTrackerWork=this.activeTrackerWork.then(async()=>{if(this.trackerAbortInFlight)return;let f=await this.mistakeTracker.record($);if(f.action==="stop")this.trackerAbortInFlight=!0,this.conversation.appendMessage({role:"user",content:[{type:"text",text:f.message}]}),this.activeRuntime?.abort(f.reason??f.message)})}buildLegacyResult($){let{runResult:f,thrownError:J,startedAt:Q,endedAt:Z}=$,W=Z.getTime()-Q.getTime(),j=J?"error":cG(f),X=f?.outputText||(f?.status==="failed"?f.error?.message:void 0)||"",H=f?{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens>0?f.usage.cacheReadTokens:void 0,cacheWriteTokens:f.usage.cacheWriteTokens>0?f.usage.cacheWriteTokens:void 0,totalCost:f.usage.totalCost}:this.currentRunUsage,Y=f?v1(f.messages):this.conversation.getMessages(),V=IZ(this.config);if(J)throw J;return{text:X,usage:H,messages:Y,toolCalls:this.currentRunToolCalls,iterations:f?.iterations??0,finishReason:j,model:{id:this.config.modelId,provider:this.config.providerId,info:V},startedAt:Q,endedAt:Z,durationMs:W}}}function uG($,f,J,Q){if(!$)return;if(f==="debug"){$.debug(J,Q);return}if(f==="error"&&$.error){$.error(J,Q);return}let Z=f==="warn"?"warn":f==="error"?"error":"info";$.log(J,{...Q,severity:Z})}function cG($){if(!$)return"error";switch($.status){case"completed":return"completed";case"aborted":return"aborted";case"failed":return"error"}}async function dG($,f,J,Q){let{buildInitialUserContent:Z}=await Promise.resolve().then(() => kZ);return Z($,f,J,Q)}function IZ($){if($.knownModels?.[$.modelId])return $.knownModels[$.modelId];let f=_J($);if(f?.[$.modelId])return f[$.modelId];return}import{buildClineSystemPrompt as xZ}from"@cline/shared";function mZ($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return xZ({ide:f.clineIdeName?.trim()||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,rules:`# Team Teammate Role
146
+ ${J}`,platform:f.clinePlatform,metadata:f.workspaceMetadata})}function gZ($,f){let J=$.trim();if(f.providerId.toLowerCase()!=="cline")return J;return xZ({ide:f.clineIdeName||"Terminal",workspaceRoot:f.cwd?.trim()||"/",providerId:f.providerId,overridePrompt:J,metadata:f.workspaceMetadata,platform:f.clinePlatform})}function N4($){let f={...$};return{getRuntimeConfig:()=>f,getConnectionConfig:()=>({providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking}),updateConnectionDefaults:(J)=>{f={...f,...J}}}}function z2($){let f=$.configProvider.getRuntimeConfig(),J=$.kind==="teammate"?mZ($.prompt,f):gZ($.prompt,f);return{...$.configProvider.getConnectionConfig(),systemPrompt:J,tools:$.tools,maxIterations:$.maxIterations??f.maxIterations,parentAgentId:$.parentAgentId,abortSignal:$.abortSignal,onEvent:$.onEvent,hooks:f.hooks,extensions:f.extensions,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval,logger:f.logger,role:$.role}}function T4($){let f=z2($),J=new T$(f);if(f.onEvent)J.subscribeEvents(f.onEvent);return J}var rG=CJ.object({systemPrompt:CJ.string().describe("System prompt defining the sub-agent's behavior"),task:CJ.string().describe("Task for the sub-agent to complete")});function u1($){return lG({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:pG(rG),execute:async(f,J)=>{let Q=$.createSubAgentTools?await $.createSubAgentTools(f,J):$.subAgentTools??[],Z=T4({kind:"subagent",prompt:f.systemPrompt,configProvider:$.configProvider,tools:Q,maxIterations:$.defaultMaxIterations,parentAgentId:J.agentId,abortSignal:J.signal,onEvent:$.onSubAgentEvent,hookErrorMode:$.hookErrorMode,toolPolicies:$.toolPolicies,requestToolApproval:$.requestToolApproval}),W=Z.getAgentId(),j=Z.getConversationId(),X=J.agentId;if($.onSubAgentStart)try{await $.onSubAgentStart({subAgentId:W,conversationId:j,parentAgentId:X,input:f})}catch{}try{let H=await Z.run(f.task),Y={text:H.text,iterations:H.iterations,finishReason:H.finishReason,usage:{inputTokens:H.usage.inputTokens,outputTokens:H.usage.outputTokens}};if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,result:Y,agentResult:H})}catch{}return Y}catch(H){if($.onSubAgentEnd)try{await $.onSubAgentEnd({subAgentId:W,conversationId:j,parentAgentId:X,input:f,error:H instanceof Error?H:Error(String(H))})}catch{}throw H}},timeoutMs:300000,retryable:!1})}import{createTool as Q0,TEAM_AWAIT_TIMEOUT_MS as iG,TEAM_RUN_MESSAGE_PREVIEW_LIMIT as nG,TEAM_RUN_TEXT_PREVIEW_LIMIT as aG,TEAM_TASK_IGNORED_FIELDS_BY_ACTION as tG,TeamAttachOutcomeFragmentInputSchema as vZ,TeamAwaitRunsInputSchema as uZ,TeamBroadcastInputSchema as cZ,TeamBroadcastToolResultSchema as sG,TeamCancelRunInputSchema as dZ,TeamCancelRunToolResultSchema as oG,TeamCleanupInputSchema as lZ,TeamCleanupToolResultSchema as eG,TeamCreateOutcomeInputSchema as pZ,TeamCreateOutcomeToolResultSchema as $K,TeamFinalizeOutcomeInputSchema as rZ,TeamFinalizeOutcomeToolResultSchema as fK,TeamListOutcomesInputSchema as iZ,TeamListRunsInputSchema as nZ,TeamMailboxMessageToolResultSchema as JK,TeamMissionLogInputSchema as aZ,TeamMissionLogToolResultSchema as QK,TeamOutcomeFragmentToolResultSchema as tZ,TeamOutcomeToolResultSchema as ZK,TeamReadMailboxInputSchema as sZ,TeamReviewOutcomeFragmentInputSchema as oZ,TeamRunTaskInputSchema as eZ,TeamRunTaskToolResultSchema as EJ,TeamRunToolSummarySchema as bJ,TeamSendMessageInputSchema as $3,TeamSendMessageToolResultSchema as WK,TeamShutdownTeammateInputSchema as f3,TeamSimpleAgentStatusToolResultSchema as J3,TeamSpawnTeammateInputSchema as Q3,TeamStatusInputSchema as Z3,TeamStatusToolResultSchema as jK,TeamTaskInputSchema as W3,TeamTaskToolResultSchema as _2,validateWithZod as w,zodToJsonSchema as Z0}from"@cline/shared";function j3($,f){let J=$.replace(/\s+/g," ").trim();if(J.length<=f)return J;return`${J.slice(0,Math.max(0,f-3)).trimEnd()}...`}function j1($,f){if($===void 0)throw Error(`Missing required field: ${f}`);return $}function XK($){let f=$.result;if(!f)return;return{textPreview:j3(f.text,aG),iterations:f.iterations,finishReason:f.finishReason,durationMs:f.durationMs,usage:{inputTokens:f.usage.inputTokens,outputTokens:f.usage.outputTokens,cacheReadTokens:f.usage.cacheReadTokens,cacheWriteTokens:f.usage.cacheWriteTokens,totalCost:f.usage.totalCost}}}function M4($){return $?.toISOString()}function kJ($){return{id:$.id,agentId:$.agentId,taskId:$.taskId,status:$.status,messagePreview:j3($.message,nG),priority:$.priority,retryCount:$.retryCount,maxRetries:$.maxRetries,nextAttemptAt:M4($.nextAttemptAt),continueConversation:$.continueConversation,startedAt:$.startedAt.toISOString(),endedAt:M4($.endedAt),leaseOwner:$.leaseOwner,heartbeatAt:M4($.heartbeatAt),lastProgressAt:M4($.lastProgressAt),lastProgressMessage:$.lastProgressMessage,currentActivity:$.currentActivity,error:$.error,resultSummary:XK($)}}function HK($){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 q4=["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 X3($){let f=[];if($.createBaseTools)f.push(...$.createBaseTools());f.push(...N2({runtime:$.runtime,requesterId:$.spec.agentId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!1})),$.runtime.spawnTeammate({agentId:$.spec.agentId,config:z2({kind:"teammate",prompt:$.spec.rolePrompt,role:$.spec.rolePrompt,configProvider:$.teammateConfigProvider,tools:f,maxIterations:$.spec.maxIterations,cwd:$.teammateConfigProvider.getRuntimeConfig().cwd})})}function y4($){let f=$.leadAgentId??"lead",J=$.restoredFromPersistence===!0,Q=N2({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,allowSpawn:!0,includeSpawnTool:$.includeLeadSpawnTool,includeManagementTools:$.includeLeadManagementTools,onLeadToolsUnlocked:$.onLeadToolsUnlocked}),Z=[];for(let W of $.restoredTeammates??[]){if($.runtime.isTeammateActive(W.agentId))continue;X3({runtime:$.runtime,requesterId:f,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:W}),Z.push(W.agentId)}return{tools:Q,restoredFromPersistence:J,restoredTeammates:Z}}function N2($){let f=$.allowSpawn??!0,J=$.includeSpawnTool??!0,Q=$.includeManagementTools??!0,Z=[];if(J)Z.push(Q0({name:"team_spawn_teammate",description:"Spawn a teammate with a required agentId and rolePrompt.",inputSchema:Z0(Q3),execute:async(j)=>{let X=w(Q3,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");if(!f)throw Error("Spawning teammates is disabled in this context.");let H={agentId:X.agentId,rolePrompt:X.rolePrompt};if(X3({runtime:$.runtime,requesterId:$.requesterId,teammateConfigProvider:$.teammateConfigProvider,createBaseTools:$.createBaseTools,spec:H}),!Q)$.onLeadToolsUnlocked?.(N2({...$,includeSpawnTool:!1,includeManagementTools:!0,onLeadToolsUnlocked:void 0}));return w(J3,{agentId:X.agentId,status:"spawned"})}}));if(!Q)return Z;Z.push(Q0({name:"team_shutdown_teammate",description:"Shutdown a teammate by agentId.",inputSchema:Z0(f3),execute:async(j)=>{let X=w(f3,j);if($.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can manage teammates.");return $.runtime.shutdownTeammate(X.agentId,X.reason),w(J3,{agentId:X.agentId,status:"stopped"})}})),Z.push(Q0({name:"team_status",description:"Return a snapshot of team members, task counts, mailbox, and mission log stats.",inputSchema:Z0(Z3),execute:async(j)=>{return w(Z3,j),w(jK,$.runtime.getSnapshot())}})),Z.push(Q0({name:"team_task",description:"Manage shared team tasks with action-specific payloads. create requires title and description, with optional dependsOn and assignee. list accepts optional status, assignee. claim requires taskId. complete requires taskId and summary. block requires taskId and reason. Do not include fields from other actions.",inputSchema:Z0(W3),execute:async(j)=>{let X=w(W3,j);switch(X.action){case"create":{let H=new Set(tG.create??[]),Y=Object.entries(j).filter(([A,B])=>H.has(A)&&B!=null).map(([A])=>A),V=$.runtime.createTask({title:j1(X.title,"title"),description:j1(X.description,"description"),dependsOn:X.dependsOn,assignee:X.assignee,createdBy:$.requesterId});return w(_2,{action:"create",taskId:V.id,status:V.status,...Y.length>0?{ignoredFields:Y,note:`Ignored fields for action=create: ${Y.join(", ")}`}:{}})}case"list":return w(_2,{action:"list",tasks:$.runtime.listTaskItems({status:X.status,assignee:X.assignee})});case"claim":{let H=$.runtime.claimTask(j1(X.taskId,"taskId"),$.requesterId);return w(_2,{action:"claim",taskId:H.id,status:H.status,nextStep:"Task is now in_progress. Execute the work using team_run_task or your own tools, then call team_task with action=complete when done."})}case"complete":{let H=$.runtime.completeTask(j1(X.taskId,"taskId"),$.requesterId,j1(X.summary,"summary"));return w(_2,{action:"complete",taskId:H.id,status:H.status})}case"block":{let H=$.runtime.blockTask(j1(X.taskId,"taskId"),$.requesterId,j1(X.reason,"reason"));return w(_2,{action:"block",taskId:H.id,status:H.status})}}}}));let W=new Map;return Z.push(Q0({name:"team_run_task",description:"Route a delegated task to a teammate. Choose sync (wait) or async (run in background).",inputSchema:Z0(eZ),execute:async(j)=>{let X=w(eZ,j);if(X.runMode==="async"){let V=$.runtime.startTeammateRun(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0});return w(EJ,{agentId:X.agentId,mode:"async",status:"queued",dispatched:!0,message:`Task dispatched to ${X.agentId} and queued as ${V.id}.`,runId:V.id})}let H=W.get(X.agentId);if(H){let V=await H;return w(EJ,{...V,status:"joined",deduped:!0,message:`Task for ${X.agentId} was already dispatched in this tool batch; joined the existing in-flight run.`})}let Y=$.runtime.routeToTeammate(X.agentId,X.task,{taskId:X.taskId||void 0,fromAgentId:$.requesterId,continueConversation:X.continueConversation||void 0}).then((V)=>w(EJ,{agentId:X.agentId,mode:"sync",status:"running",dispatched:!0,message:`Task dispatched to ${X.agentId} and completed in sync mode.`,text:V.text,iterations:V.iterations})).finally(()=>{W.delete(X.agentId)});return W.set(X.agentId,Y),await Y}})),Z.push(Q0({name:"team_cancel_run",description:"Cancel one async teammate run.",inputSchema:Z0(dZ),execute:async(j)=>{let X=w(dZ,j),H=$.runtime.cancelRun(X.runId,X.reason);return w(oG,{runId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_runs",description:"List teammate runs started with team_run_task in async mode, including live activity/progress fields when available.",inputSchema:Z0(nZ),execute:async(j)=>w(bJ.array(),$.runtime.listRuns(w(nZ,j)).map(kJ))})),Z.push(Q0({name:"team_await_runs",description:"Wait for async teammate runs. Provide runId to wait for one run, or omit it to wait for all active async runs. Uses a long timeout for legitimate teammate work.",inputSchema:Z0(uZ),timeoutMs:iG,execute:async(j)=>{let X=w(uZ,j);if(X.runId){let V=await $.runtime.awaitRun(X.runId);return HK(V),w(bJ,kJ(V))}let H=await $.runtime.awaitAllRuns(),Y=H.filter((V)=>["failed","cancelled","interrupted"].includes(V.status));if(Y.length>0){let V=Y.map((A)=>`${A.id}:${A.status}${A.error?`(${A.error})`:""}`).join(", ");throw Error(`One or more runs did not complete successfully: ${V}`)}return w(bJ.array(),H.map(kJ))}})),Z.push(Q0({name:"team_send_message",description:"Send a mailbox message to a specific teammate.",inputSchema:Z0($3),execute:async(j)=>{let X=w($3,j),H=$.runtime.sendMessage($.requesterId,X.toAgentId,X.subject,X.body,X.taskId??void 0);return w(WK,{id:H.id,toAgentId:H.toAgentId})}})),Z.push(Q0({name:"team_broadcast",description:"Broadcast a message to all teammates.",inputSchema:Z0(cZ),execute:async(j)=>{let X=w(cZ,j),H=$.runtime.broadcast($.requesterId,X.subject,X.body,{taskId:X.taskId??void 0});return w(sG,{delivered:H.length})}})),Z.push(Q0({name:"team_read_mailbox",description:"Read the current agent mailbox.",inputSchema:Z0(sZ),execute:async(j)=>{let X=w(sZ,j);return w(JK.array(),$.runtime.listMailbox($.requesterId,{unreadOnly:X.unreadOnly,markRead:!0}))}})),Z.push(Q0({name:"team_mission_log",description:"Append a mission log update for your team.",inputSchema:Z0(aZ),execute:async(j)=>{let X=w(aZ,j),H=$.runtime.appendMissionLog({agentId:$.requesterId,taskId:X.taskId||void 0,kind:X.kind,summary:X.summary,evidence:X.evidence?.length?X.evidence:void 0,nextAction:X.nextAction||void 0});return w(QK,{id:H.id})}})),Z.push(Q0({name:"team_cleanup",description:"Clean up the team runtime. Fails if teammates are still running.",inputSchema:Z0(lZ),execute:async(j)=>{if(w(lZ,j),$.runtime.getMemberRole($.requesterId)!=="lead")throw Error("Only the lead agent can run cleanup.");return $.runtime.cleanup(),w(eG,{status:"cleaned"})}})),Z.push(Q0({name:"team_create_outcome",description:"Create a converged team outcome.",inputSchema:Z0(pZ),execute:async(j)=>{let X=w(pZ,j),H=$.runtime.createOutcome({title:X.title,requiredSections:X.requiredSections,createdBy:$.requesterId});return w($K,{outcomeId:H.id,status:H.status,requiredSections:H.requiredSections})}})),Z.push(Q0({name:"team_attach_outcome_fragment",description:"Attach a fragment to an outcome section.",inputSchema:Z0(vZ),execute:async(j)=>{let X=w(vZ,j),H=$.runtime.attachOutcomeFragment({outcomeId:X.outcomeId,section:X.section,sourceAgentId:$.requesterId,sourceRunId:X.sourceRunId||void 0,content:X.content});return w(tZ,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_review_outcome_fragment",description:"Review one outcome fragment.",inputSchema:Z0(oZ),execute:async(j)=>{let X=w(oZ,j),H=$.runtime.reviewOutcomeFragment({fragmentId:X.fragmentId,reviewedBy:$.requesterId,approved:X.approved});return w(tZ,{fragmentId:H.id,status:H.status})}})),Z.push(Q0({name:"team_finalize_outcome",description:"Finalize one outcome.",inputSchema:Z0(rZ),execute:async(j)=>{let X=w(rZ,j),H=$.runtime.finalizeOutcome(X.outcomeId);return w(fK,{outcomeId:H.id,status:H.status})}})),Z.push(Q0({name:"team_list_outcomes",description:"List team outcomes.",inputSchema:Z0(iZ),execute:async(j)=>{return w(iZ,j),w(ZK.array(),$.runtime.listOutcomes())}})),Z}function H3($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}var YK=[{id:"read_files",description:"Read the full content of text or image files at the provided absolute paths, or return only an inclusive one-based line range when start_line/end_line are provided.",headlessToolNames:["read_files"]},{id:"search_codebase",description:"Perform regex pattern searches across the codebase for code patterns, definitions, imports, and other text matches.",headlessToolNames:["search_codebase"]},{id:"run_commands",description:"Run shell commands from the root of the workspace for listing files, checking git status, builds, tests, and similar tasks.",headlessToolNames:["run_commands"]},{id:"editor",description:"Make controlled filesystem edits on text files with create, replace, and insert operations.",headlessToolNames:["editor"]},{id:"fetch_web_content",description:"Fetch URL content and analyze it with a prompt describing what to extract.",headlessToolNames:["fetch_web_content"]},{id:"skills",description:"Execute a configured skill within the main conversation when a matching skill exists for the task.",headlessToolNames:["skills"]},{id:"ask_question",description:"Ask the user a single clarifying question with 2-5 selectable options.",headlessToolNames:["ask_question"]},{id:"spawn_agent",description:u1({configProvider:{}}).description,headlessToolNames:["spawn_agent"]},{id:"teams",description:"Enable team collaboration tools for teammate management, task coordination, mailbox messaging, mission logs, and outcomes.",headlessToolNames:[...q4]}],VK={read_files:"enableReadFiles",search_codebase:"enableSearch",run_commands:"enableBash",fetch_web_content:"enableWebFetch",apply_patch:"enableApplyPatch",editor:"enableEditor",skills:"enableSkills",ask_question:"enableAskQuestion"};function AK($){return $==="plan"||$==="yolo"?$:"act"}function V3($){let f=AK($.mode),J=r0[N$({mode:f})],Q=L2($.providerId??"",$.modelId??"",f,R2);return{mode:f,flags:{...J,...Q,...typeof $.enableSpawnAgent==="boolean"?{enableSpawnAgent:$.enableSpawnAgent}:{},...typeof $.enableAgentTeams==="boolean"?{enableAgentTeams:$.enableAgentTeams}:{}}}}function Y3($,f){if(f.disabledToolIds?.has($))return!1;let{flags:J}=V3(f);if($==="spawn_agent")return J.enableSpawnAgent===!0;if($==="teams")return J.enableAgentTeams===!0;if($==="editor")return J.enableEditor===!0||J.enableApplyPatch===!0;let Q=VK[$];return Q?J[Q]===!0:!1}function BK($,f){if($.id==="editor"){let{flags:J}=V3(f),Q=J.enableApplyPatch===!0&&J.enableEditor!==!0;return{...$,defaultEnabled:Y3($.id,f),headlessToolNames:[Q?"apply_patch":"editor"]}}return{...$,defaultEnabled:Y3($.id,f)}}function T2($={}){return YK.map((f)=>BK(f,$))}function A3($={}){return T2($).filter((f)=>f.defaultEnabled).map((f)=>f.id)}function B3($){if(!$.enabled)return new Set;let f=T2($.availabilityContext),J=new Set(f.map((Q)=>Q.id));if(!$.allowlist||$.allowlist.length===0)return new Set(f.filter((Q)=>Q.defaultEnabled).map((Q)=>Q.id));for(let Q of $.allowlist)if(!J.has(Q))throw Error(`Unknown tool "${Q}". Available tools: ${f.map((Z)=>Z.id).join(", ")}`);return new Set($.allowlist)}function IJ($,f={}){return T2(f).filter((J)=>$.has(J.id)).flatMap((J)=>J.headlessToolNames)}function G3($,f={}){return IJ($,f)}function M2($={}){let{executorOptions:f={},executors:J,...Q}=$,Z={...z4(f),...J??{}};return m1({...Q,executors:Z})}function w4($){return $.trim().replace(/^\/+/,"").toLowerCase()}function GK($){if(!$||$.length===0)return;let f=$.map(w4).filter((J)=>J.length>0);return f.length>0?new Set(f):void 0}function KK($,f,J){if(!J)return!0;let Q=w4($),Z=w4(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function q2($,f){let J=GK(f);return[...$.getSnapshot("skill").entries()].map(([Z,W])=>{let j=W.item;return{id:Z,name:j.name.trim(),description:j.description?.trim(),disabled:j.disabled===!0,skill:j}}).filter((Z)=>KK(Z.id,Z.name,J))}function FK($,f){return q2($,f).filter((J)=>!J.disabled).map((J)=>J.name.trim()).filter((J)=>J.length>0).sort((J,Q)=>J.localeCompare(Q))}function PK($,f,J){let Q=w4(f);if(!Q)return{error:"Missing skill name."};let Z=q2($,J),W=Z.find((V)=>V.id===Q);if(W){let{skill:V}=W;if(V.disabled===!0)return{error:`Skill "${V.name}" is configured but disabled.`};return{id:W.id,skill:V}}let j=Q.includes(":")?Q.split(":").at(-1)??Q:Q,X=Z.filter(({id:V})=>{if(V===j)return!0;return V.endsWith(`:${j}`)}),H=X.filter(({skill:V})=>V.disabled!==!0);if(H.length===1){let{id:V,skill:A}=H[0];return{id:V,skill:A}}if(H.length>1)return{error:`Skill "${f}" is ambiguous. Use one of: ${H.map(({id:V})=>V).join(", ")}`};if(X.length===1){let{skill:V}=X[0];return{error:`Skill "${V.name}" is configured but disabled.`}}if(X.length>1)return{error:`Skill "${f}" is ambiguous, and all matches are disabled: ${X.map(({id:V})=>V).join(", ")}`};let Y=FK($,J);return{error:Y.length>0?`Skill "${f}" not found. Available skills: ${Y.join(", ")}`:"No skills are currently available."}}function UK($,f=Promise.resolve(),J){let Q=new Set,Z=async(W,j)=>{await f;let X=PK($,W,J);if("error"in X)return X.error;let{id:H,skill:Y}=X;if(Q.has(H))return`Skill "${Y.name}" is already running.`;Q.add(H);try{let V=j?.trim(),A=V?`
147
147
  <command-args>${V}</command-args>`:"",B=Y.description?.trim()?`Description: ${Y.description.trim()}
148
148
 
149
149
  `:"";return`<command-name>${Y.name}</command-name>${A}
150
150
  <command-instructions>
151
151
  ${B}${Y.instructions}
152
- </command-instructions>`}finally{Q.delete(H)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>Nf($,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function eZ($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await f,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>NQ($.watcher)});if($.registerSkillsTool)Q.registerTool(k1(iK($.watcher,f,$.allowedSkillNames)));for(let Z of Gf($.watcher).filter((W)=>W.kind==="skill"&&$.includeSkills||W.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
152
+ </command-instructions>`}finally{Q.delete(H)}};return Object.defineProperty(Z,"configuredSkills",{get:()=>q2($,J).map(({skill:W,...j})=>j),enumerable:!0,configurable:!1}),Z}function K3($){let f=$.watcherReady??Promise.resolve();return{name:"cline-user-instructions",manifest:{capabilities:[$.includeRules?"rules":void 0,$.registerSkillsTool?"tools":void 0,$.includeSkills||$.includeWorkflows?"commands":void 0].filter((Q)=>Boolean(Q))},async setup(Q){if(await f,$.includeRules)Q.registerRule({id:"cline-user-instructions:rules",source:"user-instruction-watcher",content:()=>vQ($.watcher)});if($.registerSkillsTool)Q.registerTool(x1(UK($.watcher,f,$.allowedSkillNames)));for(let Z of P2($.watcher).filter((W)=>W.kind==="skill"&&$.includeSkills||W.kind==="workflow"&&$.includeWorkflows))Q.registerCommand({name:Z.name,description:Z.description,handler:(W)=>{let j=W.trim();return j?`${Z.instructions}
153
153
 
154
- ${j}`:Z.instructions}})}}}class $3{watcher;ready;stopped=!1;constructor($){this.watcher=LQ($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return Gf(this.watcher)}resolveRuntimeSlashCommand($){return _Q($,this.watcher)}hasConfiguredSkills($){return Nf(this.watcher,$).length>0}createExtension($){return eZ({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function v1($){return new $3($)}import{readFile as nK,writeFile as aK}from"node:fs/promises";import J3 from"yaml";function tK($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J,W=J3.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function f3($,f){return`---
155
- ${J3.stringify($).trimEnd()}
154
+ ${j}`:Z.instructions}})}}}class F3{watcher;ready;stopped=!1;constructor($){this.watcher=kQ($)}start(){if(!this.ready)this.stopped=!1,this.ready=this.watcher.start();return this.ready}stop(){if(this.stopped)return;this.stopped=!0,this.watcher.stop(),this.ready=void 0}async refreshType($){await this.start(),await this.watcher.refreshType($)}listRecords($){return[...this.watcher.getSnapshot($).entries()].map(([f,J])=>({type:$,id:f,filePath:J.filePath,item:J.item}))}listRuntimeCommands(){return P2(this.watcher)}resolveRuntimeSlashCommand($){return mQ($,this.watcher)}hasConfiguredSkills($){return q2(this.watcher,$).some((f)=>!f.disabled)}createExtension($){return K3({...$,watcher:this.watcher,watcherReady:(this.ready??Promise.resolve()).catch(()=>{})})}}function c1($){return new F3($)}import{readFile as DK,writeFile as RK}from"node:fs/promises";import U3 from"yaml";function LK($){let f=/^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/,J=$.match(f);if(!J)return{data:{},body:$,hadFrontmatter:!1};let[,Q,Z]=J,W=U3.parse(Q);return{data:W&&typeof W==="object"&&!Array.isArray(W)?W:{},body:Z,hadFrontmatter:!0}}function P3($,f){return`---
155
+ ${U3.stringify($).trimEnd()}
156
156
  ---
157
- ${f}`}function sK($,f){let{data:J,body:Q,hadFrontmatter:Z}=tK($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return f3(J,Q)}return J.disabled=!0,f3(J,Q)}async function Q3({filePath:$,enabled:f}){let J=await nK($,"utf8"),Q=sK(J,f);return await aK($,Q),{filePath:$,enabled:f,disabled:!f}}import{spawn as yG}from"node:child_process";import{StringDecoder as D3}from"node:string_decoder";import{UnauthorizedError as K3}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as NG}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as GG}from"node:crypto";import{UnauthorizedError as PG}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as FG}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as DG}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as RG}from"@modelcontextprotocol/sdk/client/streamableHttp.js";y8();var UG="/mcp/oauth/callback",LG=[1456,1457,1458],OG=300000;function zG($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function _G($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function T8($){let f={};try{f=wf($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,Q,Z=async(j)=>{let X=c1(j(f))??{};try{f=Sf($.serverName,()=>X,{filePath:$.settingsPath})}catch{f=X}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return _G(f.redirectUrl??$.redirectUrl)},state:()=>{return Q=GG(),Q},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((X)=>({...X,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((X)=>({...X,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((X)=>({...X,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((X)=>{if(j==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((X)=>({...X,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((X)=>({...X,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function N8($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new DG(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new RG(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function A3($){return new FG({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function B3($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (y8(),V3)),Q=J({filePath:$.filePath}).find((H)=>H.name===f);if(!Q)throw Error(`MCP server "${f}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await $$({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:LG,callbackPath:$.callbackPath??UG,timeoutMs:$.timeoutMs??OG,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=T8({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(H)=>{await $.openUrl?.(H)}});await W.resetInteractiveState();let j=A3($),X;try{let H=N8({registration:Q,oauthProvider:W.provider,fetch:$.fetch});try{return await j.connect(H),await j.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(Y){if(!(Y instanceof PG))throw Y;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let A=await Z.waitForCallback();if(!A)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(A.error)throw Error(`OAuth authorization failed: ${A.error}`);if(!A.code)throw Error("OAuth callback did not include an authorization code.");let B=W.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(A.state!==B)throw Error("OAuth authorization failed: state mismatch.");await H.finishAuth(A.code),X=A3($);let K=N8({registration:Q,oauthProvider:W.provider,fetch:$.fetch});return await X.connect(K),await X.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(H){let Y=zG(H);throw await W.markError(Y),Error(Y)}finally{await j.close().catch(()=>{return}),await X?.close().catch(()=>{return}),Z.close()}}var TG="2024-11-05",MG=5000,qG=1500,G3="http://127.0.0.1:1456/mcp/oauth/callback";function M8($){return $ instanceof Error?$.message:String($)}function P3($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
157
+ ${f}`}function OK($,f){let{data:J,body:Q,hadFrontmatter:Z}=LK($);if(!Z&&f)return $;if(f){if(delete J.disabled,J.enabled===!1)delete J.enabled;if(Object.keys(J).length===0)return Q;return P3(J,Q)}return J.disabled=!0,P3(J,Q)}async function D3({filePath:$,enabled:f}){let J=await DK($,"utf8"),Q=OK(J,f);return await RK($,Q),{filePath:$,enabled:f,disabled:!f}}import{spawn as nK}from"node:child_process";import{StringDecoder as C3}from"node:string_decoder";import{UnauthorizedError as y3}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as aK}from"@modelcontextprotocol/sdk/client/index.js";import{randomUUID as mK}from"node:crypto";import{UnauthorizedError as gK}from"@modelcontextprotocol/sdk/client/auth.js";import{Client as vK}from"@modelcontextprotocol/sdk/client/index.js";import{SSEClientTransport as uK}from"@modelcontextprotocol/sdk/client/sse.js";import{StreamableHTTPClientTransport as cK}from"@modelcontextprotocol/sdk/client/streamableHttp.js";S4();var dK="/mcp/oauth/callback",lK=[1456,1457,1458],pK=300000;function rK($){if($ instanceof Error){let f=$.message.trim();if(f.length>0)return f}return String($)}function iK($){return{client_name:"Cline",redirect_uris:[$],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"}}function C4($){let f={};try{f=h2($.serverName,{filePath:$.settingsPath})??{}}catch{f={}}let J,Q,Z=async(j)=>{let X=d1(j(f))??{};try{f=C2($.serverName,()=>X,{filePath:$.settingsPath})}catch{f=X}};return{provider:{get redirectUrl(){return f.redirectUrl??$.redirectUrl},get clientMetadata(){return iK(f.redirectUrl??$.redirectUrl)},state:()=>{return Q=mK(),Q},clientInformation:()=>f.clientInformation,saveClientInformation:async(j)=>{await Z((X)=>({...X,clientInformation:j,redirectUrl:$.redirectUrl,lastError:void 0}))},tokens:()=>f.tokens,saveTokens:async(j)=>{await Z((X)=>({...X,tokens:j,redirectUrl:$.redirectUrl,lastError:void 0,lastAuthenticatedAt:Date.now()}))},redirectToAuthorization:async(j)=>{J=j.toString(),await $.onAuthorizationUrl?.(J)},saveCodeVerifier:async(j)=>{await Z((X)=>({...X,codeVerifier:j,redirectUrl:$.redirectUrl}))},codeVerifier:()=>{if(!f.codeVerifier)throw Error(`Missing OAuth code verifier for MCP server "${$.serverName}".`);return f.codeVerifier},invalidateCredentials:async(j)=>{await Z((X)=>{if(j==="all")return{lastError:X.lastError,redirectUrl:X.redirectUrl};return{...X,...j==="client"?{clientInformation:void 0}:{},...j==="tokens"?{tokens:void 0,lastAuthenticatedAt:void 0}:{},...j==="verifier"?{codeVerifier:void 0}:{},...j==="discovery"?{discoveryState:void 0}:{}}})},saveDiscoveryState:async(j)=>{await Z((X)=>({...X,discoveryState:j}))},discoveryState:()=>f.discoveryState},getLastAuthorizationUrl:()=>J,getLastOAuthState:()=>Q,resetInteractiveState:async()=>{await Z((j)=>({...j,clientInformation:void 0,codeVerifier:void 0,discoveryState:void 0,lastError:void 0,redirectUrl:$.redirectUrl}))},markError:async(j)=>{await Z((X)=>({...X,lastError:j}))},clearError:async()=>{await Z((j)=>({...j,lastError:void 0}))}}}function h4($){let f=$.registration.transport;if(f.type==="stdio")throw Error(`MCP server "${$.registration.name}" uses stdio transport and does not support OAuth browser flow.`);let J=f.headers?{headers:f.headers}:void 0;if(f.type==="sse")return new uK(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch});return new cK(new URL(f.url),{authProvider:$.oauthProvider,requestInit:J,fetch:$.fetch})}function M3($){return new vK({name:$.clientName?.trim()||"@cline/core",version:$.clientVersion?.trim()||"0.0.0"})}async function q3($){let f=$.serverName.trim();if(!f)throw Error("MCP server name cannot be empty.");let{resolveMcpServerRegistrations:J}=await Promise.resolve().then(() => (S4(),T3)),Q=J({filePath:$.filePath}).find((H)=>H.name===f);if(!Q)throw Error(`MCP server "${f}" is not configured.`);if(Q.disabled)throw Error(`MCP server "${f}" is disabled. Enable it before running OAuth.`);if(Q.transport.type==="stdio")throw Error(`MCP server "${f}" uses stdio transport and does not support OAuth browser flow.`);let Z=await e0({host:$.callbackHost,ports:$.callbackPorts?.length?$.callbackPorts:lK,callbackPath:$.callbackPath??dK,timeoutMs:$.timeoutMs??pK,successHtml:$.successHtml,onListening:$.onServerListening,onClose:$.onServerClose});if(!Z.callbackUrl)throw Error("Unable to bind local MCP OAuth callback server.");let W=C4({settingsPath:$.filePath,serverName:f,redirectUrl:Z.callbackUrl,onAuthorizationUrl:async(H)=>{await $.openUrl?.(H)}});await W.resetInteractiveState();let j=M3($),X;try{let H=h4({registration:Q,oauthProvider:W.provider,fetch:$.fetch});try{return await j.connect(H),await j.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" is already authorized.`}}catch(Y){if(!(Y instanceof gK))throw Y;if(!W.getLastAuthorizationUrl())throw Error(`MCP server "${f}" did not provide an authorization URL.`);let A=await Z.waitForCallback();if(!A)throw Error("Timed out waiting for MCP OAuth authorization callback.");if(A.error)throw Error(`OAuth authorization failed: ${A.error}`);if(!A.code)throw Error("OAuth callback did not include an authorization code.");let B=W.getLastOAuthState();if(!B)throw Error(`MCP server "${f}" did not start an OAuth stateful authorization flow.`);if(A.state!==B)throw Error("OAuth authorization failed: state mismatch.");await H.finishAuth(A.code),X=M3($);let G=h4({registration:Q,oauthProvider:W.provider,fetch:$.fetch});return await X.connect(G),await X.listTools(),await W.clearError(),{serverName:f,authorized:!0,message:`MCP server "${f}" OAuth authorization completed.`}}}catch(H){let Y=rK(H);throw await W.markError(Y),Error(Y)}finally{await j.close().catch(()=>{return}),await X?.close().catch(()=>{return}),Z.close()}}var tK="2024-11-05",sK=5000,oK=1500,w3="http://127.0.0.1:1456/mcp/oauth/callback";function E4($){return $ instanceof Error?$.message:String($)}function S3($){let f=Buffer.from(JSON.stringify($),"utf8"),J=Buffer.from(`Content-Length: ${f.byteLength}\r
158
158
  \r
159
- `,"utf8");return Buffer.concat([J,f])}function F3($){return Buffer.from(`${JSON.stringify($)}
160
- `,"utf8")}class SJ{buffer="";decoder=new D3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
159
+ `,"utf8");return Buffer.concat([J,f])}function h3($){return Buffer.from(`${JSON.stringify($)}
160
+ `,"utf8")}class uJ{buffer="";decoder=new C3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`\r
161
161
  \r
162
- `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let W=Number.parseInt(Z[1],10),j=J+4,X=j+W;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class CJ{buffer="";decoder=new D3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
163
- `);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)f.push(Q)}return f}}class R3{registration;process;nextRequestId=1;pending=new Map;framedParser=new SJ;newlineParser=new CJ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:TG,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},qG),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){f=Q instanceof Error?Q:Error(String(Q))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new SJ,this.newlineParser=new CJ,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=yG(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${M8(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${M8($)}.${J}`)),f.kill()}async request($,f,J=MG){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,H)=>{let Y=setTimeout(()=>{this.pending.delete(Z),H(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:H,timeout:Y})});try{Q.stdin.write(this.protocolMode==="framed"?P3(W):F3(W))}catch(X){let H=this.pending.get(Z);if(H)clearTimeout(H.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?P3(Q):F3(Q))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class U3{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=T8({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??G3});this.authContext=$;try{let f=new NG({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=N8({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof K3?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):M8(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??T8({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??G3}),J=$ instanceof K3?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):M8($);throw await f.markError(J),Error(J)}}function q8($={}){return(f)=>f.transport.type==="stdio"?new R3(f):new U3(f,$)}y8();function S0(){return Date.now()}function wG($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class Ef{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:S0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=S0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=S0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&S0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),Q=await(await this.ensureConnectedClient(f)).listTools(),Z=wG(Q);return f.toolCache=Z,f.toolCacheUpdatedAt=S0(),f.updatedAt=S0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=S0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=S0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=S0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=S0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=S0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=S0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,W),await J.catch(()=>{return});try{return await f()}finally{if(Q?.(),this.operationLocks.get($)===W)this.operationLocks.delete($)}}}import{createHash as SG}from"node:crypto";var L3=128,CG=/[^a-zA-Z0-9_-]+/g,O3=8,EG=1,hG="mcp_tool";function bG($){return SG("sha1").update($).digest("hex").slice(0,O3)}function kG($){return $.replace(CG,"_")}var w8=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,Q=kG(J);if(Q===J&&J.length<=L3)return J;let Z=bG(J),W=L3-EG-O3;return`${Q.slice(0,W)||hG}_${Z}`};function EJ($){return{[($.nameTransform??w8)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function z3($){let f={};for(let J of $.toolNames)Object.assign(f,EJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as IG}from"@cline/shared";function xG($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function S8($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??w8;return f.map((Q)=>{let Z=J({serverName:$.serverName,toolName:Q.name});return IG({name:Z,description:xG($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(W,j)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}Z$();Z$();import{existsSync as SP}from"node:fs";import{discoverPluginModulePaths as CP,resolveConfiguredPluginModulePaths as EP,resolvePluginConfigSearchPaths as hP}from"@cline/shared/storage";import{resolve as HP}from"node:path";import{normalizePluginManifest as YP}from"@cline/shared";import{existsSync as A0,readFileSync as p1}from"node:fs";import{builtinModules as rG,createRequire as w3}from"node:module";import{dirname as kf,extname as b8,isAbsolute as iG,resolve as c}from"node:path";import{fileURLToPath as S3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as nG}from"@cline/shared";var C3=kf(S3(import.meta.url)),aG=w3(import.meta.url),tG=c(C3,"..","..","..","..",".."),xJ=eG(tG),sG=["@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"],vJ=new Set(rG.flatMap(($)=>[$,$.replace(/^node:/,"")])),bf=new Set(nG),oG=["development","node","import","require","default"];function eG($){let f={},J={"@cline/agents":c($,"packages/agents/src/index.ts"),"@cline/core":c($,"packages/core/src/index.ts"),"@cline/llms":c($,"packages/llms/src/index.ts"),"@cline/shared":c($,"packages/shared/src/index.ts"),"@cline/shared/storage":c($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":c($,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(A0(Z))f[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=c($,"packages",Q),W=c(Z,"package.json");if(!A0(W))continue;try{let j=JSON.parse(p1(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=c(Z,j.exports);if(A0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,H]of Object.entries(j.exports)){let Y=$P(Z,H);if(!Y)continue;let V=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[V]=Y}}catch{}}return f}function $P($,f){let J=cJ(f);if(!J)return null;let Q=E3($,J);for(let Z of Q)if(A0(Z))return Z;return null}function cJ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let Q of oG){let Z=cJ(J[Q],f);if(Z)return Z}return null}function E3($,f){let J=f.replace(/^\.\//,""),Q=[c($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[c($,`${Z}.ts`),c($,`${Z}.tsx`),c($,`${Z}.mts`),c($,`${Z}.cts`),...Q]}return Q}function fP($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function h8($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function l1($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function JP($){let f=l1($);if($===f)return".";return`.${$.slice(f.length)}`}function h3($){return l1($).startsWith("@cline/")}function gJ($,f){let J=l1(f),Q=kf($);while(!0){let Z=c(Q,"node_modules",J);if(A0(Z)||A0(c(Z,"package.json")))return!0;let W=c(Q,"..");if(W===Q)return!1;Q=W}}function q3($){return mJ($)!==null}function mJ($){try{return aG.resolve($)}catch{}return QP($)}function QP($){let f=l1($),J=ZP(f);if(!J)return null;let Q=c(J,"package.json");try{let Z=JSON.parse(p1(Q,"utf8")),W=JP($),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,X=cJ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let H=c(J,X),Y=[H,...E3(J,X).filter((V)=>V!==H)];for(let V of Y)if(A0(V))return V;return null}catch{return null}}function ZP($){let f=C3;while(!0){let J=c(f,"package.json");if(A0(J))try{if(JSON.parse(p1(J,"utf8")).name===$)return f}catch{}let Q=c(f,"node_modules",$,"package.json");if(A0(Q))return kf(Q);let Z=c(f,"..");if(Z===f)return null;f=Z}}function WP($){let J=kf($);for(let Q=0;Q<4;Q++){let Z=c(J,"package.json");if(A0(Z))try{let j=JSON.parse(p1(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=c(J,"..");if(W===J)return!1;J=W}return!1}function b3($,f){let J=f.startsWith("file:")?S3(f):iG(f)?f:c(kf($),f);if(A0(J)&&bf.has(b8(J)))return J;for(let Q of bf){let Z=`${J}${Q}`;if(A0(Z))return Z}for(let Q of bf){let Z=c(J,`index${Q}`);if(A0(Z))return Z}return null}function k3($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of $.matchAll(Q)){let W=Z[1];if(W)f.add(W)}return[...f]}function jP($){return b8($)!==".ts"}function I3($,f,J=new Set){if(J.has($)||!A0($))return;if(J.add($),!bf.has(b8($)))return;let Q=p1($,"utf8"),Z=jP($);for(let W of k3(Q)){if(W.startsWith("node:")||vJ.has(W))continue;if(h8(W)){if(!Z)continue;if(Object.hasOwn(xJ,W)||Object.hasOwn(xJ,l1(W))||gJ($,W)||h3(W)&&q3(W)||f&&q3(W))continue;throw Error(`Cannot find module '${l1(W)}'`)}let j=b3($,W);if(j)I3(j,f,J)}}function x3($,f=new Set,J=new Set){if(f.has($)||!A0($))return J;if(f.add($),!bf.has(b8($)))return J;let Q=p1($,"utf8");for(let Z of k3(Q)){if(J.add(Z),h8(Z))continue;let W=b3($,Z);if(W)x3(W,f,J)}return J}function XP($,f){let J=w3($),Q={},Z=x3($),W=new Set(sG);for(let[j,X]of Object.entries(xJ)){try{J.resolve(j);continue}catch{}Q[j]=X}for(let j of Z)if(h8(j)&&(h3(j)||f))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||gJ($,j))continue;let X=mJ(j);if(X)Q[j]=X}if(!f)return Q;for(let j of Z){if(!h8(j)||Object.hasOwn(Q,j)||gJ($,j)||j.startsWith("node:")||vJ.has(j))continue;let X=mJ(j);if(X)Q[j]=X}return Q}async function g3($,f={}){let J=!WP($);I3($,J);let Q=XP($,J),Z=fP(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...vJ],transformModules:Object.keys(Z)}).import($,{})}function m3($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function v3($){return typeof $==="object"&&$!==null}function uJ($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function VP($,f){if(!v3($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!uJ($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!uJ($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!uJ($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function AP($,f){if(!v3($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);VP($,f)}async function dJ($,f={}){let J=HP(f.cwd??process.cwd(),$),Q=await g3(J,{useCache:f.useCache}),Z=f.exportName??"plugin",W=Q.default??Q[Z];AP(W,J);let j=W,X=j.setup,H=X?(Y,V)=>{let A={...f.session,...V.session},B={...V,session:Object.keys(A).length>0?A:void 0,client:f.client??V.client,user:f.user??V.user,workspaceInfo:f.workspaceInfo??V.workspaceInfo,automation:f.automation??V.automation,logger:f.logger??V.logger,telemetry:f.telemetry??V.telemetry};return X(Y,B)}:void 0;return{...j,manifest:YP(j.manifest),setup:H}}async function c3($,f={}){return(await W1($,f)).plugins}async function W1($,f={}){let J=[],Q=[],Z=new Map,W=0;for(let j of $)try{let X=await dJ(j,f);if(!m3(X.manifest,f))continue;let H=Z.get(X.name);if(H)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:j,overriddenPluginPath:H.pluginPath,message:`Plugin "${X.name}" from ${j} overrides ${H.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:j,order:W++})}catch(X){let H=X instanceof Error?X.message:String(X);J.push({pluginPath:j,phase:"load",message:H,stack:X instanceof Error?X.stack:void 0})}return{plugins:[...Z.values()].sort((j,X)=>j.order-X.order).map((j)=>j.plugin),failures:J,warnings:Q}}import{existsSync as RP}from"node:fs";import{createRequire as UP}from"node:module";import{dirname as LP,join as I8}from"node:path";import{fileURLToPath as OP}from"node:url";import{spawn as BP}from"node:child_process";import{basename as KP}from"node:path";import{augmentNodeCommandForDebug as GP,withResolvedClineBuildEnv as PP}from"@cline/shared";function u3($){if($ instanceof Error)return $;return Error(String($))}var FP="CLINE_JS_RUNTIME_PATH";function d3($){let f=$?.trim();if(!f)return!1;let J=KP(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function l3($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[FP]?.trim();if(J)return J;let Q=$.execPath?.trim()||process.execPath;if(d3(Q))return Q;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let W=Z?.trim();if(W&&d3(W))return W}return"node"}function DP($,f={}){let J=l3({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return GP([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class k8{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=DP($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=BP(f[0]??l3(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:PP(process.env)});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${u3(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let X=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let H={resolve:(Y)=>j(Y),reject:X};if((J.timeoutMs??0)>0)H.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,H),Q.send(W,(Y)=>{if(!Y)return;let V=this.clearPendingRequest(Z);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${$}": ${u3(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function zP($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function x8($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function _P(){let $=LP(OP(import.meta.url)),f=UP(import.meta.url),J=[I8($,"plugin-sandbox-bootstrap.js"),I8($,"extensions","plugin-sandbox-bootstrap.js"),I8($,"agents","plugin-sandbox-bootstrap.js")];for(let W of J)if(RP(W))return{file:W};let Q=I8($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
164
- `)}}var lJ=_P();function pJ($,f){return typeof $==="number"&&$>0?$:f}async function r3($){let f=new k8({name:"plugin-sandbox",..."file"in lJ?{bootstrapFile:lJ.file}:{bootstrapScript:lJ.script},onEvent:$.onEvent}),J=pJ($.importTimeoutMs,4000),Q=pJ($.hookTimeoutMs,3000),Z=pJ($.contributionTimeoutMs,60000),W={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},H;try{H=await f.call("initialize",W,{timeoutMs:J})}catch(A){throw await f.shutdown().catch(()=>{}),A}return{extensions:H.plugins.map(zP).map((A)=>{let B={name:A.name,manifest:A.manifest,setup:(K)=>{yP(K,f,A,Z,X),NP(K,f,A,Z,X),MP(K,f,A,Z,X),TP(K,A)}};return B.hooks=wP(f,A,Q,X),B}),failures:H.failures,shutdown:async()=>{await f.shutdown()},warnings:H.warnings}}function yP($,f,J,Q,Z){for(let W of J.contributions?.tools??[]){let j={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(X,H)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:H},{timeoutMs:Q})}catch(Y){if(!x8(Y))throw Y;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:H},{timeoutMs:Q})}}};$.registerTool(j)}}function NP($,f,J,Q,Z){for(let W of J.contributions?.commands??[])$.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(X){if(!x8(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function TP($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function MP($,f,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:W.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return p3(X)?X:j}catch(X){if(!x8(X))throw X;await Z();let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return p3(H)?H:j}}})}function p3($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function qP($,f,J,Q,Z){return async(W)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!x8(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}}}function wP($,f,J,Q){let Z={};for(let W of f.hooks??[])Z[W]=qP($,f.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}function rJ($){return hP($)}function iJ($){return CP($)}function If($={}){let f=$.cwd??process.cwd(),J=rJ($.workspacePath).flatMap((j)=>iJ(j)).filter((j)=>SP(j)),Q=EP($.pluginPaths??[],f),Z=[],W=new Set;for(let j of[...Q,...J]){if(W.has(j))continue;W.add(j),Z.push(j)}return kJ(Z)}async function g8($={}){let f=If($);if(f.length===0)return{extensions:[],failures:[],warnings:[]};if($.mode==="in_process"){let Q=await W1(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,warnings:Q.warnings}}let J=await r3({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}Z$();function bP($,f){if(!$.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(Q,{workspaceInfo:f}),J}async function nJ($){let f=If({workspacePath:$.workspacePath,cwd:$.cwd}),J=r0($.disabledToolNames),Q=[];for(let Z of f){let W=await W1([Z],{cwd:$.cwd,providerId:$.providerId,modelId:$.modelId});for(let j of W.plugins)for(let X of bP(j,{rootPath:$.workspacePath}))Q.push({name:X.name,pluginName:j.name,path:Z,source:Z.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",enabled:!J.has(X.name),description:X.description?.trim()||void 0})}return Q.sort((Z,W)=>{let j=Z.name.localeCompare(W.name);if(j!==0)return j;return Z.path.localeCompare(W.path)})}function v8($,f){if(!f)return"global";let J=IP(f,$);return!J.startsWith("..")&&!kP(J)?"workspace":"global"}function xf($){return[...$].sort((f,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return Q(f.source)-Q(J.source);return f.name.localeCompare(J.name)})}function a3($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function n3($,f){if($.userInstructionService)return await f($.userInstructionService);let J=a3($);if(!J)return await f(void 0);let Q=v1({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Q.start(),await f(Q)}finally{Q.stop()}}function xP($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let Q=J.find((Z)=>Z.id===f.id);if(Q)return Q}for(let Q of J)if(Q.filePath===f.path||Q.item.name===f.name||Q.id===f.name)return Q;return}class r1{async list($={}){return await n3($,async(f)=>{let J=a3($),Q=[],Z=[],W=[],j=[],X=[];if(f){for(let Y of f.listRecords("workflow")){let V=Y.item;Q.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"workflow",source:v8(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let V=Y.item;Z.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"rule",source:v8(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let V=Y.item;W.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"skill",source:v8(Y.filePath,J),description:V.description,toggleable:!0})}}if(J)try{for(let Y of await nJ({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let H=w0();if(Z1({filePath:H}))try{for(let Y of T$({filePath:H}))X.push({id:Y.name,name:Y.name,path:H,enabled:Y.disabled!==!0,kind:"mcp",source:v8(H,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:xf(Q.filter((Y)=>m8(Y.path))),rules:xf(Z.filter((Y)=>m8(Y.path))),skills:xf(W.filter((Y)=>m8(Y.path))),tools:xf(j),mcp:xf(X.filter((Y)=>m8(Y.path)))}})}async toggle($){if($.type==="skills")return await n3($,async(f)=>{let J=xP(f,$),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??i3($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=$.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??i3($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await Q3({filePath:Q,enabled:W}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)bJ($.name);else M3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||w0(),Q=$.enabled;if(Q===void 0){let Z=T$({filePath:J}).find((W)=>W.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);Q=Z.disabled===!0}return qf({filePath:J,name:f,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function gf(){return new r1}function t3($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await gf().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await gf().toggle(f)}}}function s3($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}function P0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=f&&Object.keys(f).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}function aJ($){let{hooks:f,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:H,checkpoint:Y,compaction:V,...A}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(H)B.onConsecutiveMistakeLimitReached=H;if(Y?.createCheckpoint)B.checkpoint=Y;if(V?.compact)B.compaction=V;let K=Object.keys(B).length>0?B:void 0;return{config:{...A,...Y?{checkpoint:{enabled:Y.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,maxInputTokens:V.maxInputTokens,summarizer:V.summarizer}}:{}},...K?{localRuntime:K}:{}}}function o3($){let f=$.config;return"providerId"in f?{...$,config:{...f,...gP($.localRuntime)},localRuntime:$.localRuntime}:$}function tJ($,f={}){let J=aJ($.config),Q=P0(f.defaultCapabilities,$.capabilities),Z=mP(J.localRuntime,$.localRuntime),W=f.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...$,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function gP($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=$;return W}function mP(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}R0();function e3($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:g.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??G0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function mf($){return!!$&&typeof $==="object"&&!Array.isArray($)}function sJ($){let f=$?.trim();return f?f:void 0}function vP($,f){let J=$?.trim();if(!J)return f;let Q=Date.parse(J);if(!Number.isFinite(Q))return f;return new Date(Q).toISOString()}function $W($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function fW($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function cP($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function uP($,f){let J=$.eventId.trim(),Q=$.eventType.trim(),Z=$.source.trim(),W=sJ($.subject),j=sJ($.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:vP($.occurredAt,f),workspaceRoot:sJ($.workspaceRoot),payload:mf($.payload)?$.payload:void 0,attributes:mf($.attributes)?$.attributes:void 0,dedupeKey:j}}function oJ($,f){if(!f)return;let J=f.split("."),Q=$;for(let Z of J){if(!mf(Q))return;Q=Q[Z]}return Q}function dP($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=oJ(J,f);if(Q!==void 0)return Q;if($.attributes){let Z=oJ($.attributes,f);if(Z!==void 0)return Z}if($.payload)return oJ($.payload,f);return}function c8($,f){if(Array.isArray(f))return f.some((J)=>c8($,J));if(Array.isArray($))return $.some((J)=>c8(J,f));if(mf(f)){if(!mf($))return!1;return Object.entries(f).every(([J,Q])=>c8($[J],Q))}return Object.is($,f)}function lP($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,Q])=>c8(dP($,J),Q))}class eJ{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=uP($,f),Q=this.store.insertEventLog(J,{receivedAtIso:f});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],X=[];for(let V of Z){if(!lP(J,V.filters)){W.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(V);let A=this.materializeForSpec(V,J,Q.record.receivedAt);if(A.run)X.push(A.run);else W.push({specId:V.specId,externalId:V.externalId,reason:A.reason,dedupeKey:J.dedupeKey})}let H=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:H,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:W.filter((V)=>V.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:H,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:Y??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let Q=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let H=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(H){let Y=cP(H.scheduledFor,$W(J,Z)),V=this.store.updateQueuedEventRunForDebounce({runId:H.runId,triggerEventId:f.eventId,scheduledFor:Y});if(V)return{run:V,reason:"dedupe_window"}}}let W=$.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:fW(J,W)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:fW(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?$W(J,Z):J}),reason:"dedupe_window"}}}class vf{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of f)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as $F}from"node:path";import{buildClineSystemPrompt as fF}from"@cline/shared";import{nowIso as WW}from"@cline/shared/db";import{basename as pP,resolve as rP}from"node:path";import{performance as JW}from"node:perf_hooks";import{processWorkspaceInfo as QW}from"@cline/shared";import iP from"simple-git";function j1($){return rP($)}async function d8($){return(await $5($)).info}function u8($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function $5($){let f=j1($),J={rootPath:f,hint:pP(f)},Q;try{let Z=iP({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((H)=>{let Y=H.refs.fetch||H.refs.push;return`${H.name}: ${Y}`});J.associatedRemoteUrls=X}}catch(j){Q??=u8(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=u8(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=u8(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:u8(Z)}}}async function f5($){let f=await d8($);return QW(f)}async function ZW($){let f=JW.now(),J=await $5($),Q=JW.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:QW(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as nP,writeFileSync as aP}from"node:fs";import{join as tP}from"node:path";import{resolveCronReportsDir as sP}from"@cline/shared/storage";function M$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function X1($,f){if(f===void 0||f===null)return;return`${$}: ${M$(f)}`}function oP($,f,J){let Q=[`runId: ${M$($.runId)}`,`specId: ${M$(f.specId)}`,`externalId: ${M$(f.externalId)}`,`title: ${M$(f.title)}`,`triggerKind: ${M$($.triggerKind)}`,`status: ${M$($.status)}`,`sourcePath: ${M$(f.sourcePath)}`],Z=[X1("sessionId",$.sessionId),X1("startedAt",$.startedAt),X1("completedAt",$.completedAt),X1("triggerEventId",$.triggerEventId),X1("triggerEventType",J?.eventType),X1("triggerEventSource",J?.source),X1("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
162
+ `);if(J<0)break;let Z=this.buffer.slice(0,J).match(/(?:^|\r\n)Content-Length:\s*(\d+)(?:\r\n|$)/i);if(!Z)throw Error("Invalid MCP stdio frame: missing Content-Length header.");let W=Number.parseInt(Z[1],10),j=J+4,X=j+W;if(this.buffer.length<X)break;f.push(this.buffer.slice(j,X)),this.buffer=this.buffer.slice(X)}return f}}class cJ{buffer="";decoder=new C3("utf8");push($){this.buffer+=this.decoder.write($);let f=[];while(!0){let J=this.buffer.indexOf(`
163
+ `);if(J<0)break;let Q=this.buffer.slice(0,J).trim();if(this.buffer=this.buffer.slice(J+1),Q.length>0)f.push(Q)}return f}}class E3{registration;process;nextRequestId=1;pending=new Map;framedParser=new uJ;newlineParser=new cJ;stderrBuffer="";connected=!1;protocolMode="newline";constructor($){this.registration=$}async connect(){if(this.connected)return;if(this.registration.transport.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=["newline","framed"],f;for(let J of $){await this.disconnect().catch(()=>{}),this.spawnProcess(J);try{await this.request("initialize",{protocolVersion:tK,capabilities:{},clientInfo:{name:"@cline/core",version:"0.0.0"}},oK),this.notify("notifications/initialized"),this.connected=!0,this.protocolMode=J;return}catch(Q){f=Q instanceof Error?Q:Error(String(Q))}}throw f??Error(`Failed to connect to MCP server "${this.registration.name}".`)}async disconnect(){let $=this.process;if(this.connected=!1,this.process=void 0,this.failAllPending(Error(`Disconnected from MCP server "${this.registration.name}".`)),!$)return;$.kill()}async listTools(){return((await this.request("tools/list")).tools??[]).filter((f)=>typeof f?.name==="string"&&typeof f.inputSchema==="object"&&f.inputSchema!==null).map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}async callTool($){return this.request("tools/call",{name:$.name,arguments:$.arguments??{}})}spawnProcess($){let f=this.registration.transport;if(f.type!=="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${f.type}`);this.framedParser=new uJ,this.newlineParser=new cJ,this.stderrBuffer="",this.protocolMode=$;let J=process.platform==="win32"?{windowsHide:!0,shell:!0}:{},Q=nK(f.command,f.args??[],{cwd:f.cwd,env:{...process.env,...f.env??{}},stdio:["pipe","pipe","pipe"],...J});this.process=Q,Q.stdout.on("data",(Z)=>this.handleStdout(Z)),Q.stderr.on("data",(Z)=>{if(this.process!==Q)return;if(this.stderrBuffer+=Z.toString("utf8"),this.stderrBuffer.length>16384)this.stderrBuffer=this.stderrBuffer.slice(-16384)}),Q.once("error",(Z)=>{if(this.process!==Q)return;this.failAllPending(Error(`MCP process error: ${E4(Z)}`))}),Q.once("exit",(Z,W)=>{if(this.process!==Q)return;this.connected=!1,this.process=void 0;let j=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`MCP process exited for "${this.registration.name}" (code=${Z??"null"}, signal=${W??"null"}).${j}`))})}handleStdout($){try{let f=this.protocolMode==="framed"?this.framedParser.push($):this.newlineParser.push($);for(let J of f){let Q=JSON.parse(J);if(typeof Q.id!=="number")continue;let Z=this.pending.get(Q.id);if(!Z)continue;if(this.pending.delete(Q.id),clearTimeout(Z.timeout),Q.error){let W=Q.error.message||`MCP request failed with code ${Q.error.code??"unknown"}`;Z.reject(Error(W));continue}Z.resolve(Q.result)}}catch(f){this.handleProtocolFailure(f)}}handleProtocolFailure($){let f=this.process;if(!f)return;this.connected=!1,this.process=void 0;let J=this.stderrBuffer.trim()?` stderr: ${this.stderrBuffer.trim()}`:"";this.failAllPending(Error(`Invalid MCP response from "${this.registration.name}": ${E4($)}.${J}`)),f.kill()}async request($,f,J=sK){let Q=this.process;if(!Q?.stdin.writable)throw Error(`MCP server "${this.registration.name}" is not connected.`);let Z=this.nextRequestId++,W={jsonrpc:"2.0",id:Z,method:$,...f?{params:f}:{}},j=new Promise((X,H)=>{let Y=setTimeout(()=>{this.pending.delete(Z),H(Error(`MCP request timed out for "${this.registration.name}" (${$}).`))},J);this.pending.set(Z,{resolve:X,reject:H,timeout:Y})});try{Q.stdin.write(this.protocolMode==="framed"?S3(W):h3(W))}catch(X){let H=this.pending.get(Z);if(H)clearTimeout(H.timeout),this.pending.delete(Z);throw X}return j}notify($,f){let J=this.process;if(!J?.stdin.writable)return;let Q={jsonrpc:"2.0",method:$,...f?{params:f}:{}};J.stdin.write(this.protocolMode==="framed"?S3(Q):h3(Q))}failAllPending($){for(let[f,J]of this.pending)clearTimeout(J.timeout),this.pending.delete(f),J.reject($)}}class b3{registration;options;client;authContext;constructor($,f){this.registration=$;this.options=f}async connect(){if(this.client)return;if(this.registration.transport.type==="stdio")throw Error(`Unsupported MCP transport for "${this.registration.name}": ${this.registration.transport.type}`);let $=C4({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??w3});this.authContext=$;try{let f=new aK({name:this.options.clientName?.trim()||"@cline/core",version:this.options.clientVersion?.trim()||"0.0.0"}),J=h4({registration:this.registration,oauthProvider:$.provider,fetch:this.options.fetch});await f.connect(J),await $.clearError(),this.client=f}catch(f){let J=f instanceof y3?this.formatUnauthorizedMessage($.getLastAuthorizationUrl()):E4(f);throw await $.markError(J),Error(J)}}async disconnect(){let $=this.client;this.client=void 0,await $?.close()}async listTools(){let $=await this.ensureConnectedClient();try{return(await $.listTools()).tools.map((J)=>({name:J.name,description:J.description,inputSchema:J.inputSchema&&typeof J.inputSchema==="object"&&!Array.isArray(J.inputSchema)?J.inputSchema:{}}))}catch(f){return await this.handleOperationError(f)}}async callTool($){let f=await this.ensureConnectedClient();try{return await f.callTool({name:$.name,arguments:$.arguments??{}})}catch(J){return await this.handleOperationError(J)}}async ensureConnectedClient(){if(!this.client)await this.connect();if(!this.client)throw Error(`MCP server "${this.registration.name}" is not connected.`);return this.client}formatUnauthorizedMessage($){let f=`MCP server "${this.registration.name}" requires OAuth authorization.`;if(!$)return`${f} Run authorizeMcpServerOAuth for this server.`;return`${f} Run authorizeMcpServerOAuth for this server and complete this URL: ${$}`}async handleOperationError($){let f=this.authContext??C4({settingsPath:this.options.settingsPath,serverName:this.registration.name,redirectUrl:this.registration.oauth?.redirectUrl??w3}),J=$ instanceof y3?this.formatUnauthorizedMessage(f.getLastAuthorizationUrl()):E4($);throw await f.markError(J),Error(J)}}function b4($={}){return(f)=>f.transport.type==="stdio"?new E3(f):new b3(f,$)}S4();function E0(){return Date.now()}function eK($){return $.map((f)=>({name:f.name,description:f.description,inputSchema:f.inputSchema}))}class b2{toolsCacheTtlMs;clientFactory;servers=new Map;operationLocks=new Map;constructor($){this.clientFactory=$.clientFactory,this.toolsCacheTtlMs=$.toolsCacheTtlMs??5000}async registerServer($){await this.runExclusive($.name,async()=>{let f=this.servers.get($.name);if(!f){this.servers.set($.name,{registration:{...$},status:"disconnected",updatedAt:E0()});return}let J=JSON.stringify(f.registration.transport)!==JSON.stringify($.transport);if(f.registration={...$},f.updatedAt=E0(),J)await this.disconnectState(f),f.client=void 0,f.toolCache=void 0,f.toolCacheUpdatedAt=void 0})}async unregisterServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f),this.servers.delete($)})}async connectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.connectState(f)})}async disconnectServer($){await this.runExclusive($,async()=>{let f=this.requireServer($);await this.disconnectState(f)})}async setServerDisabled($,f){await this.runExclusive($,async()=>{let J=this.requireServer($);if(J.registration={...J.registration,disabled:f},J.updatedAt=E0(),f)await this.disconnectState(J)})}listServers(){return[...this.servers.values()].map(($)=>({name:$.registration.name,status:$.status,disabled:$.registration.disabled===!0,lastError:$.lastError,toolCount:$.toolCache?.length??0,updatedAt:$.updatedAt,metadata:$.registration.metadata})).sort(($,f)=>$.name.localeCompare(f.name))}async listTools($){let f=this.requireServer($),J=f.toolCacheUpdatedAt??0;if(f.toolCache&&E0()-J<=this.toolsCacheTtlMs)return f.toolCache;return this.refreshTools($)}async refreshTools($){return this.runExclusive($,async()=>{let f=this.requireServer($),Q=await(await this.ensureConnectedClient(f)).listTools(),Z=eK(Q);return f.toolCache=Z,f.toolCacheUpdatedAt=E0(),f.updatedAt=E0(),Z})}async callTool($){return this.runExclusive($.serverName,async()=>{let f=this.requireServer($.serverName),J=await this.ensureConnectedClient(f);return f.updatedAt=E0(),J.callTool({name:$.toolName,arguments:$.arguments,context:$.context})})}async dispose(){let $=[...this.servers.keys()];for(let f of $)await this.unregisterServer(f)}async ensureConnectedClient($){if(await this.connectState($),!$.client)throw Error(`MCP server "${$.registration.name}" does not have an initialized client.`);return $.client}async connectState($){if($.registration.disabled)throw Error(`MCP server "${$.registration.name}" is disabled and cannot be connected.`);if($.status==="connected"&&$.client)return;$.status="connecting",$.updatedAt=E0();try{let f=$.client??await this.clientFactory($.registration);await f.connect(),$.client=f,$.status="connected",$.lastError=void 0,$.updatedAt=E0()}catch(f){throw $.status="disconnected",$.lastError=f instanceof Error?f.message:String(f),$.updatedAt=E0(),f}}async disconnectState($){if(!$.client){$.status="disconnected",$.updatedAt=E0();return}try{await $.client.disconnect()}finally{$.status="disconnected",$.updatedAt=E0()}}requireServer($){let f=this.servers.get($);if(!f)throw Error(`Unknown MCP server: ${$}`);return f}async runExclusive($,f){let J=this.operationLocks.get($)??Promise.resolve(),Q,Z=new Promise((j)=>{Q=j}),W=J.catch(()=>{return}).then(()=>Z);this.operationLocks.set($,W),await J.catch(()=>{return});try{return await f()}finally{if(Q?.(),this.operationLocks.get($)===W)this.operationLocks.delete($)}}}import{createHash as $F}from"node:crypto";var k3=128,fF=/[^a-zA-Z0-9_-]+/g,I3=8,JF=1,QF="mcp_tool";function ZF($){return $F("sha1").update($).digest("hex").slice(0,I3)}function WF($){return $.replace(fF,"_")}var k4=({serverName:$,toolName:f})=>{let J=`${$}__${f}`,Q=WF(J);if(Q===J&&J.length<=k3)return J;let Z=ZF(J),W=k3-JF-I3;return`${Q.slice(0,W)||QF}_${Z}`};function dJ($){return{[($.nameTransform??k4)({serverName:$.serverName,toolName:$.toolName})]:{enabled:!1}}}function x3($){let f={};for(let J of $.toolNames)Object.assign(f,dJ({serverName:$.serverName,toolName:J,nameTransform:$.nameTransform}));return f}import{createTool as jF}from"@cline/shared";function XF($,f){let J=f.description?.trim();if(J)return J;return`Execute MCP tool "${f.name}" from server "${$}".`}async function I4($){let f=await $.provider.listTools($.serverName),J=$.nameTransform??k4;return f.map((Q)=>{let Z=J({serverName:$.serverName,toolName:Q.name});return jF({name:Z,description:XF($.serverName,Q),inputSchema:Q.inputSchema,timeoutMs:$.timeoutMs,retryable:$.retryable,maxRetries:$.maxRetries,execute:async(W,j)=>$.provider.callTool({serverName:$.serverName,toolName:Q.name,arguments:W&&typeof W==="object"&&!Array.isArray(W)?W:void 0,context:j})})})}Z$();import{stat as BP}from"node:fs/promises";Z$();import{existsSync as HP}from"node:fs";import{discoverPluginModulePaths as YP,resolveConfiguredPluginModulePaths as VP,resolvePluginConfigSearchPaths as AP}from"@cline/shared/storage";import{resolve as vF}from"node:path";import{normalizePluginManifest as uF}from"@cline/shared";import{existsSync as j0,readFileSync as r1}from"node:fs";import{builtinModules as OF,createRequire as sJ}from"node:module";import{dirname as q$,extname as m2,isAbsolute as zF,resolve as g}from"node:path";import{fileURLToPath as d3}from"node:url";import{PLUGIN_FILE_EXTENSIONS as _F}from"@cline/shared";var l3=q$(d3(import.meta.url)),NF=sJ(import.meta.url),TF=g(l3,"..","..","..","..",".."),nJ=yF(TF),MF=["@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"],oJ=new Set(OF.flatMap(($)=>[$,$.replace(/^node:/,"")])),x2=new Set(_F),qF=["development","node","import","require","default"];function yF($){let f={},J={"@cline/sdk":g($,"packages/sdk/src/index.ts"),"@cline/agents":g($,"packages/agents/src/index.ts"),"@cline/core":g($,"packages/core/src/index.ts"),"@cline/llms":g($,"packages/llms/src/index.ts"),"@cline/shared":g($,"packages/shared/src/index.ts"),"@cline/shared/storage":g($,"packages/shared/src/storage/index.ts"),"@cline/shared/db":g($,"packages/shared/src/db/index.ts")};for(let[Q,Z]of Object.entries(J))if(j0(Z))f[Q]=Z;for(let Q of["agents","core","llms","shared"]){let Z=g($,"packages",Q),W=g(Z,"package.json");if(!j0(W))continue;try{let j=JSON.parse(r1(W,"utf8"));if(typeof j.name!=="string"||!j.exports)continue;if(typeof j.exports==="string"){let X=g(Z,j.exports);if(j0(X))f[j.name]=X;continue}if(typeof j.exports!=="object")continue;for(let[X,H]of Object.entries(j.exports)){let Y=wF(Z,H);if(!Y)continue;let V=X==="."?j.name:`${j.name}/${X.replace(/^\.\//,"")}`;f[V]=Y}}catch{}}return f}function wF($,f){let J=eJ(f);if(!J)return null;let Q=p3($,J);for(let Z of Q)if(j0(Z))return Z;return null}function eJ($,f=new Set){if(typeof $==="string")return $;if(!$||typeof $!=="object")return null;if(f.has($))return null;f.add($);let J=$;for(let Q of qF){let Z=eJ(J[Q],f);if(Z)return Z}return null}function p3($,f){let J=f.replace(/^\.\//,""),Q=[g($,f)];if(J.startsWith("dist/")){let Z=J.replace(/^dist\//,"src/").replace(/\.(mjs|cjs|js)$/,"");return[g($,`${Z}.ts`),g($,`${Z}.tsx`),g($,`${Z}.mts`),g($,`${Z}.cts`),...Q]}return Q}function SF($){return Object.fromEntries(Object.entries($).sort(([f],[J])=>J.length-f.length))}function u4($){return!($.startsWith(".")||$.startsWith("/")||$.startsWith("file:")||$.startsWith("data:")||$.startsWith("http:")||$.startsWith("https:"))}function p1($){if($.startsWith("@")){let[f,J]=$.split("/",3);return J?`${f}/${J}`:$}return $.split("/",1)[0]??$}function hF($){let f=p1($);if($===f)return".";return`.${$.slice(f.length)}`}function r3($){return p1($).startsWith("@cline/")}function aJ($,f){let J=p1(f),Q=q$($);while(!0){let Z=g(Q,"node_modules",J);if(j0(Z)||j0(g(Z,"package.json")))return!0;let W=g(Q,"..");if(W===Q)return!1;Q=W}}function c3($){return tJ($)!==null}function tJ($){try{return NF.resolve($)}catch{}return CF($)}function CF($){let f=p1($),J=i3(f);if(!J)return null;let Q=g(J,"package.json");try{let Z=JSON.parse(r1(Q,"utf8")),W=hF($),j=W==="."&&typeof Z.exports==="string"?Z.exports:Z.exports&&typeof Z.exports==="object"&&Object.hasOwn(Z.exports,W)?Z.exports[W]:void 0,X=eJ(j)??(W==="."&&typeof Z.main==="string"?Z.main:null);if(!X)return null;let H=g(J,X),Y=[H,...p3(J,X).filter((V)=>V!==H)];for(let V of Y)if(j0(V))return V;return null}catch{return null}}function EF(){let $=[l3],f=process.env.CLINE_WRAPPER_PATH?.trim();if(f)$.push(q$(q$(f)));let J=process.execPath?.trim();if(J)$.push(q$(J));return[...new Set($.map((Q)=>g(Q)))]}function bF($,f){let J=$;while(!0){let Q=g(J,"package.json");if(j0(Q))try{if(JSON.parse(r1(Q,"utf8")).name===f)return J}catch{}let Z=g(J,"node_modules",f,"package.json");if(j0(Z))return q$(Z);let W=g(J,"..");if(W===J)return null;J=W}}function i3($){for(let f of EF()){let J=bF(f,$);if(J)return J}return null}function kF($){let J=q$($);for(let Q=0;Q<4;Q++){let Z=g(J,"package.json");if(j0(Z))try{let j=JSON.parse(r1(Z,"utf8"));return j!=null&&typeof j==="object"&&"cline"in j}catch{return!1}let W=g(J,"..");if(W===J)return!1;J=W}return!1}function n3($,f){let J=f.startsWith("file:")?d3(f):zF(f)?f:g(q$($),f);if(j0(J)&&x2.has(m2(J)))return J;for(let Q of x2){let Z=`${J}${Q}`;if(j0(Z))return Z}for(let Q of x2){let Z=g(J,`index${Q}`);if(j0(Z))return Z}return null}function a3($){let f=new Set,J=[/\bimport\s+(?:type\s+)?[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bexport\s+[^"'`]*?\bfrom\s*["'`]([^"'`]+)["'`]/g,/\bimport\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g,/\brequire\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g];for(let Q of J)for(let Z of $.matchAll(Q)){let W=Z[1];if(W)f.add(W)}return[...f]}function IF($){return m2($)!==".ts"}function t3($,f,J=new Set){if(J.has($)||!j0($))return;if(J.add($),!x2.has(m2($)))return;let Q=r1($,"utf8"),Z=IF($);for(let W of a3(Q)){if(W.startsWith("node:")||oJ.has(W))continue;if(u4(W)){if(!Z)continue;if(Object.hasOwn(nJ,W)||Object.hasOwn(nJ,p1(W))||aJ($,W)||r3(W)&&c3(W)||f&&c3(W))continue;throw Error(`Cannot find module '${p1(W)}'`)}let j=n3($,W);if(j)t3(j,f,J)}}function s3($,f=new Set,J=new Set){if(f.has($)||!j0($))return J;if(f.add($),!x2.has(m2($)))return J;let Q=r1($,"utf8");for(let Z of a3(Q)){if(J.add(Z),u4(Z))continue;let W=n3($,Z);if(W)s3(W,f,J)}return J}function xF($,f){let J=sJ($),Q={},Z=s3($),W=new Set(MF);for(let[j,X]of Object.entries(nJ)){try{J.resolve(j);continue}catch{}Q[j]=X}for(let j of Z)if(u4(j)&&(r3(j)||f))W.add(j);for(let j of W){if(Object.hasOwn(Q,j)||aJ($,j))continue;let X=tJ(j);if(X)Q[j]=X}if(!f)return Q;for(let j of Z){if(!u4(j)||Object.hasOwn(Q,j)||aJ($,j)||j.startsWith("node:")||oJ.has(j))continue;let X=tJ(j);if(X)Q[j]=X}return Q}function mF($){let f=m2($);return f===".ts"||f===".tsx"||f===".mts"||f===".cts"}var H1;function gF(){if(H1!==void 0)return H1;let $=i3("jiti");if(!$)return H1=null,null;let f=g($,"dist","babel.cjs");if(!j0(f))return H1=null,null;try{let Q=sJ(f)(f);H1=typeof Q==="function"?Q:null}catch{H1=null}return H1}async function o3($,f={}){let J=!kF($);t3($,J);let Q=xF($,J),Z=SF(Q),W=await import("jiti"),j=typeof W==="function"?W:typeof W.default==="function"?W.default:void 0;if(!j)throw Error("Unable to load jiti");let X=Object.entries(Z).filter(([,A])=>mF(A)).map(([A])=>A),H=gF(),Y=H?(A)=>H({...A,interopDefault:!0}):void 0;return await j($,{alias:Z,cache:f.useCache,requireCache:f.useCache,esmResolve:!0,interopDefault:!1,nativeModules:[...oJ],transformModules:X,tryNative:!1,...Y?{transform:Y}:{}}).import($,{})}function e3($,f){if(!$)return!0;if($.providerIds?.length){if(!f?.providerId||!$.providerIds.includes(f.providerId))return!1}if($.modelIds?.length){if(!f?.modelId||!$.modelIds.includes(f.modelId))return!1}return!0}function $W($){return typeof $==="object"&&$!==null}function $5($){return Array.isArray($)&&$.every((f)=>typeof f==="string")}function cF($,f){if(!$W($.manifest))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);if(!$5($.manifest.capabilities))throw Error(`Invalid plugin module at ${f}: manifest.capabilities must be a string array`);if($.manifest.capabilities.length===0)throw Error(`Invalid plugin module at ${f}: manifest.capabilities cannot be empty`);if(Object.hasOwn($.manifest,"providerIds")&&!$5($.manifest.providerIds))throw Error(`Invalid plugin module at ${f}: manifest.providerIds must be a string array when provided`);if(Object.hasOwn($.manifest,"modelIds")&&!$5($.manifest.modelIds))throw Error(`Invalid plugin module at ${f}: manifest.modelIds must be a string array when provided`)}function dF($,f){if(!$W($))throw Error(`Invalid plugin module at ${f}: expected object export`);if(typeof $.name!=="string"||$.name.length===0)throw Error(`Invalid plugin module at ${f}: expected non-empty "name"`);if(!Object.hasOwn($,"manifest"))throw Error(`Invalid plugin module at ${f}: missing required "manifest"`);cF($,f)}async function f5($,f={}){let J=vF(f.cwd??process.cwd(),$),Q=await o3(J,{useCache:f.useCache}),Z=f.exportName??"plugin",W=Q.default??Q[Z];dF(W,J);let j=W,X=j.setup,H=X?(Y,V)=>{let A={...f.session,...V.session},B={...V,session:Object.keys(A).length>0?A:void 0,client:f.client??V.client,user:f.user??V.user,workspaceInfo:f.workspaceInfo??V.workspaceInfo,automation:f.automation??V.automation,logger:f.logger??V.logger,telemetry:f.telemetry??V.telemetry};return X(Y,B)}:void 0;return{...j,manifest:uF(j.manifest),setup:H}}async function fW($,f={}){return(await g2($,f)).plugins}async function g2($,f={}){let J=[],Q=[],Z=new Map,W=0;for(let j of $)try{let X=await f5(j,f);if(!e3(X.manifest,f))continue;let H=Z.get(X.name);if(H)Q.push({type:"duplicate_plugin_override",pluginName:X.name,pluginPath:j,overriddenPluginPath:H.pluginPath,message:`Plugin "${X.name}" from ${j} overrides ${H.pluginPath}`});Z.set(X.name,{plugin:X,pluginPath:j,order:W++})}catch(X){let H=X instanceof Error?X.message:String(X);J.push({pluginPath:j,phase:"load",message:H,stack:X instanceof Error?X.stack:void 0})}return{plugins:[...Z.values()].sort((j,X)=>j.order-X.order).map((j)=>j.plugin),failures:J,warnings:Q}}import{existsSync as Z5}from"node:fs";import{createRequire as jW}from"node:module";import{dirname as d4,join as i1}from"node:path";import{fileURLToPath as tF}from"node:url";import{spawn as lF}from"node:child_process";import{basename as pF}from"node:path";import{augmentNodeCommandForDebug as rF,withResolvedClineBuildEnv as iF}from"@cline/shared";function JW($){if($ instanceof Error)return $;return Error(String($))}var nF="CLINE_JS_RUNTIME_PATH";function QW($){let f=$?.trim();if(!f)return!1;let J=pF(f).toLowerCase();return J==="node"||J==="node.exe"||J==="bun"||J==="bun.exe"}function ZW($={}){let f=$.env??process.env,J=$.runtimeExecutable?.trim()||f[nF]?.trim();if(J)return J;let Q=$.execPath?.trim()||process.execPath;if(QW(Q))return Q;for(let Z of[f.BUN_EXEC_PATH,f.npm_node_execpath,f.NODE]){let W=Z?.trim();if(W&&QW(W))return W}return"node"}function aF($,f={}){let J=ZW({env:f.env,execPath:f.execPath,runtimeExecutable:f.runtimeExecutable});return rF([J,...$],{env:f.env,execArgv:f.execArgv,debugRole:f.name==="plugin-sandbox"?"plugin-sandbox":"sandbox"})}class c4{options;process=null;requestCounter=0;pending=new Map;constructor($){this.options=$}get processLabel(){return this.options.name??"sandbox"}clearPendingRequest($){let f=this.pending.get($);if(!f)return;if(this.pending.delete($),f.timeout)clearTimeout(f.timeout);return f}start(){if(this.process&&this.process.exitCode===null)return;let $=this.options.bootstrapFile?[this.options.bootstrapFile]:["-e",this.options.bootstrapScript??""],f=aF($,{name:this.options.name,runtimeExecutable:this.options.runtimeExecutable}),J=lF(f[0]??ZW(this.options),f.slice(1),{stdio:["ignore","ignore","pipe","ipc"],env:iF(process.env)});this.process=J;let Q="",Z=(W)=>{let j=Q+W;Q=j.length>4000?j.slice(-4000):j};J.stderr?.setEncoding("utf8"),J.stderr?.on("data",(W)=>{Z(W)}),J.on("message",(W)=>{this.onMessage(W)}),J.on("error",(W)=>{this.failPending(Error(`${this.processLabel} process error: ${JW(W).message}`))}),J.on("exit",(W,j)=>{this.process=null;let X=Q.trim();this.failPending(Error(`${this.options.name??"sandbox"} process exited (code=${String(W)}, signal=${String(j)})${X?`: ${X}`:""}`))})}async call($,f,J={}){this.start();let Q=this.process;if(!Q||Q.exitCode!==null)throw Error(`${this.processLabel} process is not available`);let Z=`req_${++this.requestCounter}`,W={type:"call",id:Z,method:$,args:f};return await new Promise((j,X)=>{let H={resolve:(Y)=>j(Y),reject:X};if((J.timeoutMs??0)>0)H.timeout=setTimeout(()=>{this.clearPendingRequest(Z),this.shutdown().catch(()=>{}),X(Error(`${this.processLabel} call timed out after ${J.timeoutMs}ms: ${$}`))},J.timeoutMs);this.pending.set(Z,H),Q.send(W,(Y)=>{if(!Y)return;let V=this.clearPendingRequest(Z);if(!V)return;V.reject(Error(`${this.processLabel} failed to send call "${$}": ${JW(Y).message}`))})})}async shutdown(){let $=this.process;if(this.process=null,!$||$.exitCode!==null){this.failPending(Error(`${this.processLabel} shutdown`));return}await new Promise((f)=>{let J=setTimeout(()=>{try{$.kill("SIGKILL")}catch{}f()},300);$.once("exit",()=>{clearTimeout(J),f()});try{$.kill("SIGTERM")}catch{clearTimeout(J),f()}}),this.failPending(Error(`${this.processLabel} shutdown`))}onMessage($){if(!$)return;if($.type==="event"){if(typeof $.name==="string"&&$.name.length>0)this.options.onEvent?.({name:$.name,payload:$.payload});return}if($.type!=="response"||!$.id)return;let f=this.clearPendingRequest($.id);if(!f)return;if($.ok){f.resolve($.result);return}f.reject(Error($.error?.message||`${this.processLabel} call failed`))}failPending($){for(let[f,J]of this.pending.entries()){if(this.pending.delete(f),J.timeout)clearTimeout(J.timeout);J.reject($)}}}function sF($){return{...$,contributions:{tools:$.contributions?.tools??[],commands:$.contributions?.commands??[],messageBuilders:$.contributions?.messageBuilders??[],providers:$.contributions?.providers??[],automationEventTypes:$.contributions?.automationEventTypes??[],shortcuts:$.contributions?.shortcuts??[],flags:$.contributions?.flags??[]}}}function l4($){return($ instanceof Error?$.message:String($)).includes("Unknown sandbox plugin id:")}function oF(){return`@cline/cli-${process.platform==="win32"?"windows":process.platform}-${process.arch}`}function eF(){let $=process.env.CLINE_WRAPPER_PATH?.trim();if(!$)return;try{let J=jW($).resolve(`${oF()}/package.json`),Q=i1(d4(J),"extensions","plugin-sandbox-bootstrap.js");return Z5(Q)?Q:void 0}catch{return}}function $P(){let $=process.execPath?.trim();if(!$)return;let f=i1(d4(d4($)),"extensions","plugin-sandbox-bootstrap.js");return Z5(f)?f:void 0}function fP(){let $=d4(tF(import.meta.url)),f=jW(import.meta.url),J=[i1($,"plugin-sandbox-bootstrap.js"),i1($,"extensions","plugin-sandbox-bootstrap.js"),i1($,"agents","plugin-sandbox-bootstrap.js"),eF(),$P()];for(let W of J.filter((j)=>typeof j==="string"))if(Z5(W))return{file:W};let Q=i1($,"plugin-sandbox-bootstrap.ts"),Z="jiti";try{Z=f.resolve("jiti")}catch{}return{script:[`const createJiti = require(${JSON.stringify(Z)});`,`const jiti = createJiti(${JSON.stringify(Q)}, { cache: false, requireCache: false, esmResolve: true, interopDefault: false });`,`Promise.resolve(jiti.import(${JSON.stringify(Q)}, {})).catch((error) => {`," console.error(error);"," process.exitCode = 1;","});"].join(`
164
+ `)}}var J5=fP();function Q5($,f){return typeof $==="number"&&$>0?$:f}async function p4($){let f=new c4({name:"plugin-sandbox",..."file"in J5?{bootstrapFile:J5.file}:{bootstrapScript:J5.script},onEvent:$.onEvent}),J=Q5($.importTimeoutMs,4000),Q=Q5($.hookTimeoutMs,3000),Z=Q5($.contributionTimeoutMs,60000),W={pluginPaths:$.pluginPaths,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,loggerEnabled:Boolean($.logger)},j,X=()=>{return j??=f.call("initialize",W,{timeoutMs:J}).finally(()=>{j=void 0}),j},H;try{H=await f.call("initialize",W,{timeoutMs:J})}catch(A){throw await f.shutdown().catch(()=>{}),A}return{extensions:H.plugins.map(sF).map((A)=>{let B={name:A.name,__clinePluginPath:A.pluginPath,manifest:A.manifest,setup:(G)=>{JP(G,f,A,Z,X),QP(G,f,A,Z,X),WP(G,f,A,Z,X),ZP(G,A)}};return B.hooks=XP(f,A,Q,X),B}),failures:H.failures,shutdown:async()=>{await f.shutdown()},warnings:H.warnings}}function JP($,f,J,Q,Z){for(let W of J.contributions?.tools??[]){let j={name:W.name,description:W.description??"",inputSchema:W.inputSchema??{type:"object",properties:{}},timeoutMs:W.timeoutMs,retryable:W.retryable,execute:async(X,H)=>{try{return await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:H},{timeoutMs:Q})}catch(Y){if(!l4(Y))throw Y;return await Z(),await f.call("executeTool",{pluginId:J.pluginId,contributionId:W.id,input:X,context:H},{timeoutMs:Q})}}};$.registerTool(j)}}function QP($,f,J,Q,Z){for(let W of J.contributions?.commands??[])$.registerCommand({name:W.name,description:W.description,handler:async(j)=>{try{return await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}catch(X){if(!l4(X))throw X;return await Z(),await f.call("executeCommand",{pluginId:J.pluginId,contributionId:W.id,input:j},{timeoutMs:Q})}}})}function ZP($,f){for(let J of f.contributions?.providers??[])$.registerProvider({name:J.name,description:J.description,metadata:J.metadata});for(let J of f.contributions?.automationEventTypes??[])$.registerAutomationEventType({eventType:J.eventType,source:J.source,description:J.description,attributesSchema:J.attributesSchema,payloadSchema:J.payloadSchema,examples:J.examples,metadata:J.metadata})}function WP($,f,J,Q,Z){for(let W of J.contributions?.messageBuilders??[])$.registerMessageBuilder({name:W.name,async build(j){try{let X=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return WW(X)?X:j}catch(X){if(!l4(X))throw X;await Z();let H=await f.call("buildMessages",{pluginId:J.pluginId,contributionId:W.id,messages:j},{timeoutMs:Q});return WW(H)?H:j}}})}function WW($){return Array.isArray($)&&$.every((f)=>typeof f==="object"&&f!==null&&("role"in f)&&("content"in f))}function jP($,f,J,Q,Z){return async(W)=>{try{return await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}catch(j){if(!l4(j))throw j;return await Z(),await $.call("invokeHook",{pluginId:f,hookName:J,payload:W},{timeoutMs:Q})}}}function XP($,f,J,Q){let Z={};for(let W of f.hooks??[])Z[W]=jP($,f.pluginId,W,J,Q);return Object.keys(Z).length>0?Z:void 0}function W5($){return AP($)}function j5($){return YP($)}function v2($={}){let f=$.cwd??process.cwd(),J=W5($.workspacePath).flatMap((j)=>j5(j)).filter((j)=>HP(j)),Q=VP($.pluginPaths??[],f),Z=[],W=new Set;for(let j of[...Q,...J]){if(W.has(j))continue;W.add(j),Z.push(j)}return rJ(Z)}async function r4($={}){let f=v2($);if(f.length===0)return{extensions:[],failures:[],warnings:[]};if($.mode==="in_process"){let Q=await g2(f,{cwd:$.cwd,exportName:$.exportName,providerId:$.providerId,modelId:$.modelId,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,automation:$.automation,logger:$.logger,telemetry:$.telemetry});return{extensions:Q.plugins,failures:Q.failures,warnings:Q.warnings}}let J=await p4({pluginPaths:f,exportName:$.exportName,importTimeoutMs:$.importTimeoutMs,hookTimeoutMs:$.hookTimeoutMs,contributionTimeoutMs:$.contributionTimeoutMs,onEvent:$.onEvent,providerId:$.providerId,modelId:$.modelId,cwd:$.cwd,session:$.session,client:$.client,user:$.user,workspaceInfo:$.workspaceInfo,logger:$.logger});return{extensions:J.extensions??[],shutdown:J.shutdown,failures:J.failures,warnings:J.warnings}}Z$();var GP=32,n1=new Map;function KP($,f){if(!n1.has($)&&n1.size>=GP){let J=n1.keys().next().value;if(J)n1.delete(J)}n1.set($,f)}async function FP($){let f=await Promise.all($.pluginPaths.map(async(J)=>{try{let Q=await BP(J);return`${J}:${Q.mtimeMs}:${Q.size}`}catch{return`${J}:missing`}}));return JSON.stringify({workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,pathStats:f})}function XW($,f){return $.map((J)=>({...J,enabled:!f.has(J.name)}))}function PP($){return $.sort((f,J)=>{let Q=f.name.localeCompare(J.name);if(Q!==0)return Q;return f.path.localeCompare(J.path)})}function UP($,f){if(!$.setup)return[];let J=[],Q={registerTool:(Z)=>J.push(Z),registerCommand:()=>{},registerMessageBuilder:()=>{},registerRule:()=>{},registerProvider:()=>{},registerAutomationEventType:()=>{}};return $.setup(Q,{workspaceInfo:f}),J}async function HW($){let f=v2({workspacePath:$.workspacePath,cwd:$.cwd}),J=Q$($.disabledToolNames);if(f.length===0)return{tools:[],failures:[],warnings:[]};let Q=await FP({pluginPaths:f,workspacePath:$.workspacePath,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId}),Z=n1.get(Q);if(Z)return{tools:XW(Z.tools,J),failures:Z.failures,warnings:Z.warnings};let W=[],j=[],X=[],H;try{H=await p4({pluginPaths:f,cwd:$.cwd,providerId:$.providerId,modelId:$.modelId,workspaceInfo:{rootPath:$.workspacePath}}),j=[...H.failures],X=[...H.warnings];for(let A of H.extensions??[]){let B=A.__clinePluginPath;if(!B)continue;for(let G of UP(A,{rootPath:$.workspacePath}))W.push({name:G.name,pluginName:A.name,path:B,source:B.startsWith($.workspacePath)?"workspace-plugin":"global-plugin",description:G.description?.trim()||void 0})}}catch(A){j=f.map((B)=>({pluginPath:B,phase:"load",message:A instanceof Error?A.message:String(A),stack:A instanceof Error?A.stack:void 0}))}finally{await H?.shutdown().catch(()=>{})}let Y=PP(W);return KP(Q,{tools:Y,failures:j,warnings:X}),{tools:XW(Y,J),failures:j,warnings:X}}async function X5($){return(await HW($)).tools}function n4($,f){if(!f)return"global";let J=RP(f,$);return!J.startsWith("..")&&!DP(J)?"workspace":"global"}function u2($){return[...$].sort((f,J)=>{let Q=(Z)=>{switch(Z){case"workspace":case"workspace-plugin":return 0;case"global":case"global-plugin":return 1;case"builtin":return 2}};if(f.source!==J.source)return Q(f.source)-Q(J.source);return f.name.localeCompare(J.name)})}function AW($){return $.workspaceRoot?.trim()||$.cwd?.trim()||""}async function VW($,f){if($.userInstructionService)return await f($.userInstructionService);let J=AW($);if(!J)return await f(void 0);let Q=c1({skills:{workspacePath:J},rules:{workspacePath:J},workflows:{workspacePath:J}});try{return await Q.start(),await f(Q)}finally{Q.stop()}}function LP($,f){if(!$)return;let J=$.listRecords("skill");if(f.id){let Q=J.find((Z)=>Z.id===f.id);if(Q)return Q}for(let Q of J)if(Q.filePath===f.path||Q.item.name===f.name||Q.id===f.name)return Q;return}class a1{async list($={}){return await VW($,async(f)=>{let J=AW($),Q=[],Z=[],W=[],j=[],X=[];if(f){for(let Y of f.listRecords("workflow")){let V=Y.item;Q.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"workflow",source:n4(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("rule")){let V=Y.item;Z.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"rule",source:n4(Y.filePath,J),description:V.instructions,toggleable:!1})}for(let Y of f.listRecords("skill")){let V=Y.item;W.push({id:Y.id,name:V.name,path:Y.filePath,enabled:V.disabled!==!0,kind:"skill",source:n4(Y.filePath,J),description:V.description,toggleable:!0})}}if(J)try{for(let Y of await X5({workspacePath:J,cwd:$.cwd,providerId:$.availabilityContext?.providerId,modelId:$.availabilityContext?.modelId}))j.push({id:`${Y.pluginName}:${Y.name}:${Y.path}`,name:Y.name,path:Y.path,enabled:Y.enabled,kind:"tool",source:Y.source,description:Y.description,toggleable:!0})}catch{}let H=C0();if(X1({filePath:H}))try{for(let Y of M$({filePath:H}))X.push({id:Y.name,name:Y.name,path:H,enabled:Y.disabled!==!0,kind:"mcp",source:n4(H,J),description:Y.transport.type,toggleable:!0})}catch{}return{workflows:u2(Q.filter((Y)=>i4(Y.path))),rules:u2(Z.filter((Y)=>i4(Y.path))),skills:u2(W.filter((Y)=>i4(Y.path))),tools:u2(j),mcp:u2(X.filter((Y)=>i4(Y.path)))}})}async toggle($){if($.type==="skills")return await VW($,async(f)=>{let J=LP(f,$),Q=J?.filePath;if(!Q)throw Error(`Unable to resolve skill setting '${$.id??$.name??YW($.path??"")}'.`);let Z=J?.item&&"disabled"in J.item?J.item.disabled!==!0:void 0,W=$.enabled??(Z!==void 0?!Z:void 0);if(W===void 0)throw Error(`Cannot determine toggle state for skill '${$.id??$.name??YW($.path??"")}'; provide an explicit enabled value or a resolvable workspace context.`);return await D3({filePath:Q,enabled:W}),await f?.refreshType("skill"),{snapshot:await this.list({...$,userInstructionService:f}),changedTypes:["skills"]}});if($.type==="tools"){if(!$.name?.trim())throw Error("Tool settings toggle requires a tool name.");if($.enabled===void 0)pJ($.name);else u3($.name,!$.enabled);return{snapshot:await this.list($),changedTypes:["tools"]}}if($.type==="mcp"){let f=$.name?.trim()||$.id?.trim();if(!f)throw Error("MCP server settings toggle requires a server name.");let J=$.path?.trim()||C0(),Q=$.enabled;if(Q===void 0){let Z=M$({filePath:J}).find((W)=>W.name===f);if(!Z)throw Error(`Unknown MCP server: ${f}`);Q=Z.disabled===!0}return S2({filePath:J,name:f,disabled:!Q}),{snapshot:await this.list($),changedTypes:["mcp"]}}throw Error(`Settings type '${$.type}' does not support toggles.`)}}function c2(){return new a1}function BW($){return{async list(f){let J=$;if(J.listSettings)return await J.listSettings(f);return await c2().list(f)},async toggle(f){let J=$;if(J.toggleSetting)return await J.toggleSetting(f);return await c2().toggle(f)}}}function GW($){function f(){let J=$.pendingPrompts;if(!J)throw Error("Pending prompt service is not available.");return J}return{list(J){return f().list(J)},update(J){return f().update(J)},delete(J){return f().delete(J)}}}function P0(...$){let f,J;for(let Z of $){if(!Z)continue;if(Z.toolExecutors)f={...f??{},...Z.toolExecutors};if(Z.requestToolApproval)J=Z.requestToolApproval}let Q=f&&Object.keys(f).length>0;if(!Q&&!J)return;return{...Q?{toolExecutors:f}:{},...J?{requestToolApproval:J}:{}}}function H5($){let{hooks:f,logger:J,telemetry:Q,extensionContext:Z,extraTools:W,extensions:j,onTeamEvent:X,onConsecutiveMistakeLimitReached:H,checkpoint:Y,compaction:V,...A}=$,B={};if(f)B.hooks=f;if(J)B.logger=J;if(Q)B.telemetry=Q;if(Z)B.extensionContext=Z;if(W)B.extraTools=W;if(j)B.extensions=j;if(X)B.onTeamEvent=X;if(H)B.onConsecutiveMistakeLimitReached=H;if(Y?.createCheckpoint)B.checkpoint=Y;if(V?.compact)B.compaction=V;let G=Object.keys(B).length>0?B:void 0;return{config:{...A,...Y?{checkpoint:{enabled:Y.enabled}}:{},...V?{compaction:{enabled:V.enabled,strategy:V.strategy,thresholdRatio:V.thresholdRatio,reserveTokens:V.reserveTokens,preserveRecentTokens:V.preserveRecentTokens,maxInputTokens:V.maxInputTokens,summarizer:V.summarizer}}:{}},...G?{localRuntime:G}:{}}}function KW($){let f=$.config;return"providerId"in f?{...$,config:{...f,...OP($.localRuntime)},localRuntime:$.localRuntime}:$}function Y5($,f={}){let J=H5($.config),Q=P0(f.defaultCapabilities,$.capabilities),Z=zP(J.localRuntime,$.localRuntime),W=f.withExtensionContext?.(Z?.extensionContext);if(W)Z={...Z??{},extensionContext:W};return{...$,...J,...Z?{localRuntime:Z}:{},...Q?{capabilities:Q}:{}}}function OP($){if(!$)return{};let{modelCatalogDefaults:f,userInstructionService:J,configExtensions:Q,onTeamRestored:Z,...W}=$;return W}function zP(...$){let f={};for(let J of $)if(J)Object.assign(f,J);return Object.keys(f).length>0?f:void 0}G0();function FW($){let f=$.input.config.telemetry??$.telemetry;if(!f)return;f.capture({event:k.SESSION.STARTED,properties:{sessionId:$.sessionId,source:$.input.source??F0.CORE,providerId:$.input.config.providerId,modelId:$.input.config.modelId,enableTools:$.input.config.enableTools,enableSpawnAgent:$.input.config.enableSpawnAgent,enableAgentTeams:$.input.config.enableAgentTeams,clientName:$.clientName,runtimeAddress:$.runtimeAddress}})}function d2($){return!!$&&typeof $==="object"&&!Array.isArray($)}function V5($){let f=$?.trim();return f?f:void 0}function _P($,f){let J=$?.trim();if(!J)return f;let Q=Date.parse(J);if(!Number.isFinite(Q))return f;return new Date(Q).toISOString()}function PW($,f){return new Date(new Date($).getTime()+Math.max(0,Math.floor(f))*1000).toISOString()}function UW($,f){return new Date(new Date($).getTime()-Math.max(0,Math.floor(f))*1000).toISOString()}function NP($,f){if(!$)return f;return new Date($).getTime()>=new Date(f).getTime()?$:f}function TP($,f){let J=$.eventId.trim(),Q=$.eventType.trim(),Z=$.source.trim(),W=V5($.subject),j=V5($.dedupeKey)??`${Q}:${Z}:${W??J}`;return{eventId:J,eventType:Q,source:Z,subject:W,occurredAt:_P($.occurredAt,f),workspaceRoot:V5($.workspaceRoot),payload:d2($.payload)?$.payload:void 0,attributes:d2($.attributes)?$.attributes:void 0,dedupeKey:j}}function A5($,f){if(!f)return;let J=f.split("."),Q=$;for(let Z of J){if(!d2(Q))return;Q=Q[Z]}return Q}function MP($,f){if($.attributes&&Object.hasOwn($.attributes,f))return $.attributes[f];if($.payload&&Object.hasOwn($.payload,f))return $.payload[f];let J={eventId:$.eventId,eventType:$.eventType,source:$.source,subject:$.subject,occurredAt:$.occurredAt,workspaceRoot:$.workspaceRoot,dedupeKey:$.dedupeKey,attributes:$.attributes,payload:$.payload},Q=A5(J,f);if(Q!==void 0)return Q;if($.attributes){let Z=A5($.attributes,f);if(Z!==void 0)return Z}if($.payload)return A5($.payload,f);return}function a4($,f){if(Array.isArray(f))return f.some((J)=>a4($,J));if(Array.isArray($))return $.some((J)=>a4(J,f));if(d2(f)){if(!d2($))return!1;return Object.entries(f).every(([J,Q])=>a4($[J],Q))}return Object.is($,f)}function qP($,f){if(!f||Object.keys(f).length===0)return!0;return Object.entries(f).every(([J,Q])=>a4(MP($,J),Q))}class B5{store;nowFn;logger;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now()),this.logger=$.logger}ingestEvent($){let f=new Date(this.nowFn()).toISOString(),J=TP($,f),Q=this.store.insertEventLog(J,{receivedAtIso:f});if(!Q.created)return this.logger?.debug("cron.event.duplicate",{eventId:Q.record.eventId,eventType:Q.record.eventType,source:Q.record.source}),{event:Q.record,duplicate:!0,matchedSpecs:[],queuedRuns:[],suppressions:[{reason:"duplicate_event",dedupeKey:Q.record.dedupeKey}]};try{let Z=this.store.listEventSpecsForType(J.eventType),W=[],j=[],X=[];for(let V of Z){if(!qP(J,V.filters)){W.push({specId:V.specId,externalId:V.externalId,reason:"filter_mismatch",dedupeKey:J.dedupeKey});continue}j.push(V);let A=this.materializeForSpec(V,J,Q.record.receivedAt);if(A.run)X.push(A.run);else W.push({specId:V.specId,externalId:V.externalId,reason:A.reason,dedupeKey:J.dedupeKey})}let H=j.length===0?"unmatched":X.length>0?"queued":"suppressed";this.store.updateEventLogProcessing(Q.record.eventId,{status:H,matchedSpecCount:j.length,queuedRunCount:X.length,suppressedCount:W.filter((V)=>V.reason!=="filter_mismatch").length});let Y=this.store.getEventLog(Q.record.eventId);return this.logger?.debug("cron.event.processed",{eventId:Q.record.eventId,eventType:Q.record.eventType,status:H,matchedSpecCount:j.length,queuedRunCount:X.length}),{event:Y??Q.record,duplicate:!1,matchedSpecs:j,queuedRuns:X,suppressions:W}}catch(Z){if(this.store.updateEventLogProcessing(Q.record.eventId,{status:"failed",error:Z instanceof Error?Z.message:String(Z)}),this.logger?.error)this.logger.error("cron.event.failed",{eventId:Q.record.eventId,eventType:Q.record.eventType,error:Z});throw Z}}materializeForSpec($,f,J){let Q=f.dedupeKey??f.eventId,Z=$.debounceSeconds??0;if(Z>0){let H=this.store.findQueuedEventRunForDedupe({specId:$.specId,dedupeKey:Q});if(H){let Y=NP(H.scheduledFor,PW(J,Z)),V=this.store.updateQueuedEventRunForDebounce({runId:H.runId,triggerEventId:f.eventId,scheduledFor:Y});if(V)return{run:V,reason:"dedupe_window"}}}let W=$.dedupeWindowSeconds??0;if(W>0&&this.store.hasRecentEventRunForDedupe({specId:$.specId,dedupeKey:Q,sinceIso:UW(J,W)}))return{reason:"dedupe_window"};let j=$.cooldownSeconds??0;if(j>0&&this.store.hasRecentEventRunForSpec({specId:$.specId,sinceIso:UW(J,j)}))return{reason:"cooldown"};return{run:this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"event",triggerEventId:f.eventId,scheduledFor:Z>0?PW(J,Z):J}),reason:"dedupe_window"}}}class l2{store;nowFn;constructor($){this.store=$.store,this.nowFn=$.now??(()=>Date.now())}materializeAll(){let $={oneOffQueued:0,scheduleQueued:0},f=this.store.listSpecs({triggerKind:"one_off",enabled:!0,parseStatus:"valid"});for(let Q of f)if(this.materializeOneOff(Q))$.oneOffQueued+=1;let J=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let Q of J)try{if(this.materializeSchedule(Q))$.scheduleQueued+=1}catch{}return $}materializeOneOff($){if($.triggerKind!=="one_off")return!1;if(!$.enabled||$.removed)return!1;if(this.store.hasOneOffRunForRevision($.specId,$.revision))return!1;return this.store.enqueueRun({specId:$.specId,specRevision:$.revision,triggerKind:"one_off",scheduledFor:new Date(this.nowFn()).toISOString()}),!0}materializeSchedule($){if($.triggerKind!=="schedule")return!1;if(!$.enabled||$.removed)return!1;if(!$.scheduleExpr)return!1;return this.store.materializeDueScheduleRun({specId:$.specId,nowMs:this.nowFn()}).queued}}import{basename as xP}from"node:path";import{buildClineSystemPrompt as mP}from"@cline/shared";import{nowIso as OW}from"@cline/shared/db";import{basename as yP,resolve as wP}from"node:path";import{performance as DW}from"node:perf_hooks";import{processWorkspaceInfo as RW}from"@cline/shared";import SP from"simple-git";function Y1($){return wP($)}async function s4($){return(await G5($)).info}function t4($){if($ instanceof Error)return{errorType:$.name?.trim()||$.constructor.name||"Error",message:$.message};return{errorType:"Error",message:String($)}}async function G5($){let f=Y1($),J={rootPath:f,hint:yP(f)},Q;try{let Z=SP({baseDir:f});if(!await Z.checkIsRepo())return{info:J,vcsType:"none"};try{let j=await Z.getRemotes(!0);if(j.length>0){let X=j.map((H)=>{let Y=H.refs.fetch||H.refs.push;return`${H.name}: ${Y}`});J.associatedRemoteUrls=X}}catch(j){Q??=t4(j)}try{let j=(await Z.revparse(["HEAD"])).trim();if(j.length>0)J.latestGitCommitHash=j}catch(j){Q??=t4(j)}try{let j=(await Z.branch()).current.trim();if(j.length>0)J.latestGitBranchName=j}catch(j){Q??=t4(j)}return{info:J,vcsType:"git",error:Q}}catch(Z){return{info:J,vcsType:"none",error:t4(Z)}}}async function K5($){let f=await s4($);return RW(f)}async function LW($){let f=DW.now(),J=await G5($),Q=DW.now()-f,Z=J.info;return{workspaceInfo:Z,workspaceMetadata:RW(Z),durationMs:Q,vcsType:J.vcsType,initError:J.error}}import{mkdirSync as hP,writeFileSync as CP}from"node:fs";import{join as EP}from"node:path";import{resolveCronReportsDir as bP}from"@cline/shared/storage";function y$($){if(/[:#\n]/.test($)||$.includes('"'))return JSON.stringify($);return $}function V1($,f){if(f===void 0||f===null)return;return`${$}: ${y$(f)}`}function kP($,f,J){let Q=[`runId: ${y$($.runId)}`,`specId: ${y$(f.specId)}`,`externalId: ${y$(f.externalId)}`,`title: ${y$(f.title)}`,`triggerKind: ${y$($.triggerKind)}`,`status: ${y$($.status)}`,`sourcePath: ${y$(f.sourcePath)}`],Z=[V1("sessionId",$.sessionId),V1("startedAt",$.startedAt),V1("completedAt",$.completedAt),V1("triggerEventId",$.triggerEventId),V1("triggerEventType",J?.eventType),V1("triggerEventSource",J?.source),V1("triggerEventSubject",J?.subject)];for(let W of Z)if(W)Q.push(W);return`---
165
165
  ${Q.join(`
166
166
  `)}
167
167
  ---
168
- `}function eP($){let f=[];if($.triggerEvent){let J=$.triggerEvent,Q=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
168
+ `}function IP($){let f=[];if($.triggerEvent){let J=$.triggerEvent,Q=[`- eventId: ${J.eventId}`,`- eventType: ${J.eventType}`,`- source: ${J.source}`,J.subject?`- subject: ${J.subject}`:"",`- occurredAt: ${J.occurredAt}`,J.dedupeKey?`- dedupeKey: ${J.dedupeKey}`:"",J.attributes?`- attributes: ${JSON.stringify(J.attributes)}`:""].filter((Z)=>Z.length>0);f.push(`## Trigger Event
169
169
 
170
170
  ${Q.join(`
171
171
  `)}
@@ -184,17 +184,17 @@ ${Q.join(`
184
184
  ${J.join(`
185
185
  `)}
186
186
  `)}return f.join(`
187
- `)}function J5($){let f=sP($.specs);nP(f,{recursive:!0});let J=tP(f,`${$.run.runId}.md`),Q=`${oP($.run,$.spec,$.data.triggerEvent)}
188
- ${eP($.data)}`;return aP(J,Q,"utf8"),J}class Q5{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=Q)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var JF=15000,QF=90,jW=["rules","skills","plugins"];function ZF($,f){return new Set($.extensions??jW).has(f)}function WF($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)J[Q]={enabled:!0,autoApprove:!0};if(f==="yolo")J[Z0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function jF($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
189
- `)}class Z5 extends Error{constructor($){super($);this.name="TimeoutError"}}async function XF($,f){if(f<=0)return $;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new Z5("cron run timed out"))},f)});try{return await Promise.race([$,Q])}finally{if(J)clearTimeout(J)}}class cf{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 Q5($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??QF)*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??JF);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:WW(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,Q)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let W=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,H=Date.now(),Y;if(J.timeoutSeconds&&J.timeoutSeconds>0)Y=H+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let V=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(V)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:V,prompt:this.buildPrompt(J,W)},K=this.options.runtimeHandlers.sendSession(j,B),G=Y?Math.max(1,Y-Date.now()):0,F=(await XF(K,G)).result,P=Date.now(),D=J5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:F.text,usage:F.usage,toolCalls:F.toolCalls,durationMs:P-H,triggerEvent:W}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:D,claimToken:$.claimToken}),this.store.updateSpecLastRunAt(J.specId,WW())}catch(V){let A=V instanceof Z5;if(j&&A)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=V instanceof Error?V.message:String(V),K=Date.now(),G=J5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:K-H,triggerEvent:W}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:G,error:B,claimToken:$.claimToken})}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let Q={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
187
+ `)}function F5($){let f=bP($.specs);hP(f,{recursive:!0});let J=EP(f,`${$.run.runId}.md`),Q=`${kP($.run,$.spec,$.data.triggerEvent)}
188
+ ${IP($.data)}`;return CP(J,Q,"utf8"),J}class P5{globalMaxConcurrency;activeExecutions=new Map;constructor($){this.globalMaxConcurrency=Math.max(1,Math.floor($))}acquire($,f,J){if(this.getGlobalActiveCount()>=this.globalMaxConcurrency)return!1;let Q=Math.max(1,Math.floor(J)),Z=this.activeExecutions.get($)??new Set;if(Z.size>=Q)return!1;return Z.add(f),this.activeExecutions.set($,Z),!0}release($,f){let J=this.activeExecutions.get($);if(!J)return;if(J.delete(f),J.size===0)this.activeExecutions.delete($)}getGlobalActiveCount(){let $=0;for(let f of this.activeExecutions.values())$+=f.size;return $}}var gP=15000,vP=90,zW=["rules","skills","plugins"];function uP($,f){return new Set($.extensions??zW).has(f)}function cP($,f){if($.tools===void 0)return{"*":{autoApprove:!0}};let J={"*":{enabled:!1,autoApprove:!0}};for(let Q of $.tools)J[Q]={enabled:!0,autoApprove:!0};if(f==="yolo")J[W0.SUBMIT_AND_EXIT]={enabled:!0,autoApprove:!0};return J}function dP($){let f=$?.trim();if(!f)return;return["# Notes Directory",`Use ${f} for durable notes related to this automation.`,"Before starting, inspect relevant existing notes there when useful. During or after the run, write concise notes there when they would help future runs continue with context."].join(`
189
+ `)}class U5 extends Error{constructor($){super($);this.name="TimeoutError"}}async function lP($,f){if(f<=0)return $;let J,Q=new Promise((Z,W)=>{J=setTimeout(()=>{W(new U5("cron run timed out"))},f)});try{return await Promise.race([$,Q])}finally{if(J)clearTimeout(J)}}class p2{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 P5($.globalMaxConcurrency??10),this.claimLeaseMs=Math.max(5000,($.claimLeaseSeconds??vP)*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??gP);await this.tick(),this.timer=setInterval(()=>void this.tick(),$)}async stop(){let $=this.started;if(this.started=!1,this.stopping=!0,this.timer)clearInterval(this.timer),this.timer=void 0;if(!$)return;let f=[...this.activeRuns.entries()];await Promise.all(f.map(async([J,Q])=>{if(Q.sessionId)try{await this.options.runtimeHandlers.abortSession(Q.sessionId)}catch{}try{this.store.requeueRun({runId:J,claimToken:Q.claimToken,error:"runner stopped before completion"})}catch{}}))}async dispose(){if(this.disposed)return;this.disposed=!0,await this.stop()}async tick(){if(this.ticking)return;this.ticking=!0;try{this.materializer.materializeAll();let $=this.store.claimDueRuns({nowIso:OW(),leaseMs:this.claimLeaseMs});await Promise.allSettled($.map((f)=>this.executeClaim(f)))}catch($){let f=this.options.logger;if(f)if(f.error)f.error("cron.runner.tick.failed",{error:$});else f.log("cron.runner.tick.failed",{error:$})}finally{this.ticking=!1}}getActiveRuns(){return[...this.activeRuns.entries()].flatMap(([$,f])=>{let J=this.store.getRun($);return J?[{...J,...f}]:[]})}async executeClaim($){let f=$.run,J=this.store.getSpec(f.specId);if(!J){this.store.completeRun(f.runId,{status:"failed",error:"spec not found",claimToken:$.claimToken});return}if(!J.enabled||J.removed){this.store.completeRun(f.runId,{status:"cancelled",error:"spec disabled or removed",claimToken:$.claimToken});return}let Q=J.maxParallel&&J.maxParallel>0?J.maxParallel:1;if(!this.limiter.acquire(J.specId,f.runId,Q)){this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"concurrency limit reached"});return}if(this.stopping){this.limiter.release(J.specId,f.runId),this.store.requeueRun({runId:f.runId,claimToken:$.claimToken,error:"runner stopped before execution"});return}this.activeRuns.set(f.runId,{claimToken:$.claimToken});let W=f.triggerEventId?this.store.getEventLog(f.triggerEventId):void 0,j,X,H=Date.now(),Y;if(J.timeoutSeconds&&J.timeoutSeconds>0)Y=H+J.timeoutSeconds*1000;try{X=this.startClaimLeaseHeartbeat($);let V=await this.buildStartRequest(J);if(j=(await this.options.runtimeHandlers.startSession(V)).sessionId.trim(),!j)throw Error("runtime returned empty sessionId");this.activeRuns.set(f.runId,{claimToken:$.claimToken,sessionId:j}),this.store.attachSessionIdToRun(f.runId,j);let B={config:V,prompt:this.buildPrompt(J,W)},G=this.options.runtimeHandlers.sendSession(j,B),K=Y?Math.max(1,Y-Date.now()):0,F=(await lP(G,K)).result,P=Date.now(),U=F5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"done"},spec:J,data:{finalText:F.text,usage:F.usage,toolCalls:F.toolCalls,durationMs:P-H,triggerEvent:W}});this.store.completeRun(f.runId,{status:"done",sessionId:j,reportPath:U,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.completed",J,f.runId),this.store.updateSpecLastRunAt(J.specId,OW())}catch(V){let A=V instanceof U5;if(j&&A)try{await this.options.runtimeHandlers.abortSession(j)}catch{}let B=V instanceof Error?V.message:String(V),G=Date.now(),K=F5({specs:this.options.specs,workspaceRoot:this.options.workspaceRoot,run:{...f,sessionId:j,status:"failed"},spec:J,data:{error:B,durationMs:G-H,triggerEvent:W}});this.store.completeRun(f.runId,{status:"failed",sessionId:j,reportPath:K,error:B,claimToken:$.claimToken}),this.publishScheduleExecutionEvent("schedule.execution.failed",J,f.runId)}finally{if(X?.(),j)try{await this.options.runtimeHandlers.stopSession(j)}catch{}this.activeRuns.delete(f.runId),this.limiter.release(J.specId,f.runId)}}publishScheduleExecutionEvent($,f,J){if(f.source!=="hub-schedule"||!this.options.eventPublisher)return;let Q=this.store.getRun(J);if(!Q)return;let Z=Q.status==="done"?"success":Q.status==="cancelled"?"aborted":Q.status==="running"?"running":Q.status==="queued"?"pending":"failed";this.options.eventPublisher($,{scheduleId:f.externalId,executionId:Q.runId,sessionId:Q.sessionId,triggeredAt:new Date(Q.scheduledFor??Q.createdAt).getTime(),startedAt:Q.startedAt?new Date(Q.startedAt).getTime():void 0,endedAt:Q.completedAt?new Date(Q.completedAt).getTime():void 0,status:Z,errorMessage:Q.error})}buildPrompt($,f){let J=$.prompt??"";if(!f)return J;let Q={eventId:f.eventId,eventType:f.eventType,source:f.source,subject:f.subject,occurredAt:f.occurredAt,workspaceRoot:f.workspaceRoot,dedupeKey:f.dedupeKey,attributes:f.attributes,payload:f.payload};return`${J}
190
190
 
191
191
  Trigger event:
192
- ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,Q){let Z=jF($.notesDirectory),W=s2(void 0,Z),j=await f5(f),X=fF({ide:"Cline Cron",workspaceRoot:f,workspaceName:$F(f),metadata:j,rules:$.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?s2(X,W)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),Q=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,W=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:W,provider:J,model:Q,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:WF($,j),configExtensions:jW.filter((X)=>ZF($,X))}}}import{existsSync as SF,readdirSync as CF,readFileSync as EF,statSync as hF}from"node:fs";import{relative as bF}from"node:path";import{resolveCronSpecsDir as kF}from"@cline/shared/storage";function uf($,f,J,Q){let Z=new Set;function W(j){let X=j.toLowerCase();if(Q){let Y=Q.indexOf(X);if(Y!==-1)return Y+f}let H=Number(j);if(!Number.isInteger(H)||H<f||H>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return H}for(let j of $.split(",")){if(j==="*"){for(let Y=f;Y<=J;Y+=1)Z.add(Y);continue}let X=j.indexOf("/");if(X!==-1){let Y=j.slice(0,X),V=Number(j.slice(X+1));if(!Number.isInteger(V)||V<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let A=f,B=J;if(Y!=="*"){let K=Y.indexOf("-");if(K!==-1)A=W(Y.slice(0,K)),B=W(Y.slice(K+1));else A=W(Y)}if(A>B)throw Error(`Invalid cron range "${Y}"`);for(let K=A;K<=B;K+=V)Z.add(K);continue}let H=j.indexOf("-");if(H!==-1){let Y=W(j.slice(0,H)),V=W(j.slice(H+1));if(Y>V)throw Error(`Invalid cron range "${j}"`);for(let A=Y;A<=V;A+=1)Z.add(A);continue}Z.add(W(j))}return[...Z].sort((j,X)=>j-X)}var HF=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],HW=["sun","mon","tue","wed","thu","fri","sat"];function df($,f,J){let Q=$[f];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return Q}function W5($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function j5($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:uf(df(f,0,$),0,59),hours:uf(df(f,1,$),0,23),daysOfMonth:uf(df(f,2,$),1,31),months:uf(df(f,3,$),1,12,HF),daysOfWeek:uf(df(f,4,$),0,6,HW)}}function X5($){j5($)}function YW($,f,J=Date.now()){H1($,J,f)}var XW=new Map,YF=new Map(HW.map(($,f)=>[$,f]));function VW($){let f=$?.trim();return f?f:void 0}function AW($){let f=XW.get($);if(f)return f;let J=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return XW.set($,J),J}function VF($){let f=VW($);if(!f)return;AW(f).format(new Date)}function AF($,f){let J=AW(f).formatToParts(new Date($)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=YF.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function BF($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function KF($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function GF($,f,J){let Q=j5($),Z=new Date(f);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(W<=X){if(KF(Q,AF(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function H1($,f,J){let Q=VW(J);if(Q)return VF(Q),GF($,f,Q);let Z=j5($),W=new Date(f);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:X,dayOfMonth:H,dayOfWeek:Y,hour:V,minute:A}=BF(W.getTime());if(!Z.months.includes(X)){let B=Z.months.find((G)=>G>X)??W5(Z.months,"months"),K=B<=X?1:0;W=new Date(W.getFullYear()+K,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(H)||!Z.daysOfWeek.includes(Y)){W=new Date(W.getFullYear(),W.getMonth(),H+1,0,0,0,0);continue}if(!Z.hours.includes(V)){let B=Z.hours.find((G)=>G>V)??W5(Z.hours,"hours"),K=B<=V?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+K,B,0,0,0);continue}if(!Z.minutes.includes(A)){let B=Z.minutes.find((G)=>G>A)??W5(Z.minutes,"minutes"),K=B<=A?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate(),W.getHours()+K,B,0,0);continue}return W.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as PF}from"node:crypto";import FF from"yaml";function DF($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function RF($){let f=$.replace(/\r\n/g,`
192
+ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Math.floor(this.claimLeaseMs/2)),J=setInterval(()=>{let Q=new Date(Date.now()+this.claimLeaseMs).toISOString();if(!this.store.renewClaim($.run.runId,$.claimToken,Q))clearInterval(J)},f);return()=>clearInterval(J)}async buildSystemPrompt($,f,J,Q){let Z=dP($.notesDirectory),W=Q4(void 0,Z),j=await K5(f),X=mP({ide:"Cline Cron",workspaceRoot:f,workspaceName:xP(f),metadata:j,rules:$.systemPrompt?void 0:W,mode:J,providerId:Q,overridePrompt:$.systemPrompt,platform:typeof process<"u"&&process?.platform||"unknown"});return $.systemPrompt?Q4(X,W)??X:X}async buildStartRequest($){let f=($.workspaceRoot??"").trim(),J=($.providerId??"").trim(),Q=($.modelId??"").trim(),Z=$.metadata?.__hubRuntimeOptions&&typeof $.metadata.__hubRuntimeOptions==="object"&&!Array.isArray($.metadata.__hubRuntimeOptions)?$.metadata.__hubRuntimeOptions:void 0,W=typeof $.metadata?.__hubScheduleCwd==="string"&&$.metadata.__hubScheduleCwd.trim()?$.metadata.__hubScheduleCwd.trim():f;if(!f)throw Error("cron spec requires workspaceRoot");let j=$.mode==="plan"?"plan":$.mode==="act"?"act":"yolo";return{workspaceRoot:f,cwd:W,provider:J,model:Q,mode:j,source:$.source?.trim()||"user",systemPrompt:await this.buildSystemPrompt($,f,j,J),maxIterations:$.maxIterations,enableTools:Z?.enableTools??!0,enableSpawn:Z?.enableSpawn??!0,enableTeams:Z?.enableTeams??!0,autoApproveTools:Z?.autoApproveTools??!0,toolPolicies:cP($,j),configExtensions:zW.filter((X)=>uP($,X))}}}import{existsSync as GU,readdirSync as KU,readFileSync as FU,statSync as PU}from"node:fs";import{relative as UU}from"node:path";import{resolveCronSpecsDir as DU}from"@cline/shared/storage";function r2($,f,J,Q){let Z=new Set;function W(j){let X=j.toLowerCase();if(Q){let Y=Q.indexOf(X);if(Y!==-1)return Y+f}let H=Number(j);if(!Number.isInteger(H)||H<f||H>J)throw Error(`Invalid cron value "${j}" for range [${f}-${J}]`);return H}for(let j of $.split(",")){if(j==="*"){for(let Y=f;Y<=J;Y+=1)Z.add(Y);continue}let X=j.indexOf("/");if(X!==-1){let Y=j.slice(0,X),V=Number(j.slice(X+1));if(!Number.isInteger(V)||V<1)throw Error(`Invalid step "${j.slice(X+1)}"`);let A=f,B=J;if(Y!=="*"){let G=Y.indexOf("-");if(G!==-1)A=W(Y.slice(0,G)),B=W(Y.slice(G+1));else A=W(Y)}if(A>B)throw Error(`Invalid cron range "${Y}"`);for(let G=A;G<=B;G+=V)Z.add(G);continue}let H=j.indexOf("-");if(H!==-1){let Y=W(j.slice(0,H)),V=W(j.slice(H+1));if(Y>V)throw Error(`Invalid cron range "${j}"`);for(let A=Y;A<=V;A+=1)Z.add(A);continue}Z.add(W(j))}return[...Z].sort((j,X)=>j-X)}var pP=["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"],NW=["sun","mon","tue","wed","thu","fri","sat"];function i2($,f,J){let Q=$[f];if(typeof Q!=="string")throw Error(`Invalid cron pattern "${J}": missing field ${f+1}`);return Q}function D5($,f){let J=$[0];if(typeof J!=="number")throw Error(`Invalid cron pattern: no values parsed for ${f}`);return J}function R5($){let f=$.trim().split(/\s+/);if(f.length!==5)throw Error(`Invalid cron pattern "${$}": expected 5 fields, got ${f.length}`);return{minutes:r2(i2(f,0,$),0,59),hours:r2(i2(f,1,$),0,23),daysOfMonth:r2(i2(f,2,$),1,31),months:r2(i2(f,3,$),1,12,pP),daysOfWeek:r2(i2(f,4,$),0,6,NW)}}function L5($){R5($)}function TW($,f,J=Date.now()){A1($,J,f)}var _W=new Map,rP=new Map(NW.map(($,f)=>[$,f]));function MW($){let f=$?.trim();return f?f:void 0}function qW($){let f=_W.get($);if(f)return f;let J=new Intl.DateTimeFormat("en-US",{timeZone:$,calendar:"gregory",numberingSystem:"latn",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});return _W.set($,J),J}function iP($){let f=MW($);if(!f)return;qW(f).format(new Date)}function nP($,f){let J=qW(f).formatToParts(new Date($)),Q=new Map(J.map((j)=>[j.type,j.value])),Z=Q.get("weekday")?.toLowerCase().slice(0,3)??"",W=rP.get(Z);if(W===void 0)throw Error(`Unable to resolve weekday for timezone "${f}"`);return{month:Number(Q.get("month")),dayOfMonth:Number(Q.get("day")),dayOfWeek:W,hour:Number(Q.get("hour")),minute:Number(Q.get("minute"))}}function aP($){let f=new Date($);return{month:f.getMonth()+1,dayOfMonth:f.getDate(),dayOfWeek:f.getDay(),hour:f.getHours(),minute:f.getMinutes()}}function tP($,f){return $.months.includes(f.month)&&$.daysOfMonth.includes(f.dayOfMonth)&&$.daysOfWeek.includes(f.dayOfWeek)&&$.hours.includes(f.hour)&&$.minutes.includes(f.minute)}function sP($,f,J){let Q=R5($),Z=new Date(f);Z.setSeconds(0,0);let W=Z.getTime()+60000,j=new Date(f);j.setFullYear(j.getFullYear()+4);let X=j.getTime();while(W<=X){if(tP(Q,nP(W,J)))return W;W+=60000}throw Error(`No cron occurrence found within 4 years for pattern "${$}" in timezone "${J}"`)}function A1($,f,J){let Q=MW(J);if(Q)return iP(Q),sP($,f,Q);let Z=R5($),W=new Date(f);W.setSeconds(0,0),W=new Date(W.getTime()+60000);let j=new Date(f);j.setFullYear(j.getFullYear()+4);while(W<=j){let{month:X,dayOfMonth:H,dayOfWeek:Y,hour:V,minute:A}=aP(W.getTime());if(!Z.months.includes(X)){let B=Z.months.find((K)=>K>X)??D5(Z.months,"months"),G=B<=X?1:0;W=new Date(W.getFullYear()+G,B-1,1,0,0,0,0);continue}if(!Z.daysOfMonth.includes(H)||!Z.daysOfWeek.includes(Y)){W=new Date(W.getFullYear(),W.getMonth(),H+1,0,0,0,0);continue}if(!Z.hours.includes(V)){let B=Z.hours.find((K)=>K>V)??D5(Z.hours,"hours"),G=B<=V?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate()+G,B,0,0,0);continue}if(!Z.minutes.includes(A)){let B=Z.minutes.find((K)=>K>A)??D5(Z.minutes,"minutes"),G=B<=A?1:0;W=new Date(W.getFullYear(),W.getMonth(),W.getDate(),W.getHours()+G,B,0,0);continue}return W.getTime()}throw Error(`No cron occurrence found within 4 years for pattern "${$}"`)}import{createHash as oP}from"node:crypto";import eP from"yaml";function $U($){let f=$.replace(/\\/g,"/");if(f.startsWith("events/")&&f.endsWith(".event.md"))return"event";if(f.endsWith(".cron.md"))return"schedule";return"one_off"}function fU($){let f=$.replace(/\r\n/g,`
193
193
  `);if(!f.startsWith(`---
194
194
  `))return{frontmatter:void 0,body:$};let J=f.slice(4),Q=J.indexOf(`
195
195
  ---`);if(Q===-1)return{frontmatter:void 0,body:$};let Z=J.slice(0,Q),W=J.slice(Q+4);if(W.startsWith(`
196
- `))W=W.slice(1);return{frontmatter:Z,body:W}}function C0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function UF($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function V5($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function LF($){let f=V5($);if(!f)return;let J=C0(f.providerId),Q=C0(f.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function OF($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function KW($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let Q=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var zF=new Set(b1);function _F($){let f=KW($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!zF.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var yF=new Set(["rules","skills","plugins"]);function NF($){let f=KW($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!yF.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function H5($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function Y5($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function A5($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>A5(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${f.map(([J,Q])=>`${JSON.stringify(J)}:${A5(Q)}`).join(",")}}`}function GW($,f){let J=PF("sha256");return J.update(A5($)),J.update(`
197
- `),J.update(f),J.digest("hex")}function TF($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var MF=["schedule","timezone"],qF=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],wF=["cwd"];function BW($,f,J,Q,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:GW(Q,J),error:Z}}function i0($,f,J,Q,Z,W){return{externalId:$,relativePath:f,triggerKind:J,body:Q,contentHash:Z,error:W}}function PW($){let f=$.relativePath.replace(/\\/g,"/"),J=DF(f),{frontmatter:Q,body:Z}=RF($.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let D=FF.parse(Q);if(D&&typeof D==="object"&&!Array.isArray(D))W=D;else if(D!==null&&D!==void 0)return BW(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(D){return BW(f,J,Z,{},D instanceof Error?`failed to parse frontmatter: ${D.message}`:"failed to parse frontmatter")}let j=GW(W,Z),X=C0(W.id),H=X??f;if(J!=="schedule"){for(let D of MF)if(W[D]!==void 0)return i0(H,f,J,Z,j,`field "${D}" is only allowed on *.cron.md specs`)}for(let D of wF)if(W[D]!==void 0)return i0(H,f,J,Z,j,`field "${D}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let D of qF)if(W[D]!==void 0)return i0(H,f,J,Z,j,`field "${D}" is only allowed on .event.md specs`)}let Y=C0(W.prompt),V=Z.trim(),A=Y??(V.length>0?V:void 0);if(!A)return i0(H,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=C0(W.workspaceRoot);if(!B)return i0(H,f,J,Z,j,"workspaceRoot is required");let K,G;try{K=_F(W.tools),G=NF(W.extensions)}catch(D){return i0(H,f,J,Z,j,D instanceof Error?D.message:String(D))}let R=OF(W.mode);if(W.mode!==void 0&&R===void 0)return i0(H,f,J,Z,j,"mode must be one of: act, plan, yolo");let F={id:X,title:C0(W.title)??X??TF(f),prompt:A,workspaceRoot:B,mode:R??"yolo",systemPrompt:C0(W.systemPrompt),modelSelection:LF(W.modelSelection),maxIterations:H5(W.maxIterations),timeoutSeconds:H5(W.timeoutSeconds),tools:K,notesDirectory:C0(W.notesDirectory),extensions:G,source:C0(W.source)??"user",tags:UF(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:V5(W.metadata)},P;if(J==="schedule"){let D=C0(W.schedule);if(!D)return i0(H,f,J,Z,j,"schedule is required for *.cron.md specs");let O=C0(W.timezone);try{YW(D,O)}catch(L){return i0(H,f,J,Z,j,L instanceof Error?L.message:String(L))}P={...F,triggerKind:"schedule",schedule:D,timezone:O}}else if(J==="event"){let D=C0(W.event);if(!D)return i0(H,f,J,Z,j,"event is required for .event.md specs");P={...F,triggerKind:"event",event:D,filters:V5(W.filters),debounceSeconds:Y5(W.debounceSeconds),dedupeWindowSeconds:Y5(W.dedupeWindowSeconds),cooldownSeconds:Y5(W.cooldownSeconds),maxParallel:H5(W.maxParallel)}}else P={...F,triggerKind:"one_off"};return{externalId:H,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:P}}function IF($,f){return bF($,f).replace(/\\/g,"/")}function xF($){if(!SF($))return[];let f=[],J=[$];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=CF(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;f.push(j)}}return f}class B5{store;cronDir;constructor($){this.store=$.store,this.cronDir=kF($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=xF(this.cronDir),J=new Set;for(let Z of f){let W=IF(this.cronDir,Z);J.add(W),$.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),Q,Z;try{Q=EF(f,"utf8"),Z=hF(f).mtimeMs}catch{return}let j=PW({relativePath:$,raw:Q}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),Q=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=H1($.scheduleExpr,Q,$.timezone),W=new Date(Z).toISOString();if($.nextRunAt!==W)this.store.updateSpecNextRunAt($.specId,W)}catch{}}}import{existsSync as gF,mkdirSync as mF,watch as vF}from"node:fs";import{relative as cF,resolve as uF}from"node:path";var dF=250;class K5{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??dF),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{mF($,{recursive:!0}),this.watcher=vF($,{recursive:!0},(f,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=uF(this.reconciler.getCronDir(),$);if(!gF(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=cF(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as lf}from"node:crypto";import{asOptionalString as h,asString as r,loadSqliteDb as pF,nowIso as X0}from"@cline/shared/db";import{resolveCronDbPath as rF}from"@cline/shared/storage";var lF=[`CREATE TABLE IF NOT EXISTS cron_specs (
196
+ `))W=W.slice(1);return{frontmatter:Z,body:W}}function b0($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function JU($){if(!Array.isArray($))return;let f=$.map((J)=>typeof J==="string"?J.trim():"").filter((J)=>J.length>0);return f.length>0?f:void 0}function _5($){if(!$||typeof $!=="object"||Array.isArray($))return;return $}function QU($){let f=_5($);if(!f)return;let J=b0(f.providerId),Q=b0(f.modelId);if(J===void 0&&Q===void 0)return;return{providerId:J,modelId:Q}}function ZU($){if(typeof $!=="string")return;let f=$.trim().toLowerCase();if(f==="act"||f==="plan"||f==="yolo")return f;return}function wW($,f={}){let J=Array.isArray($)?$:typeof $==="string"?$.split(","):void 0;if(!J)return;let Q=[...new Set(J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0))];if(Array.isArray($)&&f.preserveEmptyArray)return Q;return Q.length>0?Q:void 0}var WU=new Set(I1);function jU($){let f=wW($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!WU.has(Q));if(J.length>0)throw Error(`unknown tool(s): ${J.join(", ")}`);return f}var XU=new Set(["rules","skills","plugins"]);function HU($){let f=wW($,{preserveEmptyArray:!0});if(!f)return;let J=f.filter((Q)=>!XU.has(Q));if(J.length>0)throw Error(`unknown extension(s): ${J.join(", ")}`);return f}function O5($){if(typeof $!=="number"||!Number.isFinite($)||$<=0)return;return Math.floor($)}function z5($){if(typeof $!=="number"||!Number.isFinite($)||$<0)return;return Math.floor($)}function N5($){if($===null||typeof $!=="object")return JSON.stringify($??null);if(Array.isArray($))return`[${$.map((J)=>N5(J)).join(",")}]`;let f=Object.entries($).filter(([,J])=>J!==void 0);return f.sort(([J],[Q])=>J<Q?-1:J>Q?1:0),`{${f.map(([J,Q])=>`${JSON.stringify(J)}:${N5(Q)}`).join(",")}}`}function SW($,f){let J=oP("sha256");return J.update(N5($)),J.update(`
197
+ `),J.update(f),J.digest("hex")}function YU($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}var VU=["schedule","timezone"],AU=["event","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds","maxParallel"],BU=["cwd"];function yW($,f,J,Q,Z){return{externalId:$,relativePath:$,triggerKind:f,body:J,contentHash:SW(Q,J),error:Z}}function i0($,f,J,Q,Z,W){return{externalId:$,relativePath:f,triggerKind:J,body:Q,contentHash:Z,error:W}}function hW($){let f=$.relativePath.replace(/\\/g,"/"),J=$U(f),{frontmatter:Q,body:Z}=fU($.raw),W={};if(Q!==void 0&&Q.trim().length>0)try{let U=eP.parse(Q);if(U&&typeof U==="object"&&!Array.isArray(U))W=U;else if(U!==null&&U!==void 0)return yW(f,J,Z,{},"frontmatter must be a YAML mapping")}catch(U){return yW(f,J,Z,{},U instanceof Error?`failed to parse frontmatter: ${U.message}`:"failed to parse frontmatter")}let j=SW(W,Z),X=b0(W.id),H=X??f;if(J!=="schedule"){for(let U of VU)if(W[U]!==void 0)return i0(H,f,J,Z,j,`field "${U}" is only allowed on *.cron.md specs`)}for(let U of BU)if(W[U]!==void 0)return i0(H,f,J,Z,j,`field "${U}" is no longer supported; cron specs use workspaceRoot as cwd`);if(J!=="event"){for(let U of AU)if(W[U]!==void 0)return i0(H,f,J,Z,j,`field "${U}" is only allowed on .event.md specs`)}let Y=b0(W.prompt),V=Z.trim(),A=Y??(V.length>0?V:void 0);if(!A)return i0(H,f,J,Z,j,"prompt is required (frontmatter `prompt` or markdown body)");let B=b0(W.workspaceRoot);if(!B)return i0(H,f,J,Z,j,"workspaceRoot is required");let G,K;try{G=jU(W.tools),K=HU(W.extensions)}catch(U){return i0(H,f,J,Z,j,U instanceof Error?U.message:String(U))}let D=ZU(W.mode);if(W.mode!==void 0&&D===void 0)return i0(H,f,J,Z,j,"mode must be one of: act, plan, yolo");let F={id:X,title:b0(W.title)??X??YU(f),prompt:A,workspaceRoot:B,mode:D??"yolo",systemPrompt:b0(W.systemPrompt),modelSelection:QU(W.modelSelection),maxIterations:O5(W.maxIterations),timeoutSeconds:O5(W.timeoutSeconds),tools:G,notesDirectory:b0(W.notesDirectory),extensions:K,source:b0(W.source)??"user",tags:JU(W.tags),enabled:typeof W.enabled==="boolean"?W.enabled:!0,metadata:_5(W.metadata)},P;if(J==="schedule"){let U=b0(W.schedule);if(!U)return i0(H,f,J,Z,j,"schedule is required for *.cron.md specs");let z=b0(W.timezone);try{TW(U,z)}catch(R){return i0(H,f,J,Z,j,R instanceof Error?R.message:String(R))}P={...F,triggerKind:"schedule",schedule:U,timezone:z}}else if(J==="event"){let U=b0(W.event);if(!U)return i0(H,f,J,Z,j,"event is required for .event.md specs");P={...F,triggerKind:"event",event:U,filters:_5(W.filters),debounceSeconds:z5(W.debounceSeconds),dedupeWindowSeconds:z5(W.dedupeWindowSeconds),cooldownSeconds:z5(W.cooldownSeconds),maxParallel:O5(W.maxParallel)}}else P={...F,triggerKind:"one_off"};return{externalId:H,relativePath:f,triggerKind:J,body:Z,contentHash:j,spec:P}}function RU($,f){return UU($,f).replace(/\\/g,"/")}function LU($){if(!GU($))return[];let f=[],J=[$];while(J.length>0){let Q=J.pop();if(!Q)continue;let Z;try{Z=KU(Q,{withFileTypes:!0})}catch{continue}for(let W of Z){let j=`${Q}/${W.name}`;if(W.isDirectory()){if(W.name==="reports")continue;J.push(j);continue}if(!W.isFile())continue;if(!W.name.endsWith(".md"))continue;f.push(j)}}return f}class T5{store;cronDir;constructor($){this.store=$.store,this.cronDir=DU($.specs??($.workspaceRoot?{scope:"workspace",workspaceRoot:$.workspaceRoot}:void 0))}getCronDir(){return this.cronDir}async reconcileAll(){let $={scanned:0,upserted:0,invalidParses:0,removed:0,changes:[]},f=LU(this.cronDir),J=new Set;for(let Z of f){let W=RU(this.cronDir,Z);J.add(W),$.scanned+=1;let j=await this.reconcileFile(W,Z);if(j){if($.changes.push(j),$.upserted+=1,j.parse.error)$.invalidParses+=1}}let Q=this.store.listSpecs({includeRemoved:!1,limit:1e4});for(let Z of Q)if(!J.has(Z.sourcePath))this.handleFileDeleted(Z),$.removed+=1;return this.refreshScheduleNextRunAt(),$}async reconcileFile($,f){let J=this.store.getSpecBySourcePath($),Q,Z;try{Q=FU(f,"utf8"),Z=PU(f).mtimeMs}catch{return}let j=hW({relativePath:$,raw:Q}),X=this.store.upsertSpec({externalId:j.externalId,sourcePath:$,triggerKind:j.triggerKind,sourceMtimeMs:Z,sourceHash:j.contentHash,parseStatus:j.error?"invalid":"valid",parseError:j.error,spec:j.spec});if(!j.error&&j.triggerKind==="schedule"&&X.record.enabled)this.applyScheduleNextRunAt(X.record,{forceReset:!J||J.removed||!J.enabled||J.scheduleExpr!==X.record.scheduleExpr||J.timezone!==X.record.timezone});return{relativePath:$,result:X,parse:j}}handleFileDeleted($){this.store.markSpecRemoved($.specId),this.store.cancelQueuedRunsForSpec($.specId)}refreshScheduleNextRunAt(){let $=this.store.listSpecs({triggerKind:"schedule",enabled:!0,parseStatus:"valid"});for(let f of $)this.applyScheduleNextRunAt(f,{forceReset:!1})}applyScheduleNextRunAt($,f){if(!$.scheduleExpr)return;if(!f.forceReset&&$.nextRunAt)return;try{let J=Date.now(),Q=$.lastRunAt?Math.max(J,new Date($.lastRunAt).getTime()):J,Z=A1($.scheduleExpr,Q,$.timezone),W=new Date(Z).toISOString();if($.nextRunAt!==W)this.store.updateSpecNextRunAt($.specId,W)}catch{}}}import{existsSync as OU,mkdirSync as zU,watch as _U}from"node:fs";import{relative as NU,resolve as TU}from"node:path";var MU=250;class M5{reconciler;debounceMs;onError;onReconciled;watcher;pending=new Map;disposed=!1;constructor($){this.reconciler=$.reconciler,this.debounceMs=Math.max(0,$.debounceMs??MU),this.onError=$.onError??(()=>{}),this.onReconciled=$.onReconciled??(()=>{})}start(){if(this.disposed)throw Error("CronWatcher disposed");if(this.watcher)return;let $=this.reconciler.getCronDir();try{zU($,{recursive:!0}),this.watcher=_U($,{recursive:!0},(f,J)=>{if(!J)return;let Q=String(J).replace(/\\/g,"/");if(!Q.endsWith(".md"))return;if(Q.startsWith("reports/"))return;this.scheduleReconcile(Q)}),this.watcher.on("error",this.onError)}catch(f){this.onError(f)}}stop(){for(let $ of this.pending.values())clearTimeout($);this.pending.clear(),this.watcher?.close(),this.watcher=void 0}dispose(){this.disposed=!0,this.stop()}scheduleReconcile($){let f=this.pending.get($);if(f)clearTimeout(f);let J=setTimeout(()=>{this.pending.delete($),this.reconcileNow($)},this.debounceMs);this.pending.set($,J)}async reconcileNow($){try{let f=TU(this.reconciler.getCronDir(),$);if(!OU(f)){await this.reconciler.reconcileAll(),await this.onReconciled();return}let J=NU(this.reconciler.getCronDir(),f).replace(/\\/g,"/");await this.reconciler.reconcileFile(J,f),await this.onReconciled()}catch(f){this.onError(f)}}}import{randomUUID as n2}from"node:crypto";import{asOptionalString as E,asString as r,loadSqliteDb as yU,nowIso as X0}from"@cline/shared/db";import{resolveCronDbPath as wU}from"@cline/shared/storage";var qU=[`CREATE TABLE IF NOT EXISTS cron_specs (
198
198
  spec_id TEXT PRIMARY KEY,
199
199
  external_id TEXT NOT NULL,
200
200
  source_path TEXT NOT NULL UNIQUE,
@@ -285,17 +285,17 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
285
285
  ON cron_specs(trigger_kind, enabled, next_run_at);`,`CREATE INDEX IF NOT EXISTS cron_specs_event_match_idx
286
286
  ON cron_specs(trigger_kind, event_type, enabled);`,`CREATE INDEX IF NOT EXISTS cron_specs_parse_status_idx
287
287
  ON cron_specs(parse_status, updated_at DESC);`,`CREATE INDEX IF NOT EXISTS cron_specs_source_path_idx
288
- ON cron_specs(source_path);`];function FW($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of lF)$.exec(f)}function l8($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function G5($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function Y1($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function q$($){return{specId:r($.spec_id),externalId:r($.external_id),sourcePath:r($.source_path),triggerKind:r($.trigger_kind),sourceMtimeMs:Y1($.source_mtime_ms),sourceHash:h($.source_hash),parseStatus:r($.parse_status)==="invalid"?"invalid":"valid",parseError:h($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:r($.title),prompt:h($.prompt),workspaceRoot:h($.workspace_root),scheduleExpr:h($.schedule_expr),timezone:h($.timezone),eventType:h($.event_type),filters:l8(h($.filters_json)),debounceSeconds:Y1($.debounce_seconds),dedupeWindowSeconds:Y1($.dedupe_window_seconds),cooldownSeconds:Y1($.cooldown_seconds),mode:h($.mode),systemPrompt:h($.system_prompt),providerId:h($.provider_id),modelId:h($.model_id),maxIterations:Y1($.max_iterations),timeoutSeconds:Y1($.timeout_seconds),maxParallel:Y1($.max_parallel),tools:G5(h($.tools_json),{preserveEmpty:!0}),notesDirectory:h($.notes_directory),extensions:G5(h($.extensions_json),{preserveEmpty:!0}),source:h($.source),tags:G5(h($.tags_json)),metadata:l8(h($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:h($.last_materialized_run_id),lastRunAt:h($.last_run_at),nextRunAt:h($.next_run_at),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function P5($){return{runId:r($.run_id),specId:r($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:r($.trigger_kind),status:r($.status),claimToken:h($.claim_token),claimStartedAt:h($.claim_started_at),claimUntilAt:h($.claim_until_at),scheduledFor:h($.scheduled_for),triggerEventId:h($.trigger_event_id),startedAt:h($.started_at),completedAt:h($.completed_at),sessionId:h($.session_id),reportPath:h($.report_path),error:h($.error),attemptCount:Number($.attempt_count??0),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function DW($){return{eventId:r($.event_id),eventType:r($.event_type),source:r($.source),subject:h($.subject),occurredAt:r($.occurred_at),receivedAt:r($.received_at),workspaceRoot:h($.workspace_root),dedupeKey:h($.dedupe_key),payload:l8(h($.payload_json)),attributes:l8(h($.attributes_json)),processingStatus:r($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:h($.error),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function RW($){return $?JSON.stringify($):null}var iF=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function UW($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function nF($,f,J,Q){for(let Z of iF){let W=$[Z],j=f[Z];if(UW(W)!==UW(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function aF($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function tF($){return`hub/schedules/${$}.cron.md`}function sF($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function F5($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:sF($)}}function LW($){return JSON.stringify(F5($))}function oF($,f){let J=$.metadata?{...$.metadata}:{},Q=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:Q,tags:f.tags??$.tags,runtimeOptions:W,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class pf{db;constructor($={}){let f=$.dbPath??rF();this.db=pF(f),FW(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?q$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?q$(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?q$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>q$(j))}createHubSchedule($){let f=`sched_${lf()}`,J=this.upsertSpec({externalId:f,sourcePath:tF(f),triggerKind:"schedule",sourceHash:LW($),parseStatus:"valid",spec:F5($)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
288
+ ON cron_specs(source_path);`];function CW($){$.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec("PRAGMA foreign_keys = ON;");for(let f of qU)$.exec(f)}function o4($){if(!$)return;try{let f=JSON.parse($);if(f&&typeof f==="object"&&!Array.isArray(f))return f}catch{}return}function q5($,f={}){if(!$)return;try{let J=JSON.parse($);if(!Array.isArray(J))return;let Q=J.map((Z)=>typeof Z==="string"?Z.trim():"").filter((Z)=>Z.length>0);if(f.preserveEmpty)return Q;return Q.length>0?Q:void 0}catch{return}}function B1($){if(typeof $==="number"&&Number.isFinite($))return $;if(typeof $==="bigint")return Number($);return}function w$($){return{specId:r($.spec_id),externalId:r($.external_id),sourcePath:r($.source_path),triggerKind:r($.trigger_kind),sourceMtimeMs:B1($.source_mtime_ms),sourceHash:E($.source_hash),parseStatus:r($.parse_status)==="invalid"?"invalid":"valid",parseError:E($.parse_error),enabled:Number($.enabled??0)===1,removed:Number($.removed??0)===1,title:r($.title),prompt:E($.prompt),workspaceRoot:E($.workspace_root),scheduleExpr:E($.schedule_expr),timezone:E($.timezone),eventType:E($.event_type),filters:o4(E($.filters_json)),debounceSeconds:B1($.debounce_seconds),dedupeWindowSeconds:B1($.dedupe_window_seconds),cooldownSeconds:B1($.cooldown_seconds),mode:E($.mode),systemPrompt:E($.system_prompt),providerId:E($.provider_id),modelId:E($.model_id),maxIterations:B1($.max_iterations),timeoutSeconds:B1($.timeout_seconds),maxParallel:B1($.max_parallel),tools:q5(E($.tools_json),{preserveEmpty:!0}),notesDirectory:E($.notes_directory),extensions:q5(E($.extensions_json),{preserveEmpty:!0}),source:E($.source),tags:q5(E($.tags_json)),metadata:o4(E($.metadata_json)),revision:Number($.revision??1),lastMaterializedRunId:E($.last_materialized_run_id),lastRunAt:E($.last_run_at),nextRunAt:E($.next_run_at),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function y5($){return{runId:r($.run_id),specId:r($.spec_id),specRevision:Number($.spec_revision??1),triggerKind:r($.trigger_kind),status:r($.status),claimToken:E($.claim_token),claimStartedAt:E($.claim_started_at),claimUntilAt:E($.claim_until_at),scheduledFor:E($.scheduled_for),triggerEventId:E($.trigger_event_id),startedAt:E($.started_at),completedAt:E($.completed_at),sessionId:E($.session_id),reportPath:E($.report_path),error:E($.error),attemptCount:Number($.attempt_count??0),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function EW($){return{eventId:r($.event_id),eventType:r($.event_type),source:r($.source),subject:E($.subject),occurredAt:r($.occurred_at),receivedAt:r($.received_at),workspaceRoot:E($.workspace_root),dedupeKey:E($.dedupe_key),payload:o4(E($.payload_json)),attributes:o4(E($.attributes_json)),processingStatus:r($.processing_status),matchedSpecCount:Number($.matched_spec_count??0),queuedRunCount:Number($.queued_run_count??0),suppressedCount:Number($.suppressed_count??0),error:E($.error),createdAt:r($.created_at),updatedAt:r($.updated_at)}}function bW($){return $?JSON.stringify($):null}var SU=["prompt","workspaceRoot","mode","systemPrompt","providerId","modelId","maxIterations","timeoutSeconds","maxParallel","tools","notesDirectory","extensions","source","scheduleExpr","timezone","eventType","filters","debounceSeconds","dedupeWindowSeconds","cooldownSeconds"];function kW($){if($===void 0)return null;if($&&typeof $==="object")return JSON.stringify($);return $}function hU($,f,J,Q){for(let Z of SU){let W=$[Z],j=f[Z];if(kW(W)!==kW(j))return!0}if(J===!1&&Q===!0)return!0;return!1}function CU($){return($.split("/").pop()??$).replace(/\.event\.md$/,"").replace(/\.cron\.md$/,"").replace(/\.md$/,"")}function EU($){return`hub/schedules/${$}.cron.md`}function bU($){let f={...$.metadata??{},...$.createdBy?{__hubScheduleCreatedBy:$.createdBy}:{},...$.cwd?{__hubScheduleCwd:$.cwd}:{},...$.runtimeOptions?{__hubRuntimeOptions:$.runtimeOptions}:{}};return Object.keys(f).length>0?f:void 0}function w5($){return{triggerKind:"schedule",title:$.name.trim(),prompt:$.prompt,workspaceRoot:$.workspaceRoot.trim(),schedule:$.cronPattern.trim(),mode:$.mode??"act",systemPrompt:$.systemPrompt,modelSelection:$.modelSelection?JSON.parse(JSON.stringify($.modelSelection)):void 0,maxIterations:typeof $.maxIterations==="number"?Math.floor($.maxIterations):void 0,timeoutSeconds:typeof $.timeoutSeconds==="number"?Math.floor($.timeoutSeconds):void 0,maxParallel:typeof $.maxParallel==="number"?Math.max(1,Math.floor($.maxParallel)):1,source:"hub-schedule",tags:$.tags?.filter((f)=>f.trim().length>0),enabled:$.enabled!==!1,metadata:bU($)}}function IW($){return JSON.stringify(w5($))}function kU($,f){let J=$.metadata?{...$.metadata}:{},Q=f.createdBy===null?void 0:f.createdBy!==void 0?f.createdBy:typeof J.__hubScheduleCreatedBy==="string"?J.__hubScheduleCreatedBy:void 0,Z=f.cwd!==void 0?f.cwd:typeof J.__hubScheduleCwd==="string"?J.__hubScheduleCwd:void 0,W=f.runtimeOptions!==void 0?f.runtimeOptions:J.__hubRuntimeOptions&&typeof J.__hubRuntimeOptions==="object"&&!Array.isArray(J.__hubRuntimeOptions)?J.__hubRuntimeOptions:void 0;return delete J.__hubScheduleCreatedBy,delete J.__hubScheduleCwd,delete J.__hubRuntimeOptions,{name:f.name??$.title,cronPattern:f.cronPattern??$.scheduleExpr??"",prompt:f.prompt??$.prompt??"",workspaceRoot:f.workspaceRoot??$.workspaceRoot??"",cwd:Z,modelSelection:f.modelSelection!==void 0?f.modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:f.enabled??$.enabled,mode:f.mode??($.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"),systemPrompt:f.systemPrompt===null?void 0:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,maxIterations:f.maxIterations===null?void 0:f.maxIterations!==void 0?f.maxIterations:$.maxIterations,timeoutSeconds:f.timeoutSeconds===null?void 0:f.timeoutSeconds!==void 0?f.timeoutSeconds:$.timeoutSeconds,maxParallel:f.maxParallel??$.maxParallel??1,createdBy:Q,tags:f.tags??$.tags,runtimeOptions:W,metadata:f.metadata!==void 0?f.metadata:Object.keys(J).length>0?J:void 0}}class a2{db;constructor($={}){let f=$.dbPath??wU();this.db=yU(f),CW(this.db)}close(){this.db.close?.()}getSpecBySourcePath($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE source_path = ?").get($);return f?w$(f):void 0}getSpec($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($);return f?w$(f):void 0}getSpecByExternalId($){let f=this.db.prepare("SELECT * FROM cron_specs WHERE external_id = ? ORDER BY created_at ASC LIMIT 1").get($);return f?w$(f):void 0}listSpecs($={}){let f=[],J=[];if($.triggerKind)f.push("trigger_kind = ?"),J.push($.triggerKind);if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.parseStatus)f.push("parse_status = ?"),J.push($.parseStatus);if(!$.includeRemoved)f.push("removed = 0");let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??500));return this.db.prepare(`SELECT * FROM cron_specs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>w$(j))}createHubSchedule($){let f=`sched_${n2()}`,J=this.upsertSpec({externalId:f,sourcePath:EU(f),triggerKind:"schedule",sourceHash:IW($),parseStatus:"valid",spec:w5($)});this.initializeScheduleNextRun(J.record.specId);let Q=this.getSpec(J.record.specId);if(!Q)throw Error("failed to create hub schedule");return Q}getHubSchedule($){let f=this.db.prepare(`SELECT * FROM cron_specs
289
289
  WHERE external_id = ? AND source = 'hub-schedule' AND removed = 0
290
- ORDER BY created_at ASC LIMIT 1`).get($);return f?q$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let W of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
290
+ ORDER BY created_at ASC LIMIT 1`).get($);return f?w$(f):void 0}listHubSchedules($={}){let f=["source = 'hub-schedule'","trigger_kind = 'schedule'","removed = 0"],J=[];if(typeof $.enabled==="boolean")f.push("enabled = ?"),J.push($.enabled?1:0);if($.tags&&$.tags.length>0)for(let W of $.tags)f.push("tags_json LIKE ?"),J.push(`%"${W.trim()}"%`);let Q=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_specs
291
291
  WHERE ${f.join(" AND ")}
292
- ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>q$(W))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let Q=oF(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:LW(Q),parseStatus:"valid",spec:F5(Q)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:X0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
292
+ ORDER BY created_at DESC LIMIT ?`).all(...J,Q).map((W)=>w$(W))}updateHubSchedule($,f){let J=this.getHubSchedule($);if(!J)return;let Q=kU(J,f),Z=this.upsertSpec({externalId:$,sourcePath:J.sourcePath,triggerKind:"schedule",sourceHash:IW(Q),parseStatus:"valid",spec:w5(Q)});if(f.cronPattern!==void 0||f.enabled!==void 0)this.initializeScheduleNextRun(Z.record.specId);return this.getSpec(Z.record.specId)}deleteHubSchedule($){let f=this.getHubSchedule($);if(!f)return!1;return this.markSpecRemoved(f.specId),this.cancelQueuedRunsForSpec(f.specId),!0}enqueueHubScheduleRun($,f="manual"){let J=this.getHubSchedule($);if(!J||!J.enabled||J.removed||J.parseStatus!=="valid")return;return this.enqueueRun({specId:J.specId,specRevision:J.revision,triggerKind:f,scheduledFor:X0()})}listEventSpecsForType($){return this.db.prepare(`SELECT * FROM cron_specs
293
293
  WHERE trigger_kind = 'event'
294
294
  AND event_type = ?
295
295
  AND enabled = 1
296
296
  AND removed = 0
297
297
  AND parse_status = 'valid'
298
- ORDER BY created_at ASC`).all($).map((J)=>q$(J))}upsertSpec($){let f=X0(),J=this.getSpecBySourcePath($.sourcePath),Q=$.spec,Z={title:Q?.title??J?.title??aF($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},W=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let V=`cspec_${lf()}`;this.insertSpecRow(V,$,Z,W,f);let A=this.getSpec(V);if(!A)throw Error("failed to insert cron_spec row");return{record:A,created:!0,revisionChanged:!0}}let X=J.sourceHash!==$.sourceHash&&nF(J,Z,J.enabled,W),H=X?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,W,H,f);let Y=this.getSpec(J.specId);if(!Y)throw Error("failed to reload cron_spec after update");return{record:Y,created:!1,revisionChanged:X}}insertSpecRow($,f,J,Q,Z){let W=f.spec;this.db.prepare(`INSERT INTO cron_specs (
298
+ ORDER BY created_at ASC`).all($).map((J)=>w$(J))}upsertSpec($){let f=X0(),J=this.getSpecBySourcePath($.sourcePath),Q=$.spec,Z={title:Q?.title??J?.title??CU($.sourcePath),prompt:Q?.prompt,workspaceRoot:Q?.workspaceRoot,scheduleExpr:Q?.triggerKind==="schedule"?Q.schedule:void 0,timezone:Q?.triggerKind==="schedule"?Q.timezone:void 0,eventType:Q?.triggerKind==="event"?Q.event:void 0,filters:Q?.triggerKind==="event"?Q.filters:void 0,debounceSeconds:Q?.triggerKind==="event"?Q.debounceSeconds:void 0,dedupeWindowSeconds:Q?.triggerKind==="event"?Q.dedupeWindowSeconds:void 0,cooldownSeconds:Q?.triggerKind==="event"?Q.cooldownSeconds:void 0,mode:Q?.mode,systemPrompt:Q?.systemPrompt,providerId:Q?.modelSelection?.providerId,modelId:Q?.modelSelection?.modelId,maxIterations:Q?.maxIterations,timeoutSeconds:Q?.timeoutSeconds,maxParallel:Q&&"maxParallel"in Q?Q.maxParallel:void 0,tools:Q?.tools,notesDirectory:Q?.notesDirectory,extensions:Q?.extensions,source:Q?.source},W=$.parseStatus==="valid"&&(Q?.enabled??!0);if(!J){let V=`cspec_${n2()}`;this.insertSpecRow(V,$,Z,W,f);let A=this.getSpec(V);if(!A)throw Error("failed to insert cron_spec row");return{record:A,created:!0,revisionChanged:!0}}let X=J.sourceHash!==$.sourceHash&&hU(J,Z,J.enabled,W),H=X?J.revision+1:J.revision;this.updateSpecRow(J.specId,$,Z,W,H,f);let Y=this.getSpec(J.specId);if(!Y)throw Error("failed to reload cron_spec after update");return{record:Y,created:!1,revisionChanged:X}}insertSpecRow($,f,J,Q,Z){let W=f.spec;this.db.prepare(`INSERT INTO cron_specs (
299
299
  spec_id, external_id, source_path, trigger_kind,
300
300
  source_mtime_ms, source_hash, parse_status, parse_error,
301
301
  enabled, removed, title, prompt, workspace_root,
@@ -318,7 +318,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
318
318
  tools_json = ?, notes_directory = ?, extensions_json = ?, source = ?,
319
319
  tags_json = ?, metadata_json = ?,
320
320
  revision = ?, updated_at = ?
321
- WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,W,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(X0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,X0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,X0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,X0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(H1(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=q$(Q);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let W=Z.nextRunAt;if(!W){let H=new Date(H1(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(H,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:H}}if(new Date(W).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${lf()}`,X;try{X=new Date(H1(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{X=void 0}return this.db.prepare(`INSERT INTO cron_runs (
321
+ WHERE spec_id = ?`).run(f.externalId,f.triggerKind,f.sourceMtimeMs??null,f.sourceHash,f.parseStatus,f.parseError??null,Q?1:0,J.title??"",J.prompt??null,J.workspaceRoot??null,J.scheduleExpr??null,J.timezone??null,J.eventType??null,J.filters?JSON.stringify(J.filters):null,J.debounceSeconds??null,J.dedupeWindowSeconds??null,J.cooldownSeconds??null,J.mode??null,J.systemPrompt??null,J.providerId??null,J.modelId??null,J.maxIterations??null,J.timeoutSeconds??null,J.maxParallel??null,J.tools?JSON.stringify(J.tools):null,J.notesDirectory??null,J.extensions?JSON.stringify(J.extensions):null,J.source??null,j?.tags?JSON.stringify(j.tags):null,j?.metadata?JSON.stringify(j.metadata):null,Z,W,$)}markSpecRemoved($){this.db.prepare("UPDATE cron_specs SET removed = 1, enabled = 0, updated_at = ? WHERE spec_id = ?").run(X0(),$)}updateSpecNextRunAt($,f){this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f??null,X0(),$)}updateSpecLastRunAt($,f){this.db.prepare("UPDATE cron_specs SET last_run_at = ?, updated_at = ? WHERE spec_id = ?").run(f,X0(),$)}updateLastMaterializedRunId($,f){this.db.prepare("UPDATE cron_specs SET last_materialized_run_id = ?, updated_at = ? WHERE spec_id = ?").run(f,X0(),$)}initializeScheduleNextRun($){let f=this.getSpec($);if(!f||f.triggerKind!=="schedule"||!f.enabled||!f.scheduleExpr){this.updateSpecNextRunAt($,void 0);return}let J=new Date(A1(f.scheduleExpr,Date.now(),f.timezone)).toISOString();this.updateSpecNextRunAt($,J)}materializeDueScheduleRun($){let f=$.nowMs,J=new Date(f).toISOString();this.db.exec("BEGIN IMMEDIATE;");try{let Q=this.db.prepare("SELECT * FROM cron_specs WHERE spec_id = ?").get($.specId);if(!Q)return this.db.exec("COMMIT;"),{queued:!1};let Z=w$(Q);if(Z.triggerKind!=="schedule"||!Z.enabled||Z.removed||Z.parseStatus!=="valid"||!Z.scheduleExpr)return this.db.exec("COMMIT;"),{queued:!1};let W=Z.nextRunAt;if(!W){let H=new Date(A1(Z.scheduleExpr,f,Z.timezone)).toISOString();return this.db.prepare("UPDATE cron_specs SET next_run_at = ?, updated_at = ? WHERE spec_id = ?").run(H,J,Z.specId),this.db.exec("COMMIT;"),{queued:!1,nextRunAt:H}}if(new Date(W).getTime()>f)return this.db.exec("COMMIT;"),{queued:!1,nextRunAt:W};let j=`crun_${n2()}`,X;try{X=new Date(A1(Z.scheduleExpr,f,Z.timezone)).toISOString()}catch{X=void 0}return this.db.prepare(`INSERT INTO cron_runs (
322
322
  run_id, spec_id, spec_revision, trigger_kind, status,
323
323
  scheduled_for, trigger_event_id, attempt_count,
324
324
  created_at, updated_at
@@ -327,22 +327,22 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
327
327
  last_run_at = ?,
328
328
  next_run_at = ?,
329
329
  updated_at = ?
330
- WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?P5(f):void 0}insertEventLog($,f={}){let J=X0(),Q=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=$.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||Q,H=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
330
+ WHERE spec_id = ?`).run(j,J,X??null,J,Z.specId),this.db.exec("COMMIT;"),{queued:!0,run:this.getRun(j),nextRunAt:X}}catch(Q){throw this.db.exec("ROLLBACK;"),Q}}getRun($){let f=this.db.prepare("SELECT * FROM cron_runs WHERE run_id = ?").get($);return f?y5(f):void 0}insertEventLog($,f={}){let J=X0(),Q=f.receivedAtIso??J,Z=$.eventId.trim();if(!Z)throw Error("automation event requires eventId");let W=$.eventType.trim();if(!W)throw Error("automation event requires eventType");let j=$.source.trim();if(!j)throw Error("automation event requires source");let X=$.occurredAt.trim()||Q,H=this.db.prepare(`INSERT OR IGNORE INTO cron_event_log (
331
331
  event_id, event_type, source, subject,
332
332
  occurred_at, received_at, workspace_root, dedupe_key,
333
333
  payload_json, attributes_json, processing_status,
334
334
  matched_spec_count, queued_run_count, suppressed_count,
335
335
  error, created_at, updated_at
336
- ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,$.subject?.trim()||null,X,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,RW($.payload),RW($.attributes),"received",0,0,0,null,J,J).changes??0,Y=this.getEventLog(Z);if(!Y)throw Error("failed to insert cron_event_log row");return{record:Y,created:H===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?DW(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
336
+ ) VALUES (?,?,?,?, ?,?,?,?, ?,?,?, ?,?,?, ?,?,?)`).run(Z,W,j,$.subject?.trim()||null,X,Q,$.workspaceRoot?.trim()||null,$.dedupeKey?.trim()||null,bW($.payload),bW($.attributes),"received",0,0,0,null,J,J).changes??0,Y=this.getEventLog(Z);if(!Y)throw Error("failed to insert cron_event_log row");return{record:Y,created:H===1}}getEventLog($){let f=this.db.prepare("SELECT * FROM cron_event_log WHERE event_id = ?").get($);return f?EW(f):void 0}listEventLogs($={}){let f=[],J=[];if($.eventType)f.push("event_type = ?"),J.push($.eventType);if($.source)f.push("source = ?"),J.push($.source);if($.processingStatus)f.push("processing_status = ?"),J.push($.processingStatus);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_event_log ${Q}
337
337
  ORDER BY received_at DESC, created_at DESC
338
- LIMIT ?`).all(...J,Z).map((j)=>DW(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
338
+ LIMIT ?`).all(...J,Z).map((j)=>EW(j))}updateEventLogProcessing($,f){return(this.db.prepare(`UPDATE cron_event_log SET
339
339
  processing_status = ?,
340
340
  matched_spec_count = COALESCE(?, matched_spec_count),
341
341
  queued_run_count = COALESCE(?, queued_run_count),
342
342
  suppressed_count = COALESCE(?, suppressed_count),
343
343
  error = ?,
344
344
  updated_at = ?
345
- WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,X0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let H of j)J.push(H)}}let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>P5(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
345
+ WHERE event_id = ?`).run(f.status,f.matchedSpecCount??null,f.queuedRunCount??null,f.suppressedCount??null,f.error??null,X0(),$).changes??0)===1}listRuns($={}){let f=[],J=[];if($.specId)f.push("spec_id = ?"),J.push($.specId);if($.status){let j=Array.isArray($.status)?$.status:[$.status];if(j.length>0){let X=j.map(()=>"?").join(",");f.push(`status IN (${X})`);for(let H of j)J.push(H)}}let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"",Z=Math.max(1,Math.floor($.limit??200));return this.db.prepare(`SELECT * FROM cron_runs ${Q} ORDER BY created_at DESC LIMIT ?`).all(...J,Z).map((j)=>y5(j))}hasRecentEventRunForDedupe($){return!!this.db.prepare(`SELECT r.run_id FROM cron_runs r
346
346
  INNER JOIN cron_event_log e ON e.event_id = r.trigger_event_id
347
347
  WHERE r.spec_id = ?
348
348
  AND r.trigger_kind = 'event'
@@ -360,7 +360,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
360
360
  AND r.status = 'queued'
361
361
  AND e.dedupe_key = ?
362
362
  ORDER BY COALESCE(r.scheduled_for, r.created_at) DESC
363
- LIMIT 1`).get($.specId,$.dedupeKey);return f?P5(f):void 0}updateQueuedEventRunForDebounce($){let f=X0();if((this.db.prepare(`UPDATE cron_runs SET
363
+ LIMIT 1`).get($.specId,$.dedupeKey);return f?y5(f):void 0}updateQueuedEventRunForDebounce($){let f=X0();if((this.db.prepare(`UPDATE cron_runs SET
364
364
  trigger_event_id = ?,
365
365
  scheduled_for = ?,
366
366
  updated_at = ?
@@ -369,7 +369,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
369
369
  AND status = 'queued'`).run($.triggerEventId,$.scheduledFor,f,$.runId).changes??0)!==1)return;return this.getRun($.runId)}hasOneOffRunForRevision($,f){return!!this.db.prepare(`SELECT run_id FROM cron_runs
370
370
  WHERE spec_id = ? AND spec_revision = ?
371
371
  AND trigger_kind = 'one_off'
372
- LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${lf()}`,J=X0();this.db.prepare(`INSERT INTO cron_runs (
372
+ LIMIT 1`).get($,f)}enqueueRun($){let f=`crun_${n2()}`,J=X0();this.db.prepare(`INSERT INTO cron_runs (
373
373
  run_id, spec_id, spec_revision, trigger_kind, status,
374
374
  scheduled_for, trigger_event_id, attempt_count,
375
375
  created_at, updated_at
@@ -386,7 +386,7 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
386
386
  )
387
387
  AND (scheduled_for IS NULL OR scheduled_for <= ?)
388
388
  ORDER BY COALESCE(scheduled_for, created_at) ASC
389
- LIMIT ?`).all(f,f,Z);for(let X of j){let H=r(X.run_id);if(!H)continue;let Y=`cclaim_${lf()}`;if((this.db.prepare(`UPDATE cron_runs SET
389
+ LIMIT ?`).all(f,f,Z);for(let X of j){let H=r(X.run_id);if(!H)continue;let Y=`cclaim_${n2()}`;if((this.db.prepare(`UPDATE cron_runs SET
390
390
  status = 'running',
391
391
  claim_token = ?,
392
392
  claim_started_at = ?,
@@ -430,41 +430,41 @@ ${JSON.stringify(Q,null,2)}`}startClaimLeaseHeartbeat($){let f=Math.max(1000,Mat
430
430
  error = ?,
431
431
  scheduled_for = COALESCE(?, scheduled_for),
432
432
  updated_at = ?
433
- WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,X0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,X0(),$)}}class rf{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new pf({dbPath:$.dbPath});let f=$.specs;this.reconciler=new B5({store:this.store,specs:f}),this.materializer=new vf({store:this.store}),this.eventIngress=new eJ({store:this.store,logger:$.logger}),this.runner=new cf({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new K5({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as VD,readFile as SW}from"node:fs/promises";import{join as CW}from"node:path";import{formatDisplayUserInput as AD,normalizeUserInput as BD}from"@cline/shared";import{resolveSessionDataDir as EW}from"@cline/shared/storage";import{mkdirSync as fD,writeFileSync as JD}from"node:fs";import{dirname as QD}from"node:path";import{normalizeUserInput as ZD}from"@cline/shared";import{nanoid as WD}from"nanoid";import{nanoid as eF}from"nanoid";function nf($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function p8($,f){let J=nf($),Q=nf(f),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function D5($,f){let J=nf($),Q=nf(f);return`${J}__teamtask__${Q}__${eF(6)}`}function af($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),X=Z.slice(W+2);if(!Q||!j||!X)return null;return{rootSessionId:Q,agentId:j,teamTaskId:X}}function r8($){if(af($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+f.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function R5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var $D=i.enum(v6),O0=i.object({version:i.literal(1),session_id:i.string().min(1),source:i.string().min(1),pid:i.number().int(),started_at:i.string().min(1),ended_at:i.string().min(1).optional(),exit_code:i.number().int().nullable().optional(),status:$D,interactive:i.boolean(),provider:i.string().min(1),model:i.string().min(1),cwd:i.string().min(1),workspace_root:i.string().min(1),team_name:i.string().min(1).optional(),enable_tools:i.boolean(),enable_spawn:i.boolean(),enable_teams:i.boolean(),prompt:i.string().optional(),metadata:i.record(i.string(),i.unknown()).optional(),messages_path:i.string().min(1).optional()});function OW($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function L5($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function zW($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function W$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function U5($,f){let J={...$};J.id=W$(J.id)??WD();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:W$(Q?.id)??W$(J.modelId)??W$(f?.id),provider:W$(Q?.provider)??W$(J.providerId)??W$(f?.provider),family:W$(Q?.family)??W$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function i8($){return $.map((f)=>U5(f))}function n8($,f,J=[]){let Q=$.map((H,Y)=>{let V=J[Y],B=V?.role===H.role&&JSON.stringify(V.content)===JSON.stringify(H.content)?{...V,...H}:{...H};return U5(B)}),Z=J.length,W=[];for(let H=Z;H<Q.length;H+=1)if(Q[H]?.role==="assistant")W.push(H);if(W.length===0){let H=[...Q].reverse().findIndex((Y)=>Y.role==="assistant");if(H===-1)return Q;W.push(Q.length-1-H)}let j=W[W.length-1],X=W.some((H)=>Q[H]?.metrics);for(let H of W){let Y=Q[H],V=Y.metrics;if(!V&&H===j&&!X){let A=f.usage;V={inputTokens:A.inputTokens,outputTokens:A.outputTokens,cacheReadTokens:A.cacheReadTokens??0,cacheWriteTokens:A.cacheWriteTokens??0,cost:A.totalCost}}Q[H]={...U5(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...V?{metrics:V}:{},ts:Y.ts??f.endedAt.getTime()}}return Q}function tf($){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 jD=120;function V1($){let f=$?.trim();return f?f.slice(0,jD):void 0}function O5($){let f=ZD($??"").trim();if(!f)return;return V1(f.split(`
434
- `)[0]?.trim())}function w$($){if(!$)return;let f={...$},J=V1(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function sf($){let f=w$($.metadata)??{},J=$.title!==void 0?V1($.title):O5($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function z5($){let f=af($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=r8($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function _5($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:i8($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function _W($,f,J){fD(QD($),{recursive:!0}),JD($,`${JSON.stringify(_5({updatedAt:f,context:J,messages:[]}),null,2)}
435
- `,"utf8")}function yW($,f){return O0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function NW($,f,J){let Q=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let W=await f(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}import{existsSync as XD}from"node:fs";import{readFile as HD}from"node:fs/promises";import{formatDisplayUserInput as TW}from"@cline/shared";class of{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function S$($){let f=$?.trim();if(!f||!XD(f))return[];try{let J=(await HD(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return MW(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return MW(Z)}return[]}catch{return[]}}function YD($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:TW($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:TW(f.text)}})}}function MW($){return $.map(YD)}function y5($){return $?{...$}:void 0}async function qW($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function ef($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function E0($){let f=ef($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function a8($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function KD($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function T5($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function GD($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function PD($){return $.isSubagent!==!0&&!ef($.parentSessionId)}function FD($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function M5($){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 DD($){let f=T5($);if(f===0)return[];let J=EW(),Z=(await VD(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:FD(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=CW(J,X,`${X}.json`),Y=await SW(H,"utf8").catch(()=>{return});if(!Y)return;let V;try{V=JSON.parse(Y)}catch{return}let A=O0.safeParse(V);if(!A.success)return;return M5(A.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function RD($,f,J){let Q=T5(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:GD(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter(PD)).slice(0,Q)}function UD($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
436
- `).trim()}function wW($){return $.replace(/\s+/g," ").trim()}function LD($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function OD($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let Q=wW(UD(J.content));if(!Q)continue;let Z=f==="user"?wW(AD(Q)):Q,W=BD(Z.split(`
437
- `)[0]??Z);return LD(W,50)}return}function zD($){let f=0;for(let J of $)f+=a8(J.metrics?.cost)??0;return f}function _D($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=E0(Z.modelInfo?.provider);if(!J)J=E0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function yD($){return E0($?.provider)??E0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function ND($){return E0($?.model)??E0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function N5($,f){let J=KD($.metadata),Q=ef(f?.title)??ef(J?.title),Z=a8(f?.totalCost)??a8(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:E0(f?.provider)??E0($.provider)??yD(J)??"",model:E0(f?.model)??E0($.model)??ND(J)??"",metadata:W}}async function TD($,f){return await Promise.all(f.map(async(J)=>{let Q=N5(J),Z=Boolean(ef(Q.metadata?.title)),W=Boolean(E0(Q.provider)),j=Boolean(E0(Q.model)),X=a8(Q.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&W&&j&&H)return Q;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return Q;let V=_D(Y),A=zD(Y);return N5(J,{title:Z?void 0:OD(Y),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:H||A<=0?void 0:A})}))}async function q5($,f={}){let J=T5(f.limit),Q=f.includeSubagents===!0,Z=await RD($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await DD(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let H of[...Z,...W]){if(j.has(H.sessionId))continue;j.set(H.sessionId,H)}let X=W.length===0?Z:Array.from(j.values()).sort((H,Y)=>Y.startedAt.localeCompare(H.startedAt)).slice(0,J);if(f.hydrate===!1)return X.map((H)=>N5(H));return await TD($,X)}async function MD($){let f=$.trim();if(!f)return;let J=CW(EW(),f,`${f}.json`),Q=await SW(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=O0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function qD($,f={}){let J=new Map;return await q5({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(tf)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await MD(Z);return await S$(W)}},f)}import{captureSdkError as eX}from"@cline/shared";import{createSessionId as NR,resolveHubCommandTimeoutMs as TR}from"@cline/shared";import{spawn as JR}from"node:child_process";import{closeSync as QR,mkdirSync as ZR,openSync as WR}from"node:fs";import{basename as jR,dirname as XR,join as HR}from"node:path";import{fileURLToPath as YR}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as VR,isHubDaemonProcess as pW,withResolvedClineBuildEnv as AR}from"@cline/shared";import{createHash as wD,randomBytes as SD}from"node:crypto";import{existsSync as CD}from"node:fs";import{chmod as ED,mkdir as w5,readFile as gW,rm as S5,writeFile as mW}from"node:fs/promises";import{dirname as vW,join as C5}from"node:path";import{resolveClineDataDir as E5,resolveClineDir as pE}from"@cline/shared/storage";var bW="0.0.41";var kW={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:bW,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^1.21.7","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"^3.32.3",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var hD="CLINE_HUB_DISCOVERY_PATH",bD="CLINE_HUB_BUILD_ID",IW=30000,kD=15000,ID=100;function xD($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function gD($){return wD("sha256").update($).digest("hex").slice(0,12)}function mD($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function cW(){return SD(32).toString("hex")}function vD($){return new Promise((f)=>setTimeout(f,$))}function cD($){return`${$}.lock`}async function uD($){try{let f=JSON.parse(await gW(C5($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function xW($){await S5($,{recursive:!0,force:!0}).catch(()=>{return})}function i1(){return process.env[bD]?.trim()||String(kW.version)}function A1($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${gD($)}`,J=process.env[hD]?.trim()||C5(E5(),"locks","hub","owners",`${xD(f)}.json`);return{ownerId:f,discoveryPath:J}}function iE($=`hub-${Date.now().toString(36)}`){return A1($)}async function B0($){try{let f=JSON.parse(await gW($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function uW($,f){await w5(vW($),{recursive:!0}),await S5($,{force:!0}).catch(()=>{return}),await mW($,`${JSON.stringify(f,null,2)}
438
- `,{encoding:"utf8",mode:384}),await ED($,384)}async function n0($){await S5($,{force:!0}).catch(()=>{return})}async function dW($,f){let J=cD($);await w5(vW(J),{recursive:!0});let Q=Date.now()+kD;while(!0)try{await w5(J,{recursive:!1}),await mW(C5(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
439
- `,"utf8");try{return await f()}finally{await xW(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await uD(J),X=j?Date.now()-Date.parse(j.acquiredAt):IW+1;if(!j||!mD(j.pid)||X>IW){await xW(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await vD(ID)}}async function F0($){try{let f=await fetch(dD($));if(!f.ok)return;return await f.json()}catch{return}}function j$($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function dD($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function nE($){return CD($)}import{CLINE_HUB_DEV_PORT as lD,CLINE_HUB_PORT as pD,resolveClineBuildEnv as rD}from"@cline/shared";var iD="CLINE_HUB_HOST",nD="CLINE_HUB_PORT",aD="CLINE_HUB_PATHNAME",tD="127.0.0.1",sD=pD,oD="/hub";function lW($){return rD($)==="development"?lD:sD}function eD($={}){return($.env??process.env)[iD]?.trim()||tD}function t8($={}){let J=($.env??process.env)[nD]?.trim();if(!J)return lW($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return lW($);return Q}function $R($={}){return($.env??process.env)[aD]?.trim()||oD}function C$($={},f={}){return{host:$.host??eD(f),port:$.port??t8(f),pathname:$.pathname??$R(f)}}var fR="shared:cline";function $h($){let f=j1($.trim());return A1(`workspace:${f||$.trim()}`)}function D0($=fR){return A1($)}var BR=8000,KR=200,GR=3000,PR=100,FR=[100,250,500,1000,2000],DR="--cline-hub-daemon";function RR($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function UR(){try{let $=HR(E5(),"logs","hub-daemon.log");return ZR(XR($),{recursive:!0}),{fd:WR($,"a"),logPath:$}}catch{return}}function $2($){let f=$.buildId?.trim();return!!f&&f===i1()}async function LR($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await F0($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,PR))}return!1}async function f2($,f){if($2($))return;if(await h5($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await LR($.url,GR),await n0(f).catch(()=>{return})}function OR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return YR(new URL(`./entry.${$}`,import.meta.url))}function zR($,f){let J=OR(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=jR(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[DR]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,...RR(f)],cwd:$,env:{...AR(process.env),CLINE_NO_INTERACTIVE:"1",[VR]:"1"}}}function _R($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function yR($,f={}){if(pW())return;let J=zR($,f),Q=UR();try{JR(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)QR(Q.fd)}}async function s8($,f={}){for(let J=0;;J++)try{yR($,f);return}catch(Q){let Z=FR[J];if(!_R(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function rW($,f={}){if(pW())return;let J=D0(),Q=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=C$(f),W=j$(Z.host,Z.port,Z.pathname);B0(J.discoveryPath).then(async(j)=>{if(j?.url){let V=await F0(j.url);if(V?.url&&$2(V)&&await E$(V.url,{authToken:j.authToken}))return;if(V?.url)await f2({...V,authToken:j.authToken},J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}let X=await F0(W);if(X?.url)await f2(X,J.discoveryPath);let Y=!Q&&Z.port!==0?{...Z,port:0}:Z;await s8($,Y)}).catch(()=>{})}async function Ah($,f={}){let J=D0(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=C$(f),j=j$(W.host,W.port,W.pathname),X=(K)=>{if(!Q)n1(K.url,K.authToken);return K},H=await B0(J.discoveryPath);if(H?.url){let K=await F0(H.url);if(K?.url&&$2(K)&&await E$(K.url,{authToken:H.authToken}))return X({url:K.url,authToken:H.authToken});if(K?.url)await f2({...K,authToken:H.authToken},J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}let Y=await F0(j);if(Y?.url)await f2(Y,J.discoveryPath);let A=!Z&&W.port!==0?{...W,port:0}:W;await s8($,A);let B=Date.now()+BR;while(Date.now()<B){let K=await B0(J.discoveryPath);if(K?.url){let R=await F0(K.url);if(R?.url&&$2(R)&&await E$(R.url,{authToken:K.authToken}))return X({url:R.url,authToken:K.authToken})}let G=await F0(j);if(G?.url&&!$2(G))await f2(G,J.discoveryPath);await new Promise((R)=>setTimeout(R,KR))}throw Error("Timed out waiting for detached hub startup.")}function MR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function sW($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return sW($.data);return String($)}function qR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function iW($){let f=$,J=qR(f.reason);return new h0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:b5,{closeCode:f.code,closeReason:J||void 0})}function wR($,f){if($ instanceof h0)return $;if($ instanceof Error)return new h0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new h0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new h0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new h0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var SR=8000,CR=200,nW="*",aW=8000,ER="cline-hub-auth.",oW=new Map,eW=new Set,hR=3000,bR=3000,kR=100,b5="Hub connection closed",IR=250,xR=5000,tW=0.5;class h0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function gR($){return $ instanceof h0}class o8 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function $j($,f){return $ instanceof o8&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function fj($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=x5($.toString());return J?oW.get(J):void 0}function mR($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function x5($){if(!mR($))return;let f=new URL(a1($));return f.search="",f.hash="",f.toString()}function k5($){let f=x5($);return!!f&&eW.has(f)}function n1($,f){let J=x5($);if(J){if(eW.add(J),f?.trim())oW.set(J,f)}return $}class X${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new h0("hub_connection_closed",b5);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||fj($);$.hash="";let Q=new(MR())($.toString(),f?[`${ER}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new h0("hub_connect_timeout",`Timed out connecting to hub after ${aW}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},aW);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),W()}),Q.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=wR(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=iW(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(sW(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=iW(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=NR("hubreq_"),W=TR($,Q?.timeoutMs),j=new Promise((H,Y)=>{let V=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new o8($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(A)=>{if(V)clearTimeout(V);H(A)},reject:(A)=>{if(V)clearTimeout(V);Y(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok)throw new o8($,X.error?.code,X.error?.message??`Hub command ${$} failed`);return X}async recoverLocalHubTransport($){if(!k5(this.currentUrl)||!gR($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await J2({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(IR*2**this.reconnectAttempt,xR),f=Math.round($*(1-tW)+Math.random()*$*tW);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!k5(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await J2({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 h0("hub_connection_closed",b5),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new h0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??nW}subscriptionSessionIdFromKey($){return $===nW?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function a1($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function E$($,f){let J=new X$({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function I5($,f){let J=a1($),Q=await F0(J);if(!Q)return{status:"unreachable",url:J};let Z=i1(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await E$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function vR($){let f=Date.now()+SR;while(Date.now()<f){let J=await B0($.discoveryPath);if(J?.url){let Q=await I5(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return n1(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,CR))}return}async function cR($){let f=Date.now()+bR;while(Date.now()<f){if(!(await F0($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,kR))}return!1}function uR($,f){try{return a1($)===a1(f)}catch{return!1}}function dR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function lR($,f,J){let Q=new X$({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:hR});return!dR(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function g5($={}){if($.endpoint?.trim()){let Z=await I5($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=D0(),J=await B0(f.discoveryPath);if(!J?.url)return;let Q=await I5(J.url);if(Q.status==="compatible")return n1(Q.url,J.authToken);if(Q.status==="build_mismatch")await n0(f.discoveryPath).catch(()=>{return});return}async function J2($={}){let f=await g5($);if(f&&await E$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=D0();return await s8($.workspaceRoot??process.cwd()),await vR(J)}async function h5($,f){let J=new URL($),Q=f?.trim()||fj(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function pR(){let $=D0(),f=await B0($.discoveryPath);if(!f?.url)return!1;try{if(await h5(f.url,f.authToken))return!0}catch{}return!1}async function Jj($){if(!k5($.url))return;let f=D0(),J=await B0(f.discoveryPath);if(!J?.url||!uR(J.url,$.url))return;if(!await lR(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await pR())return;if(!await cR(J.url))return;return await n0(f.discoveryPath).catch(()=>{return}),await J2({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as aR,createSessionId as Qj,HUB_CHECKPOINT_CAPABILITY as tR,HUB_COMPACTION_CAPABILITY as sR,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as oR,HUB_HOOK_CAPABILITY_PREFIX as eR,HUB_MISTAKE_LIMIT_CAPABILITY as $U,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as fU,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as JU,isHubToolExecutorName as QU}from"@cline/shared";function rR($){return $?JSON.parse(JSON.stringify($)):void 0}function iR($){return $?JSON.parse(JSON.stringify($)):void 0}function nR($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function h$($){let{session:f}=$,J=rR(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:iR($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=nR(J);return Q?{checkpoint:Q}:{}})()}}function m5($){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 t1($){if(!$)return;return JSON.parse(JSON.stringify($))}var ZU=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Zj($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function Wj($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function jj($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function B1($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function Xj($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(QU)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;B1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${fU}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={...jj(j.context),signal:X};return{result:await W(...H,Y)}})}for(let Z of $?.extraTools??[])B1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:t1(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:t1(Z.lifecycle)}:{},capabilityName:`${oR}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let H={...jj(W.context),signal:j};return{result:await Z.execute(W.input,{...H,emitUpdate:(V)=>{X({update:V})}})}});let Q=$?.hooks;if(Q)for(let Z of ZU){let W=Q[Z];if(typeof W!=="function")continue;B1(J,{kind:"hook",name:Z,capabilityName:`${eR}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;B1(J,{kind:"compaction",capabilityName:sR,config:Zj($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;B1(J,{kind:"checkpoint",capabilityName:tR,config:Zj($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;B1(J,{kind:"mistakeLimit",capabilityName:$U},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;B1(J,{kind:"userInstructionService",capabilityName:JU},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function WU($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return"Capability request was cancelled."}function jU($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function XU($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function HU($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function Hj($){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 v5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function b$($,f){return v5($?.[f])??0}function YU($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:b$(f,"inputTokens"),outputTokens:b$(f,"outputTokens"),cacheReadTokens:b$(f,"cacheReadTokens"),cacheWriteTokens:b$(f,"cacheWriteTokens"),cost:v5(f?.totalCost),totalInputTokens:b$(J,"inputTokens"),totalOutputTokens:b$(J,"outputTokens"),totalCacheReadTokens:b$(J,"cacheReadTokens"),totalCacheWriteTokens:b$(J,"cacheWriteTokens"),totalCost:v5(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function VU($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=XU(J)?J:J==="failed"?"error":"completed",Z=HU($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function e8($,f){return $.error?.message??`hub command failed: ${f}`}function Q2($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function Aj($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:G0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:Q2($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:Q2($.status)==="completed"?0:Q2($.status)==="failed"?1:void 0,status:Q2($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function K1($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function AU($){let f=K1($?.snapshot);if(f)return m5(f);let J=$?.session;return J?Aj(J):void 0}function Yj($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return O0.parse({version:1,session_id:$,source:f.source??G0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:Q2(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function Vj($,f){return O0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class G1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new of;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=P0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new X$({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!$j($,"session.create"))return!1;let f=await Jj({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=Xj($.localRuntime,f),Q=$.config.sessionId?.trim()||Qj(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:t1({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??G0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:t1($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(Y){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(V){throw this.cleanupPlannedSession(Q),V}}else throw Y}let j=K1(W.payload?.snapshot),X=W.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(H!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?Vj(j,$):Yj(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?Xj(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||Qj():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:t1({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??G0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:t1(Q.toolPolicies)}:{}},f)}catch(K){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw K}if(!X.ok){let K=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(K)}let H=K1(X.payload?.snapshot),Y=X.payload?.session,V=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!V){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(V&&j&&V!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(V&&Z)this.sessionCapabilities.set(V,Z);if(V&&W.handlers.size>0)this.sessionClientContributionHandlers.set(V,W.handlers);if(V)this.ensureSessionSubscription(V);let A=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:H?Vj(H,Q??{}):Yj(V,Q??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:A,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=K1(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=Hj(Q?.usage),W=Hj(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:typeof f==="string"?f:void 0},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f=await this.client.command("session.get",void 0,$);return AU(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=K1(Z);return W?[m5(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(Aj)}async listSettings($){let f=await this.client.command("settings.list",Wj($));if(!f.ok)throw Error(e8(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",Wj($));if(!f.ok)throw Error(e8(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw aR(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(e8(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(e8(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return P0(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:VU($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($);return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($);return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=K1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=YU($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=K1($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:J}}),this.events.emit({type:"ended",payload:{sessionId:f,reason:J,ts:$.timestamp??Date.now()}});return}default:return}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:Q,payload:Y},f)};try{let Y=await W({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(WU($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=jU($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:H.approved,reason:H.reason},f).catch(()=>{})}}class $4 extends G1{constructor($){super({url:a1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as BU,mkdirSync as KU}from"node:fs";import{join as GU}from"node:path";import{asBool as Z2,asOptionalString as a0,asString as H$,ensureSessionSchema as PU,loadSqliteDb as FU,nowIso as f4,toBoolInt as W2}from"@cline/shared/db";import{resolveDbDataDir as DU}from"@cline/shared/storage";class k${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??DU()}init(){this.getRawDb()}ensureSessionsDir(){if(!BU(this.sessionsDirPath))KU(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return GU(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=FU(this.sessionDbPath());return PU($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=f4();this.run(`INSERT OR REPLACE INTO sessions (
433
+ WHERE run_id = ? AND claim_token = ?`).run($.error??null,$.scheduledFor??null,f,$.runId,$.claimToken).changes??0)>0}attachSessionIdToRun($,f){this.db.prepare("UPDATE cron_runs SET session_id = ?, updated_at = ? WHERE run_id = ?").run(f,X0(),$)}attachReportPathToRun($,f){this.db.prepare("UPDATE cron_runs SET report_path = ?, updated_at = ? WHERE run_id = ?").run(f,X0(),$)}}class t2{store;reconciler;watcher;eventIngress;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a2({dbPath:$.dbPath});let f=$.specs;this.reconciler=new T5({store:this.store,specs:f}),this.materializer=new l2({store:this.store}),this.eventIngress=new B5({store:this.store,logger:$.logger}),this.runner=new p2({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,workspaceRoot:$.workspaceRoot,specs:f,logger:$.logger,pollIntervalMs:$.pollIntervalMs,claimLeaseSeconds:$.claimLeaseSeconds,globalMaxConcurrency:$.globalMaxConcurrency}),this.watcher=new M5({reconciler:this.reconciler,debounceMs:$.watcherDebounceMs,onReconciled:()=>{this.materializer.materializeAll()},onError:(J)=>{let Q=$.logger;if(Q)if(Q.error)Q.error("cron.watcher.failed",{error:J});else Q.log("cron.watcher.failed",{error:J})}})}async start(){if(this.disposed)throw Error("CronService disposed");if(this.started)return;this.started=!0,await this.reconciler.reconcileAll(),this.materializer.materializeAll(),this.watcher.start(),await this.runner.start()}async stop(){this.watcher.stop(),await this.runner.stop(),this.started=!1}async dispose(){if(this.disposed)return;this.disposed=!0,this.watcher.dispose(),await this.runner.dispose(),this.store.close()}listSpecs($){return this.store.listSpecs($)}getSpec($){return this.store.getSpec($)}listRuns($){return this.store.listRuns($)}getRun($){return this.store.getRun($)}listActiveRuns(){return this.store.listRuns({status:"running",limit:200})}listUpcomingRuns($=20){return this.store.listRuns({status:"queued",limit:$})}async reconcileNow(){await this.reconciler.reconcileAll(),this.materializer.materializeAll()}ingestEvent($){return this.eventIngress.ingestEvent($)}listEventLogs($){return this.store.listEventLogs($)}getEventLog($){return this.store.getEventLog($)}}import{readdir as iU,readFile as rW}from"node:fs/promises";import{join as iW}from"node:path";import{formatDisplayUserInput as nU,normalizeUserInput as aU}from"@cline/shared";import{resolveSessionDataDir as nW}from"@cline/shared/storage";import{mkdirSync as mU,writeFileSync as gU}from"node:fs";import{dirname as vU}from"node:path";import{normalizeUserInput as uU}from"@cline/shared";import{nanoid as cU}from"nanoid";import{nanoid as IU}from"nanoid";function s2($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function e4($,f){let J=s2($),Q=s2(f),Z=`${J}__${Q}`;return Z.length>180?Z.slice(0,180):Z}function S5($,f){let J=s2($),Q=s2(f);return`${J}__teamtask__${Q}__${IU(6)}`}function o2($){let J=$.indexOf("__teamtask__");if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+12),W=Z.lastIndexOf("__");if(W<=0)return null;let j=Z.slice(0,W),X=Z.slice(W+2);if(!Q||!j||!X)return null;return{rootSessionId:Q,agentId:j,teamTaskId:X}}function $6($){if(o2($))return null;let f="__",J=$.indexOf(f);if(J<=0)return null;let Q=$.slice(0,J),Z=$.slice(J+f.length);if(!Q||!Z)return null;return{rootSessionId:Q,agentId:Z}}function h5($){switch($.hookName){case"agent_end":return"completed";case"agent_error":return"failed";case"session_shutdown":{let f=String($.reason??"").toLowerCase();if(f.includes("cancel")||f.includes("abort")||f.includes("interrupt"))return"cancelled";if(f.includes("fail")||f.includes("error"))return"failed";return"completed"}default:return"running"}}import{z as i}from"zod";var xU=i.enum(sf),_0=i.object({version:i.literal(1),session_id:i.string().min(1),source:i.string().min(1),pid:i.number().int(),started_at:i.string().min(1),ended_at:i.string().min(1).optional(),exit_code:i.number().int().nullable().optional(),status:xU,interactive:i.boolean(),provider:i.string().min(1),model:i.string().min(1),cwd:i.string().min(1),workspace_root:i.string().min(1),team_name:i.string().min(1).optional(),enable_tools:i.boolean(),enable_spawn:i.boolean(),enable_teams:i.boolean(),prompt:i.string().optional(),metadata:i.record(i.string(),i.unknown()).optional(),messages_path:i.string().min(1).optional()});function xW($){if(!$)return!1;return Object.values($).some((f)=>typeof f==="function")}function E5($,f){let J=[...$??[],...f??[]];if(J.length===0)return;let Q=[],Z=new Set;for(let W of J){if(Z.has(W.name))continue;Z.add(W.name),Q.push(W)}return Q}function mW($){return JSON.stringify($,(f,J)=>{if(J instanceof Error)return{name:J.name,message:J.message,stack:J.stack};return J})}function W$($){return typeof $==="string"&&$.trim()?$.trim():void 0}function C5($,f){let J={...$};J.id=W$(J.id)??cU();let Q=J.modelInfo&&typeof J.modelInfo==="object"?{...J.modelInfo}:void 0,Z={id:W$(Q?.id)??W$(J.modelId)??W$(f?.id),provider:W$(Q?.provider)??W$(J.providerId)??W$(f?.provider),family:W$(Q?.family)??W$(f?.family)};if(delete J.providerId,delete J.modelId,Z.id&&Z.provider)J.modelInfo={id:Z.id,provider:Z.provider,...Z.family?{family:Z.family}:{}};else delete J.modelInfo;return J}function f6($){return $.map((f)=>C5(f))}function J6($,f,J=[]){let Q=$.map((H,Y)=>{let V=J[Y],B=V?.role===H.role&&JSON.stringify(V.content)===JSON.stringify(H.content)?{...V,...H}:{...H};return C5(B)}),Z=J.length,W=[];for(let H=Z;H<Q.length;H+=1)if(Q[H]?.role==="assistant")W.push(H);if(W.length===0){let H=[...Q].reverse().findIndex((Y)=>Y.role==="assistant");if(H===-1)return Q;W.push(Q.length-1-H)}let j=W[W.length-1],X=W.some((H)=>Q[H]?.metrics);for(let H of W){let Y=Q[H],V=Y.metrics;if(!V&&H===j&&!X){let A=f.usage;V={inputTokens:A.inputTokens,outputTokens:A.outputTokens,cacheReadTokens:A.cacheReadTokens??0,cacheWriteTokens:A.cacheWriteTokens??0,cost:A.totalCost}}Q[H]={...C5(Y,{id:f.model.id,provider:f.model.provider,family:f.model.info?.family}),...V?{metrics:V}:{},ts:Y.ts??f.endedAt.getTime()}}return Q}function e2($){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 dU=120;function G1($){let f=$?.trim();return f?f.slice(0,dU):void 0}function b5($){let f=uU($??"").trim();if(!f)return;return G1(f.split(`
434
+ `)[0]?.trim())}function S$($){if(!$)return;let f={...$},J=G1(typeof f.title==="string"?f.title:void 0);if(J)f.title=J;else delete f.title;return Object.keys(f).length>0?f:void 0}function $8($){let f=S$($.metadata)??{},J=$.title!==void 0?G1($.title):b5($.prompt);if(J)f.title=J;return Object.keys(f).length>0?f:void 0}function k5($){let f=o2($);if(f)return{agent:"teammate",sessionId:f.rootSessionId,taskType:"team"};let J=$6($);if(J)return{agent:"subagent",sessionId:J.rootSessionId,taskType:"subagent_task"};return{agent:"lead",sessionId:$}}function I5($){return{version:1,updated_at:$.updatedAt,agent:$.context.agent,sessionId:$.context.sessionId,...$.context.taskType?{taskType:$.context.taskType}:{},messages:f6($.messages),...$.systemPrompt?{system_prompt:$.systemPrompt}:{}}}function gW($,f,J){mU(vU($),{recursive:!0}),gU($,`${JSON.stringify(I5({updatedAt:f,context:J,messages:[]}),null,2)}
435
+ `,"utf8")}function vW($,f){return _0.parse({version:1,session_id:$.sessionId,source:$.source,pid:$.pid,started_at:$.startedAt,ended_at:f?.endedAt??$.endedAt??void 0,exit_code:f?.exitCode??$.exitCode??void 0,status:f?.status??$.status,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName??void 0,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt??void 0,metadata:f?.metadata??$.metadata??void 0,messages_path:$.messagesPath??void 0})}async function uW($,f,J){let Q=0;while(!0){let Z=await $();if(Z===void 0)return{updated:!1};let W=await f(Z);if(typeof W==="object"&&W!==null&&"updated"in W&&W.updated===!1){if(Q+=1,Q>=J)return W;continue}return W}}import{existsSync as lU}from"node:fs";import{readFile as pU}from"node:fs/promises";import{formatDisplayUserInput as cW}from"@cline/shared";class f8{listeners=new Set;subscribe($,f){let J={listener:$,sessionId:f?.sessionId?.trim()||void 0};return this.listeners.add(J),()=>{this.listeners.delete(J)}}emit($){let f=$.payload.sessionId?.trim();for(let J of this.listeners){if(J.sessionId&&J.sessionId!==f)continue;J.listener($)}}get size(){return this.listeners.size}}async function h$($){let f=$?.trim();if(!f||!lU(f))return[];try{let J=(await pU(f,"utf8")).trim();if(!J)return[];let Q=JSON.parse(J);if(Array.isArray(Q))return dW(Q);if(Q&&typeof Q==="object"&&!Array.isArray(Q)){let Z=Q.messages;if(Array.isArray(Z))return dW(Z)}return[]}catch{return[]}}function rU($){if($.role!=="user")return $;if(typeof $.content==="string")return{...$,content:cW($.content)};return{...$,content:$.content.map((f)=>{if(f.type!=="text"||typeof f.text!=="string")return f;return{...f,text:cW(f.text)}})}}function dW($){return $.map(rU)}function x5($){return $?{...$}:void 0}async function lW($,f){if(!($.hookName==="tool_call"||!!$.parent_agent_id))return;await f.queueSpawnRequest($);let Q=await f.upsertSubagentSessionFromHook($);if(!Q)return;await f.appendSubagentHookAudit(Q,$),await f.applySubagentStatus(Q,$)}function J8($){if(typeof $!=="string")return;let f=$.trim();return f.length>0?f:void 0}function k0($){let f=J8($);if(!f)return;return f.toLowerCase()==="unknown"?void 0:f}function Q6($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function tU($){if(!$||typeof $!=="object"||Array.isArray($))return;return{...$}}function g5($){let f=$??200;return Number.isFinite(f)?Math.max(0,Math.floor(f)):200}function sU($){if($===0)return 0;return Math.min(Math.max($*2,20),2000)}function oU($){return $.isSubagent!==!0&&!J8($.parentSessionId)}function eU($){let f=$.match(/\d{13,}/g);if(!f||f.length===0)return 0;let J=0;for(let Q of f){let Z=Number.parseInt(Q,10);if(Number.isFinite(Z)&&Z>J)J=Z}return J}function v5($){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 $D($){let f=g5($);if(f===0)return[];let J=nW(),Z=(await iU(J,{withFileTypes:!0}).catch(()=>[])).filter((j)=>j.isDirectory()).map((j)=>({entry:j,recency:eU(j.name.trim())})).sort((j,X)=>X.recency-j.recency||X.entry.name.localeCompare(j.entry.name));return(await Promise.all(Z.map(async({entry:j})=>{let X=j.name.trim();if(!X)return;let H=iW(J,X,`${X}.json`),Y=await rW(H,"utf8").catch(()=>{return});if(!Y)return;let V;try{V=JSON.parse(Y)}catch{return}let A=_0.safeParse(V);if(!A.success)return;return v5(A.data)}))).filter((j)=>Boolean(j)).sort((j,X)=>X.startedAt.localeCompare(j.startedAt)).slice(0,f)}async function fD($,f,J){let Q=g5(f);if(Q===0)return await $.listSessions(0),[];let Z=J.includeSubagents?Q:sU(Q),W=await $.listSessions(Z);return(J.includeSubagents?W:W.filter(oU)).slice(0,Q)}function JD($){if(typeof $==="string")return $.trim();let f=[];for(let J of $){if(!J||typeof J!=="object")continue;let Q=J;if(Q.type!=="text")continue;let Z=Q.text?.trim();if(Z)f.push(Z)}return f.join(`
436
+ `).trim()}function pW($){return $.replace(/\s+/g," ").trim()}function QD($,f){if($.length<=f)return $;return`${$.slice(0,Math.max(0,f-3)).trimEnd()}...`}function ZD($){for(let f of["user","assistant"])for(let J of $){if(J.role!==f)continue;let Q=pW(JD(J.content));if(!Q)continue;let Z=f==="user"?pW(nU(Q)):Q,W=aU(Z.split(`
437
+ `)[0]??Z);return QD(W,50)}return}function WD($){let f=0;for(let J of $)f+=Q6(J.metrics?.cost)??0;return f}function jD($){let f,J;for(let Q=$.length-1;Q>=0;Q-=1){let Z=$[Q];if(!f)f=k0(Z.modelInfo?.provider);if(!J)J=k0(Z.modelInfo?.id);if(f&&J)break}return{provider:f,model:J}}function XD($){return k0($?.provider)??k0($?.provider&&typeof $.provider==="object"&&!Array.isArray($.provider)?$.provider.id:void 0)}function HD($){return k0($?.model)??k0($?.model&&typeof $.model==="object"&&!Array.isArray($.model)?$.model.id:void 0)}function m5($,f){let J=tU($.metadata),Q=J8(f?.title)??J8(J?.title),Z=Q6(f?.totalCost)??Q6(J?.totalCost),W=J||Q!==void 0||Z!==void 0?{...J??{},...Q!==void 0?{title:Q}:{},...Z!==void 0?{totalCost:Z}:{}}:void 0;return{...$,provider:k0(f?.provider)??k0($.provider)??XD(J)??"",model:k0(f?.model)??k0($.model)??HD(J)??"",metadata:W}}function YD($){let f=$.content;if(!Array.isArray(f))return!1;return f.some((J)=>!!J&&typeof J==="object"&&J.type==="tool-call")}function VD($,f){if($.status!=="running"||$.interactive!==!0)return!1;let J=f.at(-1);return J?.role==="assistant"&&!YD(J)}async function AD($,f){return await Promise.all(f.map(async(J)=>{if(J.status!=="running"||J.interactive!==!0)return J;let Q=await $.readSessionMessages(J.sessionId);return VD(J,Q)?{...J,status:"idle"}:J}))}async function BD($,f){return await Promise.all(f.map(async(J)=>{let Q=m5(J),Z=Boolean(J8(Q.metadata?.title)),W=Boolean(k0(Q.provider)),j=Boolean(k0(Q.model)),X=Q6(Q.metadata?.totalCost),H=X!==void 0&&X>0;if(Z&&W&&j&&H)return Q;let Y=await $.readSessionMessages(J.sessionId);if(Y.length===0)return Q;let V=jD(Y),A=WD(Y);return m5(J,{title:Z?void 0:ZD(Y),provider:W?void 0:V.provider,model:j?void 0:V.model,totalCost:H||A<=0?void 0:A})}))}async function u5($,f={}){let J=g5(f.limit),Q=f.includeSubagents===!0,Z=await fD($,J,{includeSubagents:Q}),W=f.includeManifestFallback===!0&&Z.length<J?await $D(Math.min(Math.max(J*2,100),500)):[],j=new Map;for(let Y of[...Z,...W]){if(j.has(Y.sessionId))continue;j.set(Y.sessionId,Y)}let X=W.length===0?Z:Array.from(j.values()).sort((Y,V)=>V.startedAt.localeCompare(Y.startedAt)).slice(0,J),H=await AD($,X);if(f.hydrate===!1)return H.map((Y)=>m5(Y));return await BD($,H)}async function GD($){let f=$.trim();if(!f)return;let J=iW(nW(),f,`${f}.json`),Q=await rW(J,"utf8").catch(()=>{return});if(!Q)return;try{let Z=_0.safeParse(JSON.parse(Q));return Z.success?Z.data.messages_path:void 0}catch{return}}async function KD($,f={}){let J=new Map;return await u5({listSessions:async(Z)=>{let W=await $.listSessions(Z);J.clear();for(let j of W)J.set(j.sessionId,j);return W.map(e2)},readSessionMessages:async(Z)=>{let W=J.get(Z)?.messagesPath??await GD(Z);return await h$(W)}},f)}import{captureSdkError as DH}from"@cline/shared";import{createSessionId as AR,resolveHubCommandTimeoutMs as BR}from"@cline/shared";import{spawn as cD}from"node:child_process";import{closeSync as dD,mkdirSync as lD,openSync as pD}from"node:fs";import{basename as rD,dirname as iD,join as nD}from"node:path";import{fileURLToPath as aD}from"node:url";import{CLINE_RUN_AS_HUB_DAEMON_ENV as tD,isHubDaemonProcess as Xj,withResolvedClineBuildEnv as sD}from"@cline/shared";import{createHash as FD,randomBytes as PD}from"node:crypto";import{existsSync as UD}from"node:fs";import{chmod as DD,mkdir as c5,readFile as $j,rm as d5,writeFile as fj}from"node:fs/promises";import{dirname as Jj,join as l5}from"node:path";import{resolveClineDataDir as p5,resolveClineDir as CE}from"@cline/shared/storage";var tW="0.0.42";var sW={name:"@cline/core",description:"Cline Core SDK for Node Runtime",version:tW,repository:{type:"git",url:"https://github.com/cline/cline",directory:"sdk/packages/core"},type:"module",types:"./dist/index.d.ts",main:"./dist/index.js",private:!1,publishConfig:{access:"public"},exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js"},"./hub":{types:"./dist/hub/index.d.ts",import:"./dist/hub/index.js"},"./hub/daemon-entry":{types:"./dist/hub/daemon/entry.d.ts",import:"./dist/hub/daemon/entry.js"},"./telemetry":{types:"./dist/services/telemetry/index.d.ts",import:"./dist/services/telemetry/index.js"}},scripts:{build:"bun run ./bun.mts && bun tsc -p tsconfig.build.json",typecheck:"bun tsc -p tsconfig.dev.json --noEmit && bun run typecheck:smoke","typecheck:smoke":"bun tsc -p tsconfig.smoke.json --noEmit",test:"bun run test:unit && bun run test:e2e","test:live":"vitest run --config vitest.config.ts src/extensions/context/compaction.live.test.ts","test:unit":"vitest run --config vitest.config.ts","test:e2e":"vitest run --config vitest.e2e.config.ts","verify:routines":"zsh -lc 'bunx vitest run src/cron/schedule-service.test.ts --config vitest.config.ts'","test:watch":"vitest --config vitest.config.ts"},dependencies:{"@cline/agents":"workspace:*","@cline/shared":"workspace:*","@cline/llms":"workspace:*","@modelcontextprotocol/sdk":"^1.29.0","@opentelemetry/api":"^1.9.0","@opentelemetry/api-logs":"^0.214.0","@opentelemetry/exporter-logs-otlp-http":"^0.214.0","@opentelemetry/exporter-metrics-otlp-http":"^0.214.0","@opentelemetry/exporter-trace-otlp-http":"^0.214.0","@opentelemetry/resources":"^2.6.1","@opentelemetry/sdk-logs":"^0.214.0","@opentelemetry/sdk-metrics":"^2.6.1","@opentelemetry/sdk-trace-base":"^2.6.1","@opentelemetry/sdk-trace-node":"^2.6.1","@opentelemetry/semantic-conventions":"^1.40.0",jiti:"^2.7.0","node-machine-id":"^1.1.12",nanoid:"^5.1.7","simple-git":"3.36.0",ws:"^8.20.0",yaml:"^2.8.2",zod:"^4.3.6"},devDependencies:{"@types/ws":"^8.18.1"},engines:{node:">=22"},files:["dist","!dist/**/*.d.ts.map"]};var RD="CLINE_HUB_DISCOVERY_PATH",LD="CLINE_HUB_BUILD_ID",oW=30000,OD=15000,zD=100;function _D($){return $.replace(/[^a-zA-Z0-9_.-]+/g,"_")}function ND($){return FD("sha256").update($).digest("hex").slice(0,12)}function TD($){if(!Number.isInteger($)||!$||$<=0)return!1;try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f?String(f.code)==="EPERM":!1}}function Qj(){return PD(32).toString("hex")}function MD($){return new Promise((f)=>setTimeout(f,$))}function qD($){return`${$}.lock`}async function yD($){try{let f=JSON.parse(await $j(l5($,"owner.json"),"utf8"));if(typeof f.pid!=="number"||typeof f.acquiredAt!=="string")return;return{pid:f.pid,acquiredAt:f.acquiredAt}}catch{return}}async function eW($){await d5($,{recursive:!0,force:!0}).catch(()=>{return})}function t1(){return process.env[LD]?.trim()||String(sW.version)}function K1($=process.argv[1]?.trim()||process.cwd()){let f=`hub-${ND($)}`,J=process.env[RD]?.trim()||l5(p5(),"locks","hub","owners",`${_D(f)}.json`);return{ownerId:f,discoveryPath:J}}function bE($=`hub-${Date.now().toString(36)}`){return K1($)}async function A0($){try{let f=JSON.parse(await $j($,"utf8"));if(typeof f.hubId!=="string"||typeof f.protocolVersion!=="string"||typeof f.authToken!=="string"||typeof f.host!=="string"||typeof f.port!=="number"||typeof f.url!=="string"||typeof f.startedAt!=="string"||typeof f.updatedAt!=="string")return;return{hubId:f.hubId,protocolVersion:f.protocolVersion,buildId:typeof f.buildId==="string"?f.buildId:void 0,authToken:f.authToken,host:f.host,port:f.port,url:f.url,pid:typeof f.pid==="number"?f.pid:void 0,startedAt:f.startedAt,updatedAt:f.updatedAt}}catch{return}}async function Zj($,f){await c5(Jj($),{recursive:!0}),await d5($,{force:!0}).catch(()=>{return}),await fj($,`${JSON.stringify(f,null,2)}
438
+ `,{encoding:"utf8",mode:384}),await DD($,384)}async function n0($){await d5($,{force:!0}).catch(()=>{return})}async function Wj($,f){let J=qD($);await c5(Jj(J),{recursive:!0});let Q=Date.now()+OD;while(!0)try{await c5(J,{recursive:!1}),await fj(l5(J,"owner.json"),`${JSON.stringify({pid:process.pid,acquiredAt:new Date().toISOString()},null,2)}
439
+ `,"utf8");try{return await f()}finally{await eW(J)}}catch(Z){if((Z instanceof Error&&"code"in Z?String(Z.code):"")!=="EEXIST")throw Z;let j=await yD(J),X=j?Date.now()-Date.parse(j.acquiredAt):oW+1;if(!j||!TD(j.pid)||X>oW){await eW(J);continue}if(Date.now()>=Q)throw Error(`Timed out waiting for hub startup lock ${J}`);await MD(zD)}}async function U0($){try{let f=await fetch(wD($));if(!f.ok)return;return await f.json()}catch{return}}function j$($,f,J="/hub"){return new URL(`ws://${$}:${f}${J}`).toString()}function wD($){let f=new URL($);return f.protocol=f.protocol==="wss:"?"https:":"http:",f.pathname="/health",f.search="",f.toString()}function kE($){return UD($)}import{CLINE_HUB_DEV_PORT as SD,CLINE_HUB_PORT as hD,resolveClineBuildEnv as CD}from"@cline/shared";var ED="CLINE_HUB_HOST",bD="CLINE_HUB_PORT",kD="CLINE_HUB_PATHNAME",ID="127.0.0.1",xD=hD,mD="/hub";function jj($){return CD($)==="development"?SD:xD}function gD($={}){return($.env??process.env)[ED]?.trim()||ID}function Z6($={}){let J=($.env??process.env)[bD]?.trim();if(!J)return jj($);let Q=Number.parseInt(J,10);if(!Number.isInteger(Q)||Q<1||Q>65535)return jj($);return Q}function vD($={}){return($.env??process.env)[kD]?.trim()||mD}function C$($={},f={}){return{host:$.host??gD(f),port:$.port??Z6(f),pathname:$.pathname??vD(f)}}var uD="shared:cline";function uE($){let f=Y1($.trim());return K1(`workspace:${f||$.trim()}`)}function D0($=uD){return K1($)}var oD=8000,eD=200,$R=3000,fR=100,JR=[100,250,500,1000,2000],QR="--cline-hub-daemon";function ZR($){return[...$.host?["--host",$.host]:[],...typeof $.port==="number"?["--port",String($.port)]:[],...$.pathname?["--pathname",$.pathname]:[]]}function WR(){try{let $=nD(p5(),"logs","hub-daemon.log");return lD(iD($),{recursive:!0}),{fd:pD($,"a"),logPath:$}}catch{return}}function Q8($){let f=$.buildId?.trim();return!!f&&f===t1()}async function jR($,f){let J=Date.now()+f;while(Date.now()<J){if(!(await U0($).catch(()=>{return}))?.url)return!0;await new Promise((Z)=>setTimeout(Z,fR))}return!1}async function Z8($,f){if(Q8($))return;if(await r5($.url,$.authToken).catch(()=>!1),$.pid)try{process.kill($.pid,"SIGTERM")}catch{}await jR($.url,$R),await n0(f).catch(()=>{return})}function XR(){let $=import.meta.url.endsWith(".ts")?"ts":"js";return aD(new URL(`./entry.${$}`,import.meta.url))}function HR($,f){let J=XR(),Q=process.execPath?.trim();if(!Q)throw Error("unable to resolve runtime executable for hub daemon");let Z=rD(Q).toLowerCase().includes("bun"),W=J.startsWith("/$bunfs/"),j=Z&&J.toLowerCase().endsWith(".ts"),X=W?[QR]:[...j?["--conditions=development"]:[],J];return{launcher:Q,args:[...X,"--cwd",$,...ZR(f)],cwd:$,env:{...sD(process.env),CLINE_NO_INTERACTIVE:"1",[tD]:"1"}}}function YR($){if(!$||typeof $!=="object")return!1;if(("code"in $?$.code:void 0)==="ETXTBSY")return!0;let J="message"in $?$.message:void 0;return typeof J==="string"&&J.includes("ETXTBSY")}function VR($,f={}){if(Xj())return;let J=HR($,f),Q=WR();try{cD(J.launcher,J.args,{detached:!0,stdio:Q?["ignore",Q.fd,Q.fd]:"ignore",env:J.env,cwd:J.cwd}).unref()}finally{if(Q)dD(Q.fd)}}async function W6($,f={}){for(let J=0;;J++)try{VR($,f);return}catch(Q){let Z=JR[J];if(!YR(Q)||Z===void 0)throw Q;await new Promise((W)=>setTimeout(W,Z))}}function Hj($,f={}){if(Xj())return;let J=D0(),Q=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=C$(f),W=j$(Z.host,Z.port,Z.pathname);A0(J.discoveryPath).then(async(j)=>{if(j?.url){let V=await U0(j.url);if(V?.url&&Q8(V)&&await E$(V.url,{authToken:j.authToken}))return;if(V?.url)await Z8({...V,authToken:j.authToken},J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}let X=await U0(W);if(X?.url)await Z8(X,J.discoveryPath);let Y=!Q&&Z.port!==0?{...Z,port:0}:Z;await W6($,Y)}).catch(()=>{})}async function oE($,f={}){let J=D0(),Q=f.host!==void 0||f.port!==void 0||f.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Z=f.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),W=C$(f),j=j$(W.host,W.port,W.pathname),X=(G)=>{if(!Q)s1(G.url,G.authToken);return G},H=await A0(J.discoveryPath);if(H?.url){let G=await U0(H.url);if(G?.url&&Q8(G)&&await E$(G.url,{authToken:H.authToken}))return X({url:G.url,authToken:H.authToken});if(G?.url)await Z8({...G,authToken:H.authToken},J.discoveryPath);else await n0(J.discoveryPath).catch(()=>{return})}let Y=await U0(j);if(Y?.url)await Z8(Y,J.discoveryPath);let A=!Z&&W.port!==0?{...W,port:0}:W;await W6($,A);let B=Date.now()+oD;while(Date.now()<B){let G=await A0(J.discoveryPath);if(G?.url){let D=await U0(G.url);if(D?.url&&Q8(D)&&await E$(D.url,{authToken:G.authToken}))return X({url:D.url,authToken:G.authToken})}let K=await U0(j);if(K?.url&&!Q8(K))await Z8(K,J.discoveryPath);await new Promise((D)=>setTimeout(D,eD))}throw Error("Timed out waiting for detached hub startup.")}function GR(){let $=globalThis.WebSocket;if(!$)throw Error("Global WebSocket is not available in this runtime. Node 22+ is required for hub mode.");return $}function Gj($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();if($&&typeof $==="object"&&"data"in $&&typeof $.data<"u")return Gj($.data);return String($)}function KR($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString("utf8");if($ instanceof ArrayBuffer)return Buffer.from($).toString("utf8");return""}function Yj($){let f=$,J=KR(f.reason);return new I0("hub_connection_closed",f.code||J?`Hub connection closed (code=${f.code??0}${J?`, reason=${J}`:""})`:i5,{closeCode:f.code,closeReason:J||void 0})}function FR($,f){if($ instanceof I0)return $;if($ instanceof Error)return new I0("hub_connect_failed",$.message);if($&&typeof $==="object"&&"error"in $&&$.error instanceof Error)return new I0("hub_connect_failed",$.error.message);let J=$&&typeof $==="object"&&"message"in $&&typeof $.message==="string"?$.message.trim():"";if(J)return new I0("hub_connect_failed",J);let Q=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return new I0("hub_connect_failed",Q?`Failed to connect to hub at ${f.toString()} (${Q} event before socket open).`:`Failed to connect to hub at ${f.toString()}.`)}var PR=8000,UR=200,Vj="*",Aj=8000,DR="cline-hub-auth.",Kj=new Map,Fj=new Set,RR=3000,LR=3000,OR=100,i5="Hub connection closed",zR=250,_R=5000,Bj=0.5;class I0 extends Error{code;details;constructor($,f,J){super(f);this.code=$;this.details=J;this.name="HubTransportError"}}function NR($){return $ instanceof I0}class j6 extends Error{command;code;constructor($,f,J){super(J);this.command=$;this.code=f;this.name="HubCommandError"}}function Pj($,f){return $ instanceof j6&&$.code==="hub_command_timeout"&&(f===void 0||$.command===f)}function Uj($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=t5($.toString());return J?Kj.get(J):void 0}function TR($){try{let J=new URL($).hostname.toLowerCase().replace(/^\[|\]$/g,"");return J==="localhost"||J==="127.0.0.1"||J==="::1"}catch{return!1}}function t5($){if(!TR($))return;let f=new URL(o1($));return f.search="",f.hash="",f.toString()}function n5($){let f=t5($);return!!f&&Fj.has(f)}function s1($,f){let J=t5($);if(J){if(Fj.add(J),f?.trim())Kj.set(J,f)}return $}class X${options;socket;connectPromise;clientId;currentUrl;recoveryPromise;pendingReplies=new Map;listeners=new Set;subscriptionCounts=new Map;reconnectTimer;reconnectAttempt=0;closedByClient=!1;lastCloseError=new I0("hub_connection_closed",i5);sawSocketClose=!1;registered=!1;constructor($){this.options=$;this.clientId=$.clientId??`core-${Math.random().toString(36).slice(2,10)}-${Date.now().toString(36)}`,this.currentUrl=$.url}getClientId(){return this.clientId}getUrl(){return this.currentUrl}async connect(){if(this.socket&&(this.socket.readyState===1||this.socket.readyState===0))return this.connectPromise??Promise.resolve();this.closedByClient=!1,this.clearReconnectTimer();let $=new URL(this.currentUrl),f=this.options.authToken?.trim()||Uj($);$.hash="";let Q=new(GR())($.toString(),f?[`${DR}${f}`]:void 0);this.socket=Q;let Z=!1;this.connectPromise=new Promise((W,j)=>{let X=!1,H=setTimeout(()=>{if(X)return;X=!0,Z=!0,this.lastCloseError=new I0("hub_connect_timeout",`Timed out connecting to hub after ${Aj}ms`),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0;try{Q.close()}catch{}j(this.lastCloseError)},Aj);Q.addEventListener("open",()=>{if(X)return;X=!0,clearTimeout(H),W()}),Q.addEventListener("error",(Y)=>{if(X)return;X=!0,clearTimeout(H),this.lastCloseError=FR(Y,$),this.sawSocketClose=!1,this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)}),Q.addEventListener("close",(Y)=>{if(X)return;if(X=!0,clearTimeout(H),!Z)this.lastCloseError=Yj(Y),this.sawSocketClose=!0;this.connectPromise=void 0,this.socket=void 0,j(this.lastCloseError)})}),Q.addEventListener("message",(W)=>{this.handleFrame(JSON.parse(Gj(W)))}),Q.addEventListener("close",(W)=>{if(this.socket!==Q)return;if(!Z)this.lastCloseError=Yj(W),this.sawSocketClose=!0;this.registered=!1;for(let j of this.pendingReplies.values())j.reject(this.lastCloseError);if(this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0,!this.closedByClient&&this.hasActiveSubscriptions())this.scheduleReconnect()}),await this.connectPromise,await this.command("client.register",{clientId:this.clientId,clientType:this.options.clientType??"core",displayName:this.options.displayName??"core",transport:"native",actorKind:"client",workspaceContext:{workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}}),this.registered=!0;for(let W of this.subscriptionCounts.keys())this.sendSubscriptionFrame("stream.subscribe",this.subscriptionSessionIdFromKey(W));this.reconnectAttempt=0}subscribe($,f){let J=f?.sessionId?.trim()||void 0,Q={listener:$,sessionId:J};return this.listeners.add(Q),this.adjustSubscriptionCount(J,1),()=>{if(!this.listeners.delete(Q))return;this.adjustSubscriptionCount(J,-1)}}async command($,f,J,Q){let Z=0,W=$!=="client.register"&&$!=="client.unregister";while(!0)try{return await this.commandOnce($,f,J,Q)}catch(j){if(!W||Z>=1||!await this.recoverLocalHubTransport(j))throw j;Z+=1}}async commandOnce($,f,J,Q){await this.connect();let Z=AR("hubreq_"),W=BR($,Q?.timeoutMs),j=new Promise((H,Y)=>{let V=W===null?void 0:setTimeout(()=>{if(!this.pendingReplies.delete(Z))return;Y(new j6($,"hub_command_timeout",`Hub command ${$} timed out after ${W}ms (hub=${this.currentUrl}, requestId=${Z}, clientId=${this.clientId}). Check hub-daemon.log for matching command.start/command.slow entries, or run 'cline doctor fix' to restart the hub.`))},W);this.pendingReplies.set(Z,{resolve:(A)=>{if(V)clearTimeout(V);H(A)},reject:(A)=>{if(V)clearTimeout(V);Y(A)}})});try{this.sendFrame({kind:"command",envelope:{version:"v1",command:$,requestId:Z,clientId:this.clientId,sessionId:J,timeoutMs:W,payload:f}})}catch(H){throw this.pendingReplies.delete(Z),H}let X=await j;if(!X.ok)throw new j6($,X.error?.code,X.error?.message??`Hub command ${$} failed`);return X}async recoverLocalHubTransport($){if(!n5(this.currentUrl)||!NR($))return!1;if(this.recoveryPromise)return await this.recoveryPromise;return this.recoveryPromise=(async()=>{let f=await W8({workspaceRoot:this.options.workspaceRoot,cwd:this.options.cwd}).catch(()=>{return});if(!f)return!1;return this.currentUrl=f,this.close(),!0})().finally(()=>{this.recoveryPromise=void 0}),await this.recoveryPromise}hasActiveSubscriptions(){return this.subscriptionCounts.size>0}clearReconnectTimer(){if(!this.reconnectTimer)return;clearTimeout(this.reconnectTimer),this.reconnectTimer=void 0}scheduleReconnect(){if(this.reconnectTimer||this.closedByClient||!this.hasActiveSubscriptions())return;let $=Math.min(zR*2**this.reconnectAttempt,_R),f=Math.round($*(1-Bj)+Math.random()*$*Bj);this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.reconnectSubscribedTransport()},f)}async reconnectSubscribedTransport(){if(this.closedByClient||!this.hasActiveSubscriptions())return;try{await this.connect(),this.reconnectAttempt=0}catch{if(!n5(this.currentUrl)){this.reconnectAttempt+=1,this.scheduleReconnect();return}try{let $=await W8({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 I0("hub_connection_closed",i5),this.sawSocketClose=!1;for(let f of this.pendingReplies.values())f.reject(this.lastCloseError);this.pendingReplies.clear(),this.connectPromise=void 0,this.socket=void 0;try{$.close()}catch{}}async dispose(){if(this.socket?.readyState===1&&this.registered)try{await this.command("client.unregister",void 0,void 0,{timeoutMs:2000})}catch{}this.close()}sendFrame($){if(!this.socket||this.socket.readyState!==1){if(this.lastCloseError.code==="hub_connection_closed"&&!this.sawSocketClose)throw new I0("hub_connection_not_open","Hub connection is not open.");throw this.lastCloseError}this.socket.send(JSON.stringify($))}sendSubscriptionFrame($,f){this.sendFrame({kind:$,clientId:this.clientId,...f?{sessionId:f}:{}})}adjustSubscriptionCount($,f){let J=this.subscriptionKeyForSessionId($),Q=(this.subscriptionCounts.get(J)??0)+f;if(Q<=0){if(this.subscriptionCounts.delete(J),!this.hasActiveSubscriptions())this.clearReconnectTimer();if(f<0&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.unsubscribe",$);return}if(this.subscriptionCounts.set(J,Q),f>0&&Q===1&&this.socket?.readyState===1)this.sendSubscriptionFrame("stream.subscribe",$)}subscriptionKeyForSessionId($){return $??Vj}subscriptionSessionIdFromKey($){return $===Vj?void 0:$}handleFrame($){switch($.kind){case"reply":{let f=$.envelope.requestId;if(!f)return;let J=this.pendingReplies.get(f);if(!J)return;this.pendingReplies.delete(f),J.resolve($.envelope);return}case"event":for(let f of this.listeners){if(f.sessionId&&f.sessionId!==$.envelope.sessionId?.trim())continue;f.listener($.envelope)}return;case"command":case"stream.subscribe":case"stream.unsubscribe":return}}}function o1($){let f=new URL($);if(f.protocol==="http:")f.protocol="ws:";else if(f.protocol==="https:")f.protocol="wss:";return f.toString()}async function E$($,f){let J=new X$({url:$,authToken:f?.authToken,clientType:"hub-healthcheck",displayName:"hub healthcheck",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd});try{return await J.connect(),!0}catch{return!1}finally{J.close()}}async function a5($,f){let J=o1($),Q=await U0(J);if(!Q)return{status:"unreachable",url:J};let Z=t1(),W=Q.buildId?.trim();if(!W||W!==Z)return{status:"build_mismatch",url:J};if(f?.verifyConnection===!0&&!await E$(J,{workspaceRoot:f.workspaceRoot,cwd:f.cwd,authToken:f.authToken}))return{status:"unreachable",url:J};return{status:"compatible",url:J}}async function MR($){let f=Date.now()+PR;while(Date.now()<f){let J=await A0($.discoveryPath);if(J?.url){let Q=await a5(J.url,{verifyConnection:!0,authToken:J.authToken});if(Q.status==="compatible")return s1(Q.url,J.authToken)}await new Promise((Q)=>setTimeout(Q,UR))}return}async function qR($){let f=Date.now()+LR;while(Date.now()<f){if(!(await U0($).catch(()=>{return}))?.url)return!0;await new Promise((Q)=>setTimeout(Q,OR))}return!1}function yR($,f){try{return o1($)===o1(f)}catch{return!1}}function wR($){return($&&typeof $==="object"&&Array.isArray($.sessions)?$.sessions:[]).some((J)=>{if(!J||typeof J!=="object")return!1;let Q=J;if(Q.status==="running"||Q.status==="idle"||Q.status==="pending")return!0;return Array.isArray(Q.participants)&&Q.participants.length>0})}async function SR($,f,J){let Q=new X$({url:$,authToken:f,clientType:"hub-recovery-check",displayName:"hub recovery check",workspaceRoot:J?.workspaceRoot,cwd:J?.cwd});try{let Z=await Q.command("session.list",{limit:500},void 0,{timeoutMs:RR});return!wR(Z.payload)}catch{return!1}finally{await Q.dispose().catch(()=>{return})}}async function s5($={}){if($.endpoint?.trim()){let Z=await a5($.endpoint);return Z.status==="compatible"?Z.url:void 0}let f=D0(),J=await A0(f.discoveryPath);if(!J?.url)return;let Q=await a5(J.url);if(Q.status==="compatible")return s1(Q.url,J.authToken);if(Q.status==="build_mismatch")await n0(f.discoveryPath).catch(()=>{return});return}async function W8($={}){let f=await s5($);if(f&&await E$(f,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return f;if($.endpoint?.trim())return;let J=D0();return await W6($.workspaceRoot??process.cwd()),await MR(J)}async function r5($,f){let J=new URL($),Q=f?.trim()||Uj(J);if(J.protocol==="ws:")J.protocol="http:";else if(J.protocol==="wss:")J.protocol="https:";return J.pathname="/shutdown",J.hash="",(await fetch(J,{method:"POST",headers:Q?{authorization:`Bearer ${Q}`}:void 0})).ok}async function hR(){let $=D0(),f=await A0($.discoveryPath);if(!f?.url)return!1;try{if(await r5(f.url,f.authToken))return!0}catch{}return!1}async function Dj($){if(!n5($.url))return;let f=D0(),J=await A0(f.discoveryPath);if(!J?.url||!yR(J.url,$.url))return;if(!await SR(J.url,J.authToken,{workspaceRoot:$.workspaceRoot,cwd:$.cwd}))return;if(!await hR())return;if(!await qR(J.url))return;return await n0(f.discoveryPath).catch(()=>{return}),await W8({workspaceRoot:$.workspaceRoot,cwd:$.cwd})}import{captureSdkError as Rj,createSessionId as Lj,HUB_CHECKPOINT_CAPABILITY as kR,HUB_COMPACTION_CAPABILITY as IR,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as xR,HUB_HOOK_CAPABILITY_PREFIX as mR,HUB_MISTAKE_LIMIT_CAPABILITY as gR,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as vR,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as uR,isHubToolExecutorName as cR}from"@cline/shared";function CR($){return $?JSON.parse(JSON.stringify($)):void 0}function ER($){return $?JSON.parse(JSON.stringify($)):void 0}function bR($){let f=$?.checkpoint&&typeof $.checkpoint==="object"&&!Array.isArray($.checkpoint)?$.checkpoint:void 0,Q=(Array.isArray(f?.history)?f.history:[]).filter((j)=>!!j&&typeof j==="object"&&!Array.isArray(j)).flatMap((j)=>{let X=typeof j.ref==="string"?j.ref.trim():"",H=Number(j.createdAt),Y=Number(j.runCount);if(!X||!Number.isFinite(H)||!Number.isInteger(Y))return[];return[{ref:X,createdAt:H,runCount:Y,...j.kind==="stash"||j.kind==="commit"?{kind:j.kind}:{}}]}),Z=Q.at(-1),W=$?.checkpointEnabled===!0?!0:void 0;if(!W&&Q.length===0)return;return{...W?{enabled:W}:{},...Z?{latest:Z}:{},history:Q}}function b$($){let{session:f}=$,J=CR(f.metadata);return{version:1,sessionId:f.sessionId,source:f.source,status:f.status,createdAt:f.startedAt,updatedAt:f.updatedAt,endedAt:f.endedAt??null,exitCode:f.exitCode??null,interactive:f.interactive,workspace:{cwd:f.cwd,root:f.workspaceRoot},model:{providerId:f.provider,modelId:f.model},capabilities:{enableTools:f.enableTools,enableSpawn:f.enableSpawn,enableTeams:f.enableTeams},lineage:{...f.parentSessionId?{parentSessionId:f.parentSessionId}:{},...f.parentAgentId?{parentAgentId:f.parentAgentId}:{},...f.agentId?{agentId:f.agentId}:{},...f.conversationId?{conversationId:f.conversationId}:{},isSubagent:f.isSubagent},...f.teamName?{team:{name:f.teamName}}:{},...f.prompt?{prompt:f.prompt}:{},...J?{metadata:J}:{},...f.messagesPath?{artifacts:{messagesPath:f.messagesPath}}:{},...$.messages?{messages:ER($.messages)}:{},...$.usage?{usage:{...$.usage}}:{},...$.aggregateUsage?{aggregateUsage:{...$.aggregateUsage}}:{},...(()=>{let Q=bR(J);return Q?{checkpoint:Q}:{}})()}}function o5($){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 e1($){if(!$)return;return JSON.parse(JSON.stringify($))}var dR=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function Oj($){if(!$||typeof $!=="object"||Array.isArray($))return;return JSON.parse(JSON.stringify($))}function zj($){if(!$)return;let{userInstructionService:f,...J}=$;return JSON.parse(JSON.stringify(J))}function _j($){let f=$&&typeof $==="object"&&!Array.isArray($)?$:{};return{agentId:typeof f.agentId==="string"?f.agentId:"",conversationId:typeof f.conversationId==="string"?f.conversationId:"",iteration:typeof f.iteration==="number"?f.iteration:0,metadata:f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)?f.metadata:void 0}}function F1($,f,J){$.manifest.push(f),$.handlers.set(f.capabilityName,J)}function Nj($,f){let J={manifest:[],handlers:new Map};for(let Z of Object.keys(f.toolExecutors??{}).filter(cR)){let W=f.toolExecutors?.[Z];if(typeof W!=="function")continue;F1(J,{kind:"toolExecutor",executor:Z,capabilityName:`${vR}${Z}`},async({payload:j,abortSignal:X})=>{let H=Array.isArray(j.args)?[...j.args]:[],Y={..._j(j.context),signal:X};return{result:await W(...H,Y)}})}for(let Z of $?.extraTools??[])F1(J,{kind:"tool",name:Z.name,description:Z.description,inputSchema:e1(Z.inputSchema)??{},...Z.lifecycle?{lifecycle:e1(Z.lifecycle)}:{},capabilityName:`${xR}${Z.name}`},async({payload:W,abortSignal:j,progress:X})=>{let H={..._j(W.context),signal:j};return{result:await Z.execute(W.input,{...H,emitUpdate:(V)=>{X({update:V})}})}});let Q=$?.hooks;if(Q)for(let Z of dR){let W=Q[Z];if(typeof W!=="function")continue;F1(J,{kind:"hook",name:Z,capabilityName:`${mR}${Z}`},async({payload:j})=>({control:await W(j.context)}))}if($?.compaction?.compact){let Z=$.compaction.compact;F1(J,{kind:"compaction",capabilityName:IR,config:Oj($.compaction)},async({payload:W})=>({result:await Z(W.context)}))}if($?.checkpoint?.createCheckpoint){let Z=$.checkpoint.createCheckpoint;F1(J,{kind:"checkpoint",capabilityName:kR,config:Oj($.checkpoint)},async({payload:W})=>({result:await Z(W.context)}))}if($?.onConsecutiveMistakeLimitReached){let Z=$.onConsecutiveMistakeLimitReached;F1(J,{kind:"mistakeLimit",capabilityName:gR},async({payload:W})=>({result:await Z(W.context)}))}if($?.userInstructionService){let Z=$.userInstructionService;F1(J,{kind:"userInstructionService",capabilityName:uR},async()=>{return await Z.start().catch(()=>{}),{snapshot:{records:{skill:Z.listRecords("skill"),rule:Z.listRecords("rule"),workflow:Z.listRecords("workflow")},runtimeCommands:Z.listRuntimeCommands()}}})}return J}function yj($){if(typeof $==="string"&&$.trim())return $.trim();if($ instanceof Error)return $.message.trim()||void 0;if($&&typeof $==="object"&&"message"in $){let f=$.message;if(typeof f==="string"&&f.trim())return f.trim()}return}function lR($){return yj($)??"Capability request was cancelled."}function pR($){if(typeof $!=="string")return $;try{return JSON.parse($)}catch{return $}}function rR($){return $==="completed"||$==="max_iterations"||$==="aborted"||$==="mistake_limit"||$==="error"}function iR($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=typeof f.inputTokens==="number"?f.inputTokens:void 0,Q=typeof f.outputTokens==="number"?f.outputTokens:void 0;if(J===void 0||Q===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:typeof f.cacheReadTokens==="number"?f.cacheReadTokens:0,cacheWriteTokens:typeof f.cacheWriteTokens==="number"?f.cacheWriteTokens:0,totalCost:typeof f.totalCost==="number"?f.totalCost:0}}function Tj($){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 e5($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function k$($,f){return e5($?.[f])??0}function nR($){let f=$?.delta&&typeof $.delta==="object"?$.delta:void 0,J=$?.totals&&typeof $.totals==="object"?$.totals:void 0,Q=$?.agent&&typeof $.agent==="object"?$.agent:void 0,Z=Q?.teamRole==="teammate"||Q?.teamRole==="lead"?Q.teamRole:void 0;return{event:{type:"usage",agentId:typeof Q?.agentId==="string"?Q.agentId:void 0,conversationId:typeof Q?.conversationId==="string"?Q.conversationId:void 0,parentAgentId:typeof Q?.parentAgentId==="string"?Q.parentAgentId:void 0,inputTokens:k$(f,"inputTokens"),outputTokens:k$(f,"outputTokens"),cacheReadTokens:k$(f,"cacheReadTokens"),cacheWriteTokens:k$(f,"cacheWriteTokens"),cost:e5(f?.totalCost),totalInputTokens:k$(J,"inputTokens"),totalOutputTokens:k$(J,"outputTokens"),totalCacheReadTokens:k$(J,"cacheReadTokens"),totalCacheWriteTokens:k$(J,"cacheWriteTokens"),totalCost:e5(J?.totalCost)},teamAgentId:typeof Q?.teamAgentId==="string"?Q.teamAgentId:void 0,teamRole:Z}}function aR($){let f=$?.result&&typeof $.result==="object"&&!Array.isArray($.result)?$.result:void 0,J=$?.reason??f?.finishReason,Q=rR(J)?J:J==="failed"?"error":"completed",Z=iR($?.usage??f?.usage);return{type:"done",reason:Q,text:typeof $?.text==="string"?$.text:typeof f?.text==="string"?f.text:"",iterations:typeof $?.iterations==="number"?$.iterations:typeof f?.iterations==="number"?f.iterations:0,usage:Z}}function X6($,f){return $.error?.message??`hub command failed: ${f}`}function j8($){switch($){case"idle":case"completed":return"completed";case"failed":return"failed";case"aborted":return"cancelled";default:return"running"}}function wj($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):void 0;return{sessionId:$.sessionId,parentSessionId:typeof f?.parentSessionId==="string"?f.parentSessionId:void 0,agentId:$.runtimeSession?.agentId||(typeof f?.agentId==="string"?f.agentId:void 0),parentAgentId:typeof f?.parentAgentId==="string"?f.parentAgentId:void 0,conversationId:typeof f?.conversationId==="string"?f.conversationId:void 0,isSubagent:typeof f?.isSubagent==="boolean"?f.isSubagent:!1,source:typeof f?.source==="string"?f.source:F0.CORE,pid:typeof f?.pid==="number"?f.pid:void 0,startedAt:new Date($.createdAt).toISOString(),endedAt:j8($.status)==="running"?void 0:new Date($.updatedAt).toISOString(),exitCode:j8($.status)==="completed"?0:j8($.status)==="failed"?1:void 0,status:j8($.status),interactive:f?.interactive===!0,provider:typeof f?.provider==="string"?f.provider:"hub",model:typeof f?.model==="string"?f.model:"hub",cwd:$.cwd?.trim()||$.workspaceRoot,workspaceRoot:$.workspaceRoot,teamName:typeof f?.teamName==="string"?f.teamName:void 0,enableTools:$.runtimeOptions?.enableTools??f?.enableTools===!0,enableSpawn:$.runtimeOptions?.enableSpawn??f?.enableSpawn===!0,enableTeams:$.runtimeOptions?.enableTeams??f?.enableTeams===!0,prompt:typeof f?.prompt==="string"?f.prompt:void 0,metadata:f,updatedAt:new Date($.updatedAt).toISOString(),messagesPath:typeof f?.messagesPath==="string"?f.messagesPath:void 0,hookPath:typeof f?.hookPath==="string"?f.hookPath:void 0}}function I$($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$;return f.version===1&&typeof f.sessionId==="string"?JSON.parse(JSON.stringify(f)):void 0}function tR($){let f=I$($?.snapshot);if(f)return o5(f);let J=$?.session;return J?wj(J):void 0}function Mj($,f,J){let Q=J?.workspaceRoot?.trim()||f.config.workspaceRoot||f.config.cwd;return _0.parse({version:1,session_id:$,source:f.source??F0.CORE,pid:process.pid,started_at:new Date(J?.createdAt??Date.now()).toISOString(),status:j8(J?.status),interactive:f.interactive===!0,provider:f.config.providerId,model:f.config.modelId,cwd:J?.cwd?.trim()||f.config.cwd,workspace_root:Q,team_name:f.config.teamName,enable_tools:f.config.enableTools,enable_spawn:f.config.enableSpawnAgent,enable_teams:f.config.enableAgentTeams,prompt:f.prompt?.trim()||void 0,metadata:f.sessionMetadata&&Object.keys(f.sessionMetadata).length>0?f.sessionMetadata:void 0})}function qj($,f){return _0.parse({version:1,session_id:$.sessionId,source:$.source,pid:process.pid,started_at:$.createdAt,status:$.status,interactive:$.interactive,provider:$.model.providerId,model:$.model.modelId,cwd:$.workspace.cwd,workspace_root:$.workspace.root,team_name:$.team?.name,enable_tools:$.capabilities.enableTools,enable_spawn:$.capabilities.enableSpawn,enable_teams:$.capabilities.enableTeams,prompt:($.prompt??f.prompt?.trim())||void 0,metadata:$.metadata,messages_path:$.artifacts?.messagesPath})}class P1{runtimeAddress;pendingPrompts;client;clientOptions;clientContext;events=new f8;sessionCapabilities=new Map;sessionClientContributionHandlers=new Map;sessionSubscriptions=new Map;pendingApprovalToolCallIds=new Set;agentDoneEmittedForCurrentRunBySession=new Set;activeCapabilityAbortControllers=new Map;defaultCapabilities;telemetry;constructor($,f){this.clientContext=f,this.clientOptions={authToken:$.authToken,clientType:$.clientType??"core-hub-runtime",displayName:$.displayName??"core hub runtime",workspaceRoot:f?.workspaceRoot,cwd:f?.cwd},this.defaultCapabilities=P0($.capabilities)??{},this.telemetry=$.telemetry,this.runtimeAddress=$.url,this.pendingPrompts={list:(J)=>this.requestPendingPromptsList(J),update:(J)=>this.requestPendingPromptUpdate(J),delete:(J)=>this.requestPendingPromptDelete(J)},this.client=this.createClient($.url)}createClient($){return new X$({...this.clientOptions,url:$})}async replaceClient($){let f=this.client;this.client=this.createClient($),this.runtimeAddress=$,await Promise.resolve(f.dispose()).catch(()=>{return})}async recoverLocalHubStartupDeadlock($){if(!Pj($,"session.create"))return!1;let f=await Dj({url:this.client.getUrl(),workspaceRoot:this.clientContext?.workspaceRoot,cwd:this.clientContext?.cwd}).catch(()=>{return});if(!f)return!1;return await this.replaceClient(f),!0}registerPlannedSession($,f,J){if(this.sessionCapabilities.set($,f),J.size>0)this.sessionClientContributionHandlers.set($,J);this.ensureSessionSubscription($)}cleanupPlannedSession($){this.sessionCapabilities.delete($),this.sessionClientContributionHandlers.delete($),this.disposeSessionSubscription($)}async connect(){await this.client.connect()}async startSession($){let f=this.resolveCapabilities($),J=Nj($.localRuntime,f),Q=$.config.sessionId?.trim()||Lj(),Z=()=>this.client.command("session.create",{workspaceRoot:$.config.workspaceRoot?.trim()||$.config.cwd,cwd:$.config.cwd,sessionConfig:e1({...$.config,sessionId:Q}),metadata:{...$.sessionMetadata??{},source:$.source??F0.CORE,provider:$.config.providerId,model:$.config.modelId,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,teamName:$.config.teamName,prompt:$.prompt,interactive:$.interactive===!0},runtimeOptions:{...J.manifest.length>0?{clientContributions:J.manifest}:{},...$.localRuntime?.configExtensions?{configExtensions:$.localRuntime.configExtensions}:{}},toolPolicies:e1($.toolPolicies),initialMessages:$.initialMessages});this.registerPlannedSession(Q,f,J.handlers);let W;try{W=await Z()}catch(Y){if(this.cleanupPlannedSession(Q),await this.recoverLocalHubStartupDeadlock(Y)){this.registerPlannedSession(Q,f,J.handlers);try{W=await Z()}catch(V){throw this.cleanupPlannedSession(Q),V}}else throw Y}let j=I$(W.payload?.snapshot),X=W.payload?.session,H=(j?.sessionId??X?.sessionId)?.trim();if(!H)throw this.cleanupPlannedSession(Q),Error("Hub runtime did not return a session id.");if(H!==Q)this.cleanupPlannedSession(Q),this.registerPlannedSession(H,f,J.handlers);return{sessionId:H,manifest:j?qj(j,$):Mj(H,$,X),manifestPath:"",messagesPath:"",result:void 0}}async restoreSession($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.start)throw Error("start is required when restore.messages is true");let Q=$.start,Z=Q?this.resolveCapabilities(Q):void 0,W=Q?Nj(Q.localRuntime,Z??{}):{manifest:[],handlers:new Map},j=Q?Q.config.sessionId?.trim()||Lj():void 0;if(j&&Z)this.sessionCapabilities.set(j,Z);if(j&&W.handlers.size>0)this.sessionClientContributionHandlers.set(j,W.handlers),this.ensureSessionSubscription(j);let X;try{X=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.config.workspaceRoot?.trim()||Q.config.cwd,cwd:Q.config.cwd??$.cwd,sessionConfig:e1({...Q.config,sessionId:j}),metadata:{...Q.sessionMetadata??{},source:Q.source??F0.CORE,provider:Q.config.providerId,model:Q.config.modelId,enableTools:Q.config.enableTools,enableSpawn:Q.config.enableSpawnAgent,enableTeams:Q.config.enableAgentTeams,teamName:Q.config.teamName,prompt:Q.prompt,interactive:Q.interactive===!0},runtimeOptions:{...W.manifest.length>0?{clientContributions:W.manifest}:{},...Q.localRuntime?.configExtensions?{configExtensions:Q.localRuntime.configExtensions}:{}},toolPolicies:e1(Q.toolPolicies)}:{}},f)}catch(G){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw G}if(!X.ok){let G=typeof X.payload?.error==="string"?X.payload.error:"session.restore failed";if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error(G)}let H=I$(X.payload?.snapshot),Y=X.payload?.session,V=(H?.sessionId??Y?.sessionId)?.trim();if(J&&!V){if(j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);throw Error("Hub checkpoint restore returned no session id")}if(V&&j&&V!==j)this.sessionCapabilities.delete(j),this.sessionClientContributionHandlers.delete(j),this.disposeSessionSubscription(j);if(V&&Z)this.sessionCapabilities.set(V,Z);if(V&&W.handlers.size>0)this.sessionClientContributionHandlers.set(V,W.handlers);if(V)this.ensureSessionSubscription(V);let A=Array.isArray(X.payload?.messages)?X.payload.messages:void 0,B=X.payload?.checkpoint;if(!B)throw Error("Hub checkpoint restore returned no checkpoint");return{sessionId:V,startResult:V?{sessionId:V,manifest:H?qj(H,Q??{}):Mj(V,Q??{},Y),manifestPath:"",messagesPath:"",result:void 0}:void 0,messages:A,checkpoint:B}}async runTurn($){return this.ensureSessionSubscription($.sessionId),(await this.client.command("run.start",{sessionId:$.sessionId,input:$.prompt,mode:$.mode,attachments:($.userImages?.length??0)>0||($.userFiles?.length??0)>0?{...$.userImages?.length?{userImages:$.userImages}:{},...$.userFiles?.length?{userFiles:$.userFiles}:{}}:void 0,delivery:$.delivery,timeoutMs:$.timeoutMs},$.sessionId,{timeoutMs:null})).payload?.result}async requestPendingPromptsList($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.pending_prompts",{sessionId:$.sessionId},$.sessionId);return Array.isArray(f.payload?.prompts)?f.payload.prompts:[]}async requestPendingPromptUpdate($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.update_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,updated:f.payload?.updated===!0}}async requestPendingPromptDelete($){this.ensureSessionSubscription($.sessionId);let f=await this.client.command("session.remove_pending_prompt",{...$},$.sessionId);return{sessionId:$.sessionId,prompts:Array.isArray(f.payload?.prompts)?f.payload.prompts:[],prompt:f.payload?.prompt,removed:f.payload?.removed===!0}}async getAccumulatedUsage($){let f=await this.client.command("session.get",{includeSnapshot:!0},$),J=I$(f.payload?.snapshot);if(J){let j=J.usage?{...J.usage}:void 0,X=J.aggregateUsage?{...J.aggregateUsage}:void 0;return j||X?{usage:j,aggregateUsage:X}:void 0}let Q=f.payload?.session,Z=Tj(Q?.usage),W=Tj(Q?.aggregateUsage);return Z||W?{usage:Z,aggregateUsage:W}:void 0}async abort($,f){await this.client.command("run.abort",{sessionId:$,reason:yj(f)},$)}async stopSession($){this.sessionCapabilities.delete($),this.disposeSessionSubscription($),await this.client.command("session.detach",{sessionId:$},$)}async dispose(){for(let[$,f]of this.sessionSubscriptions){f();try{await this.client.command("session.detach",{sessionId:$},$)}catch{}}this.sessionSubscriptions.clear(),this.sessionCapabilities.clear(),this.agentDoneEmittedForCurrentRunBySession.clear();for(let $ of this.activeCapabilityAbortControllers.values())$.abort("Hub runtime host disposed.");this.activeCapabilityAbortControllers.clear(),await this.client.dispose()}async getSession($){let f=await this.client.command("session.get",void 0,$);return tR(f.payload)}async listSessions($=100){let f=await this.client.command("session.list",{limit:$}),J=Array.isArray(f.payload?.snapshots)?f.payload.snapshots.flatMap((Z)=>{let W=I$(Z);return W?[o5(W)]:[]}):[];if(J.length>0)return J;return(f.payload?.sessions??[]).map(wj)}async listSettings($){let f=await this.client.command("settings.list",zj($));if(!f.ok)throw Error(X6(f,"settings.list"));return f.payload?.snapshot}async toggleSetting($){let f=await this.client.command("settings.toggle",zj($));if(!f.ok)throw Error(X6(f,"settings.toggle"));return{snapshot:f.payload?.snapshot,changedTypes:Array.isArray(f.payload?.changedTypes)?f.payload.changedTypes:[]}}async deleteSession($){return this.sessionCapabilities.delete($),this.disposeSessionSubscription($),(await this.client.command("session.delete",{sessionId:$})).payload?.deleted===!0}async updateSession($,f){let J={...f.metadata??{}};if(typeof f.prompt==="string")J.prompt=f.prompt;if(typeof f.title==="string")J.title=f.title;return{updated:(await this.client.command("session.update",{sessionId:$,metadata:J})).ok}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Rj(this.telemetry,{component:"core",operation:"hub.runtime_host.read_session_messages",error:Error(X6(J,"session.messages")),severity:J.error?.code==="session_not_found"?"warn":"error",handled:!0,context:{command:"session.messages",sessionId:f,errorCode:J.error?.code,runtimeAddress:this.runtimeAddress}}),Error(X6(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async dispatchHookEvent($){await this.client.command("session.hook",{payload:$})}subscribe($,f){return this.events.subscribe($,f)}ensureSessionSubscription($){let f=$.trim();if(!f||this.sessionSubscriptions.has(f))return;let J=this.client.subscribe((Q)=>{this.handleHubEvent(Q)},{sessionId:f});this.sessionSubscriptions.set(f,typeof J==="function"?J:()=>{})}disposeSessionSubscription($){let f=$.trim();if(!f)return;this.sessionSubscriptions.get(f)?.(),this.sessionSubscriptions.delete(f),this.agentDoneEmittedForCurrentRunBySession.delete(f)}resolveCapabilities($){return P0(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:aR($.payload)}})}handleHubEvent($){let f=$.sessionId?.trim();if($.event==="capability.requested"){this.handleCapabilityRequest($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_request",J,$)});return}if($.event==="capability.resolved"){this.handleCapabilityResolved($);return}if($.event==="approval.requested"){this.handleApprovalRequested($).catch((J)=>{this.captureDetachedHubEventError("hub.runtime_host.approval_request",J,$)});return}if(!f)return;switch($.event){case"run.started":{this.agentDoneEmittedForCurrentRunBySession.delete(f);let J=I$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"iteration.started":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_start",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0}}});return}case"iteration.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"iteration_end",iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,hadToolCalls:$.payload?.hadToolCalls===!0,toolCallCount:typeof $.payload?.toolCallCount==="number"?$.payload.toolCallCount:0}}});return}case"assistant.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"";if(!J)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"text",text:J}}});return}case"assistant.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"text",text:typeof $.payload?.text==="string"?$.payload.text:void 0}}});return}case"reasoning.delta":{let J=typeof $.payload?.text==="string"?$.payload.text:"",Q=$.payload?.redacted===!0;if(!J&&!Q)return;this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_start",contentType:"reasoning",reasoning:J,redacted:Q}}});return}case"reasoning.finished":{this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"reasoning",reasoning:typeof $.payload?.reasoning==="string"?$.payload.reasoning:void 0}}});return}case"agent.done":{this.emitAgentDoneIfNeeded({sessionId:f,payload:$.payload});return}case"usage.updated":{let J=nR($.payload);this.events.emit({type:"agent_event",payload:{sessionId:f,event:J.event,teamAgentId:J.teamAgentId,teamRole:J.teamRole}});return}case"tool.started":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J&&this.pendingApprovalToolCallIds.delete(J))return;this.emitToolCallContentStart({sessionId:f,toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,toolInput:$.payload?.input});return}case"tool.finished":{let J=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:void 0;if(J)this.pendingApprovalToolCallIds.delete(J);this.events.emit({type:"agent_event",payload:{sessionId:f,event:{type:"content_end",contentType:"tool",toolCallId:J,toolName:typeof $.payload?.toolName==="string"?$.payload.toolName:void 0,output:$.payload?.output,error:typeof $.payload?.error==="string"?$.payload.error:void 0}}});return}case"session.created":case"session.updated":case"session.attached":case"session.detached":{let J=I$($.payload?.snapshot),Q=$.payload?.session;if(J)this.events.emit({type:"session_snapshot",payload:{sessionId:f,snapshot:J}});this.events.emit({type:"status",payload:{sessionId:f,status:Q?.status??"running"}});return}case"session.pending_prompts":{this.events.emit({type:"pending_prompts",payload:{sessionId:f,prompts:Array.isArray($.payload?.prompts)?$.payload.prompts:[]}});return}case"session.pending_prompt_submitted":{let J=$.payload?.prompt;if(!J)return;this.events.emit({type:"pending_prompt_submitted",payload:{sessionId:f,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}});return}case"run.completed":case"run.failed":case"run.aborted":{let J=I$($.payload?.snapshot),Q=typeof $.payload?.reason==="string"?$.payload.reason:$.event==="run.aborted"?"aborted":$.event==="run.failed"?"error":"completed";if(this.emitAgentDoneIfNeeded({sessionId:f,payload:{...$.payload,reason:Q}}),J?.interactive===!0&&f0(J.status))return;this.events.emit({type:"ended",payload:{sessionId:f,reason:Q,ts:$.timestamp??Date.now()}});return}default:return}}captureDetachedHubEventError($,f,J){try{Rj(this.telemetry,{component:"core",operation:$,error:f,severity:"warn",handled:!0,context:{event:J.event,sessionId:J.sessionId,runtimeAddress:this.runtimeAddress}})}catch{}}async handleCapabilityRequest($){let f=$.sessionId?.trim();if(!f)return;let J=typeof $.payload?.targetClientId==="string"?$.payload.targetClientId:void 0;if(J&&J!==this.client.getClientId())return;let Q=typeof $.payload?.requestId==="string"?$.payload.requestId:"",Z=typeof $.payload?.capabilityName==="string"?$.payload.capabilityName:"";if(!Q)return;let W=this.sessionClientContributionHandlers.get(f)?.get(Z);if(!W){await this.client.command("capability.respond",{requestId:Q,ok:!1,error:`No client contribution handler registered for capability ${Z} in session ${f}.`},f).catch(()=>{});return}let j=$.payload?.payload&&typeof $.payload.payload==="object"&&!Array.isArray($.payload.payload)?$.payload.payload:{},X=new AbortController;this.activeCapabilityAbortControllers.set(Q,X);let H=(Y)=>{this.client.command("capability.progress",{requestId:Q,payload:Y},f).catch((V)=>{this.captureDetachedHubEventError("hub.runtime_host.capability_progress",V,$)})};try{let Y=await W({payload:j,abortSignal:X.signal,progress:H});if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!0,payload:Y},f)}catch(Y){if(X.signal.aborted)return;await this.client.command("capability.respond",{requestId:Q,ok:!1,error:Y instanceof Error?Y.message:String(Y)},f)}finally{this.activeCapabilityAbortControllers.delete(Q)}}handleCapabilityResolved($){if($.payload?.cancelled!==!0)return;let f=typeof $.payload.requestId==="string"?$.payload.requestId.trim():"";if(!f)return;let J=this.activeCapabilityAbortControllers.get(f);if(!J)return;J.abort(lR($.payload.error))}async handleApprovalRequested($){let f=$.sessionId?.trim();if(!f)return;let J=this.sessionCapabilities.get(f)?.requestToolApproval??this.defaultCapabilities.requestToolApproval;if(!J)return;let Q=typeof $.payload?.approvalId==="string"?$.payload.approvalId.trim():"",Z=typeof $.payload?.toolCallId==="string"?$.payload.toolCallId:"",W=typeof $.payload?.toolName==="string"?$.payload.toolName:"";if(!Q||!Z||!W)return;let j=$.payload?.policy&&typeof $.payload.policy==="object"&&!Array.isArray($.payload.policy)?$.payload.policy:{autoApprove:!1},X=pR($.payload?.inputJson);this.pendingApprovalToolCallIds.add(Z),this.emitToolCallContentStart({sessionId:f,toolCallId:Z,toolName:W,toolInput:X});let H=await Promise.resolve(J({sessionId:f,agentId:typeof $.payload?.agentId==="string"?$.payload.agentId:"",conversationId:typeof $.payload?.conversationId==="string"?$.payload.conversationId:f,iteration:typeof $.payload?.iteration==="number"?$.payload.iteration:0,toolCallId:Z,toolName:W,input:X,policy:j})).catch((Y)=>({approved:!1,reason:Y instanceof Error?Y.message:`Tool approval request failed: ${String(Y)}`}));await this.client.command("approval.respond",{approvalId:Q,approved:H.approved,reason:H.reason},f).catch(()=>{})}}class H6 extends P1{constructor($){super({url:o1($.endpoint),authToken:$.authToken,clientType:$.clientType??"core-remote-runtime",displayName:$.displayName??"core remote runtime",capabilities:$.capabilities},{workspaceRoot:$.workspaceRoot,cwd:$.cwd})}}import{existsSync as sR,mkdirSync as oR}from"node:fs";import{join as eR}from"node:path";import{asBool as X8,asOptionalString as a0,asString as H$,ensureSessionSchema as $L,loadSqliteDb as fL,nowIso as Y6,toBoolInt as H8}from"@cline/shared/db";import{resolveDbDataDir as JL}from"@cline/shared/storage";class x${sessionsDirPath;db;constructor($={}){this.sessionsDirPath=$.sessionsDir??JL()}init(){this.getRawDb()}ensureSessionsDir(){if(!sR(this.sessionsDirPath))oR(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}sessionDbPath(){return eR(this.ensureSessionsDir(),"sessions.db")}getRawDb(){if(this.db)return this.db;let $=fL(this.sessionDbPath());return $L($,{includeLegacyMigrations:!0}),this.db=$,$}close(){this.db?.close?.(),this.db=void 0}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}create($){let f=Y6();this.run(`INSERT OR REPLACE INTO sessions (
440
440
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
441
441
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
442
442
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
443
443
  metadata_json, transcript_path, hook_path, messages_path, updated_at
444
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,W2($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,W2($.enableTools),W2($.enableSpawn),W2($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,W2($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,f])}update($){let f=[],J=[];if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId);if(f.length===0)return;f.push("updated_at = ?"),J.push(f4()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:f==="running"?null:f4(),exitCode:f==="running"?null:J??(f==="failed"?1:0)})}get($){let f=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
444
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,0,H8($.interactive),$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,H8($.enableTools),H8($.enableSpawn),H8($.enableTeams),$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,H8($.isSubagent),$.prompt??null,$.metadata?JSON.stringify($.metadata):null,"",$.hookPath??"",$.messagesPath??null,f])}update($){let f=[],J=[];if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push($.metadata?JSON.stringify($.metadata):null);if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId);if(f.length===0)return;f.push("updated_at = ?"),J.push(Y6()),J.push($.sessionId),this.run(`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`,J)}updateStatus($,f,J){this.update({sessionId:$,status:f,endedAt:f0(f)?null:Y6(),exitCode:f0(f)?null:J??(f==="failed"?1:0)})}get($){let f=this.queryOne(`SELECT session_id, source, pid, started_at, ended_at, exit_code, status, interactive,
445
445
  provider, model, cwd, workspace_root, team_name,
446
446
  enable_tools, enable_spawn, enable_teams,
447
447
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent,
448
448
  prompt, metadata_json, hook_path, messages_path, updated_at
449
- FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:H$(f.session_id),source:H$(f.source),pid:Number(f.pid??0),startedAt:H$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:H$(f.status),interactive:Z2(f.interactive),provider:H$(f.provider),model:H$(f.model),cwd:H$(f.cwd),workspaceRoot:H$(f.workspace_root),teamName:a0(f.team_name),enableTools:Z2(f.enable_tools),enableSpawn:Z2(f.enable_spawn),enableTeams:Z2(f.enable_teams),parentSessionId:a0(f.parent_session_id),parentAgentId:a0(f.parent_agent_id),agentId:a0(f.agent_id),conversationId:a0(f.conversation_id),isSubagent:Z2(f.is_subagent),prompt:a0(f.prompt),metadata:(()=>{let J=a0(f.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:a0(f.hook_path),messagesPath:a0(f.messages_path),updatedAt:a0(f.updated_at)??f4()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let Q of f){let Z=this.get(H$(Q.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}J4();import{existsSync as f9,mkdirSync as WL,readFileSync as _j,renameSync as jL,writeFileSync as XL}from"node:fs";import{join as yj}from"node:path";import{resolveSessionDataDir as HL}from"@cline/shared/storage";import{dirname as QL}from"node:path";import{nanoid as ZL}from"nanoid";import{execFile as SU}from"node:child_process";import{promisify as CU}from"node:util";var EU=CU(SU);function c5($,f){$?.log(f,{severity:"warn"})}function hU($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let Q=J.latest,Z=J.history.filter((W)=>!!W&&typeof W==="object"&&typeof W.ref==="string"&&typeof W.createdAt==="number"&&typeof W.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:Z}}async function F1($,f){let J=await EU("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function u5($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:Q}=await F1($,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
450
- `).filter(Boolean);await Promise.allSettled(Z.map((W)=>F1($,["update-ref","-d",W])))}catch{}}async function Bj($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((Q)=>F1($,["update-ref",`refs/cline/checkpoints/${f}/${Q.runCount}`,Q.ref])))}function bU($,f){let J=$.findIndex((Q)=>Q.runCount===f.runCount);if(J<0)return[...$,f];return $.map((Q,Z)=>Z===J?f:Q)}function Kj($){let f=$.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await F1($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await Q())return;let W=async(Y)=>{try{let A=(await F1($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!A)return;return{ref:A,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(V){c5($.logger,`${Y}: ${V instanceof Error?V.message:String(V)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await F1($.cwd,["stash","create",j])).stdout.trim()}catch(Y){return c5($.logger,`Checkpoint snapshot failed: ${Y instanceof Error?Y.message:String(Y)}`),W("Checkpoint HEAD fallback failed")}if(!X)return W("Checkpoint HEAD fallback failed");let H=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await F1($.cwd,["update-ref",H,X])}catch(Y){c5($.logger,`Checkpoint store failed: ${Y instanceof Error?Y.message:String(Y)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),H=hU(X);if(H?.latest.ref===j.ref)return;let Y=bU(H?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:Y}});return}}}import{existsSync as Z4,mkdirSync as kU,readdirSync as IU,rmdirSync as xU,rmSync as gU,unlinkSync as mU}from"node:fs";import{dirname as Gj,join as Q4}from"node:path";function n(){return new Date().toISOString()}function j2($){if(!$||!Z4($))return;try{mU($)}catch{}}function vU($){let f=af($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=r8($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class d5{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return Q4(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!Z4(f))kU(f,{recursive:!0});return f}sessionMessagesPath($){return Q4(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return Q4(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!Z4(f)){f=Gj(f);continue}try{if(IU(f).length>0)break;xU(f)}catch{break}f=Gj(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!Z4($))return;try{gU($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:Q,fileStem:Z}=vU($),W=this.sessionArtifactsDir(Q);return{messagesPath:Q4(W,`${Z}.messages.json`)}}}import{appendFileSync as cU,existsSync as uU,mkdirSync as Pj,readFileSync as dU,writeFileSync as Fj}from"node:fs";import{dirname as Dj,join as lU}from"node:path";import{ensureHookLogDir as pU}from"@cline/shared/storage";class l5{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new d5(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){_W(f,J,z5($))}writeSessionManifest($,f){Pj(Dj($),{recursive:!0}),Fj($,`${JSON.stringify(O0.parse(f),null,2)}
451
- `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!uU(f))return{path:f};try{return{path:f,manifest:O0.parse(JSON.parse(dU(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let Q=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=_5({updatedAt:n(),context:z5($),messages:f,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
452
- `;if(Pj(Dj(Q),{recursive:!0}),Fj(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??lU(pU(),"hooks.jsonl");cU(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:f,pid:J,source:Z})}
453
- `,"utf8")}}import{appendFileSync as rU}from"node:fs";import{join as iU}from"node:path";import{resolveRootSessionId as Rj}from"@cline/shared";import{ensureHookLogDir as nU}from"@cline/shared/storage";import{z as p5}from"zod";var aU="subagent",tU=p5.looseObject({task:p5.string().optional(),systemPrompt:p5.string().optional()});class W4{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,Q){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:aU,pid:process.ppid,startedAt:f.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:sf({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=Rj($.sessionContext);if(!f)return;let J=tU.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let Q=p8(f,$.agentId),Z=await this.adapter.getSession(Q),W=n(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:sf({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=Rj($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=p8(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,R5(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let Q=f==="running"?null:n(),Z=f==="running"?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,f)}async onTeamTaskStart($,f,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=D5($,f),W=n(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let X=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(X)??[];H.push(Z),this.teamTaskSessionsByAgent.set(X,H)}async onTeamTaskEnd($,f,J,Q,Z,W){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let H=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!H)return;let Y=Z?.messages??W,V=this.toPersistedMessages(Y,Z,W);if(V)await this.manifestStore.persistSessionMessages(H,V);await this.applySubagentStatusBySessionId(H,J),this.teamTaskLastHeartbeatBySession.delete(H),this.teamTaskLastProgressLineBySession.delete(H)}async onTeamTaskProgress($,f,J,Q){let Z=this.teamTaskQueueKey($,f),W=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!W)return;let j=J.trim();if(!j)return;let X=Q?.kind??"progress";if(X==="heartbeat"){let Y=Date.now(),V=this.teamTaskLastHeartbeatBySession.get(W)??0;if(Y-V<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,Y)}let H=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===H)return;this.teamTaskLastProgressLineBySession.set(W,H)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??iU(nU(),"hooks.jsonl");rU(J,`${JSON.stringify({ts:n(),...$})}
454
- `,"utf8")}}import{formatUserInputBlock as JL}from"@cline/shared";function t0(){return new Date().toISOString()}function Uj($,f){if(f<=0)return 0;return Math.round($/f*100)}function sU($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let W of Z.requiredSections)if(!J.has(`${Z.id}:${W}`))Q.add(`${Z.id}:${W}`)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function j4($,f){let J={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},W={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,H=0;for(let F of f.members)if(J[F.status]+=1,F.role==="lead")X+=1;else H+=1;let Y=[],V=[],A=f.tasks.filter((F)=>F.status==="completed").length,B=new Map(f.tasks.map((F)=>[F.id,F]));for(let F of f.tasks){if(Q[F.status]+=1,F.status==="blocked"){Y.push(F.id);continue}if(F.status!=="pending")continue;if(F.dependsOn.every((D)=>{return B.get(D)?.status==="completed"}))V.push(F.id)}let K=[],G,R=0;for(let F of f.runs){if(Z[F.status]+=1,F.status==="queued"||F.status==="running")K.push(F.id);let P=F.startedAt.getTime();if(P>=R)R=P,G=F.id}for(let F of f.outcomes)W[F.status]+=1;for(let F of f.outcomeFragments)j[F.status]+=1;return{teamName:$,updatedAt:t0(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:H},tasks:{total:f.tasks.length,byStatus:Q,blockedTaskIds:Y,readyTaskIds:V,completionPct:Uj(A,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:K,latestRunId:G},outcomes:{total:f.outcomes.length,byStatus:W,finalizedPct:Uj(W.finalized,f.outcomes.length),missingRequiredSections:sU(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function X4($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.task.id,agentId:f.task.assignee??f.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0()}}import{sanitizeFileName as oU,TeamMessageType as S}from"@cline/shared";import{nanoid as eU}from"nanoid";import{TeamMessageType as Pb}from"@cline/shared";function r5($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function Lj($,f){return $?.status==="stopped"&&r5(f)}var $L=600000,Oj="recovered_queued";function fL($){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.
455
-
456
- ${$.message}`}class i5{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,Q]of Object.entries($))this.addAgent(J,Q)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:S.AgentEvent,agentId:$,event:Z})}},Q=new N$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set($,Q),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Q=await J.run(f);return this.emitEvent({type:S.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:S.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Q=await J.continue(f);return this.emitEvent({type:S.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:S.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async runParallel($){let f=$.map(async(J)=>{let Q=this.agents.get(J.agentId);if(!Q)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:S.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);return this.emitEvent({type:S.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:S.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),{agentId:J.agentId,result:void 0,error:W,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let Q=this.agents.get(J.agentId);if(!Q){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:S.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);this.emitEvent({type:S.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:S.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return f}async runPipeline($,f,J){let Q=[],Z=f;for(let W of $){let j=this.agents.get(W);if(!j){Q.push({agentId:W,result:void 0,error:Error(`Agent "${W}" not found in team`)});break}this.emitEvent({type:S.TaskStart,agentId:W,message:Z});try{let X=await j.run(Z);this.emitEvent({type:S.TaskEnd,agentId:W,result:X}),Q.push({agentId:W,result:X});let H=$.indexOf(W)+1;if(H<$.length){let Y=$[H];Z=J?J(X,Y):`Previous agent output:
449
+ FROM sessions WHERE session_id = ?`,[$]);if(!f)return;return{sessionId:H$(f.session_id),source:H$(f.source),pid:Number(f.pid??0),startedAt:H$(f.started_at),endedAt:f.ended_at??null,exitCode:f.exit_code??null,status:H$(f.status),interactive:X8(f.interactive),provider:H$(f.provider),model:H$(f.model),cwd:H$(f.cwd),workspaceRoot:H$(f.workspace_root),teamName:a0(f.team_name),enableTools:X8(f.enable_tools),enableSpawn:X8(f.enable_spawn),enableTeams:X8(f.enable_teams),parentSessionId:a0(f.parent_session_id),parentAgentId:a0(f.parent_agent_id),agentId:a0(f.agent_id),conversationId:a0(f.conversation_id),isSubagent:X8(f.is_subagent),prompt:a0(f.prompt),metadata:(()=>{let J=a0(f.metadata_json);if(!J)return;try{let Q=JSON.parse(J);if(Q&&typeof Q==="object"&&!Array.isArray(Q))return Q}catch{}return})(),hookPath:a0(f.hook_path),messagesPath:a0(f.messages_path),updatedAt:a0(f.updated_at)??Y6()}}list($=200){let f=this.queryAll("SELECT session_id FROM sessions ORDER BY started_at DESC LIMIT ?",[$]),J=[];for(let Q of f){let Z=this.get(H$(Q.session_id));if(Z)J.push(Z)}return J}delete($,f=!1){let J=this.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}}V6();import{existsSync as K9,mkdirSync as lL,readFileSync as uj,renameSync as pL,writeFileSync as rL}from"node:fs";import{join as cj}from"node:path";import{resolveSessionDataDir as iL}from"@cline/shared/storage";import{dirname as cL}from"node:path";import{nanoid as dL}from"nanoid";import{execFile as FL}from"node:child_process";import{promisify as PL}from"node:util";var UL=PL(FL);function $9($,f){$?.log(f,{severity:"warn"})}function DL($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))return;let J=f;if(!J.latest||!Array.isArray(J.history))return;let Q=J.latest,Z=J.history.filter((W)=>!!W&&typeof W==="object"&&typeof W.ref==="string"&&typeof W.createdAt==="number"&&typeof W.runCount==="number");if(typeof Q.ref!=="string"||typeof Q.createdAt!=="number"||typeof Q.runCount!=="number")return;return{latest:Q,history:Z}}async function D1($,f){let J=await UL("git",["-C",$,...f],{windowsHide:!0});return{stdout:J.stdout.trim(),stderr:J.stderr.trim()}}async function f9($,f){if(!$)return;let J=`refs/cline/checkpoints/${f}/`;try{let{stdout:Q}=await D1($,["for-each-ref","--format=%(refname)",J]),Z=Q.trim().split(`
450
+ `).filter(Boolean);await Promise.allSettled(Z.map((W)=>D1($,["update-ref","-d",W])))}catch{}}async function Sj($,f,J){if(!$||J.length===0)return;await Promise.allSettled(J.map((Q)=>D1($,["update-ref",`refs/cline/checkpoints/${f}/${Q.runCount}`,Q.ref])))}function RL($,f){let J=$.findIndex((Q)=>Q.runCount===f.runCount);if(J<0)return[...$,f];return $.map((Q,Z)=>Z===J?f:Q)}function hj($){let f=$.initialRunCount??0,J,Q=async()=>{if(J!==void 0)return J;try{J=(await D1($.cwd,["rev-parse","--is-inside-work-tree"])).stdout==="true"}catch{J=!1}return J},Z=async()=>{if($.createCheckpoint)return await $.createCheckpoint({cwd:$.cwd,sessionId:$.sessionId,runCount:f});if(!await Q())return;let W=async(Y)=>{try{let A=(await D1($.cwd,["rev-parse","HEAD"])).stdout.trim();if(!A)return;return{ref:A,createdAt:Date.now(),runCount:f,kind:"commit"}}catch(V){$9($.logger,`${Y}: ${V instanceof Error?V.message:String(V)}`);return}},j=`cline checkpoint session=${$.sessionId} run=${f}`,X="";try{X=(await D1($.cwd,["stash","create",j])).stdout.trim()}catch(Y){return $9($.logger,`Checkpoint snapshot failed: ${Y instanceof Error?Y.message:String(Y)}`),W("Checkpoint HEAD fallback failed")}if(!X)return W("Checkpoint HEAD fallback failed");let H=`refs/cline/checkpoints/${$.sessionId}/${f}`;try{await D1($.cwd,["update-ref",H,X])}catch(Y){$9($.logger,`Checkpoint store failed: ${Y instanceof Error?Y.message:String(Y)}`);return}return{ref:X,createdAt:Date.now(),runCount:f,kind:"stash"}};return{beforeRun:async({snapshot:W})=>{if(W.parentAgentId!=null)return;f+=1;return},beforeModel:async({snapshot:W})=>{if(W.parentAgentId!=null||W.iteration!==1||f<1)return;let j=await Z();if(!j)return;let X=await $.readSessionMetadata(),H=DL(X);if(H?.latest.ref===j.ref)return;let Y=RL(H?.history??[],j);await $.writeSessionMetadata({...X??{},checkpoint:{latest:j,history:Y}});return}}}import{existsSync as B6,mkdirSync as LL,readdirSync as OL,rmdirSync as zL,rmSync as _L,unlinkSync as NL}from"node:fs";import{dirname as Cj,join as A6}from"node:path";function n(){return new Date().toISOString()}function Y8($){if(!$||!B6($))return;try{NL($)}catch{}}function TL($){let f=o2($);if(f)return{rootSessionId:f.rootSessionId,fileStem:`${f.agentId}__${f.teamTaskId}`};let J=$6($);if(J)return{rootSessionId:J.rootSessionId,fileStem:J.agentId};return{rootSessionId:$,fileStem:$}}class J9{ensureSessionsDir;constructor($){this.ensureSessionsDir=$}sessionArtifactsDir($){return A6(this.ensureSessionsDir(),$)}ensureSessionArtifactsDir($){let f=this.sessionArtifactsDir($);if(!B6(f))LL(f,{recursive:!0});return f}sessionMessagesPath($){return A6(this.sessionArtifactsDir($),`${$}.messages.json`)}sessionManifestPath($,f=!1){let J=f?this.ensureSessionArtifactsDir($):this.sessionArtifactsDir($);return A6(J,`${$}.json`)}removeSessionDirIfEmpty($){let f=this.sessionArtifactsDir($),J=this.ensureSessionsDir();while(f.startsWith(J)&&f!==J){if(!B6(f)){f=Cj(f);continue}try{if(OL(f).length>0)break;zL(f)}catch{break}f=Cj(f)}}removeSessionDir($){this.removeDir(this.sessionArtifactsDir($))}removeDir($){if(!B6($))return;try{_L($,{recursive:!0,force:!0})}catch{}}subagentArtifactPaths($,f,J){let{rootSessionId:Q,fileStem:Z}=TL($),W=this.sessionArtifactsDir(Q);return{messagesPath:A6(W,`${Z}.messages.json`)}}}import{appendFileSync as ML,existsSync as qL,mkdirSync as Ej,readFileSync as yL,writeFileSync as bj}from"node:fs";import{dirname as kj,join as wL}from"node:path";import{ensureHookLogDir as SL}from"@cline/shared/storage";class Q9{adapter;messagesArtifactUploader;logger;artifacts;constructor($,f,J){this.adapter=$;this.messagesArtifactUploader=f;this.logger=J;this.artifacts=new J9(()=>this.ensureSessionsDir())}ensureSessionsDir(){return this.adapter.ensureSessionsDir()}initializeMessagesFile($,f,J){gW(f,J,k5($))}writeSessionManifest($,f){Ej(kj($),{recursive:!0}),bj($,`${JSON.stringify(_0.parse(f),null,2)}
451
+ `,"utf8")}readSessionManifest($){return this.readManifestFile($).manifest}readManifestFile($){let f=this.artifacts.sessionManifestPath($,!1);if(!qL(f))return{path:f};try{return{path:f,manifest:_0.parse(JSON.parse(yL(f,"utf8")))}}catch{return{path:f}}}async resolveArtifactPath($,f,J){let Z=(await this.adapter.getSession($))?.[f];return typeof Z==="string"&&Z.trim().length>0?Z:J($)}async persistSessionMessages($,f,J){let Q=await this.resolveArtifactPath($,"messagesPath",(j)=>this.artifacts.sessionMessagesPath(j)),Z=I5({updatedAt:n(),context:k5($),messages:f,systemPrompt:J}),W=`${JSON.stringify(Z,null,2)}
452
+ `;if(Ej(kj(Q),{recursive:!0}),bj(Q,W,"utf8"),!this.messagesArtifactUploader)return;try{let j=await this.adapter.getSession($);await this.messagesArtifactUploader.uploadMessagesFile({sessionId:$,path:Q,contents:W,row:j})}catch(j){this.logger?.debug("Failed to upload persisted session messages",{sessionId:$,error:j})}}appendStaleSessionHookLog($,f,J,Q,Z){let j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??wL(SL(),"hooks.jsonl");ML(j,`${JSON.stringify({ts:$,hookName:"session_shutdown",reason:Q,sessionId:f,pid:J,source:Z})}
453
+ `,"utf8")}}import{appendFileSync as hL}from"node:fs";import{join as CL}from"node:path";import{resolveRootSessionId as Ij}from"@cline/shared";import{ensureHookLogDir as EL}from"@cline/shared/storage";import{z as Z9}from"zod";var bL="subagent",kL=Z9.looseObject({task:Z9.string().optional(),systemPrompt:Z9.string().optional()});class G6{adapter;manifestStore;toPersistedMessages;heartbeatLogIntervalMs;teamTaskSessionsByAgent=new Map;teamTaskLastHeartbeatBySession=new Map;teamTaskLastProgressLineBySession=new Map;constructor($,f,J,Q){this.adapter=$;this.manifestStore=f;this.toPersistedMessages=J;this.heartbeatLogIntervalMs=Q}teamTaskQueueKey($,f){return`${$}::${f}`}activeTeamTaskSessionId($,f){return this.teamTaskSessionsByAgent.get(this.teamTaskQueueKey($,f))?.at(-1)}buildSubsessionRow($,f){return{sessionId:f.sessionId,source:bL,pid:process.ppid,startedAt:f.startedAt,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:!1,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:f.parentSessionId,parentAgentId:f.parentAgentId,agentId:f.agentId,conversationId:f.conversationId??null,isSubagent:!0,prompt:f.prompt,metadata:$8({prompt:f.prompt}),hookPath:"",messagesPath:f.messagesPath,updatedAt:f.startedAt}}async queueSpawnRequest($){if($.hookName!=="tool_call"||$.parent_agent_id!==null)return;if($.tool_call?.name!=="spawn_agent")return;let f=Ij($.sessionContext);if(!f)return;let J=kL.safeParse($.tool_call.input);await this.adapter.enqueueSpawnRequest({rootSessionId:f,parentAgentId:$.agent_id,task:J.success?J.data.task:void 0,systemPrompt:J.success?J.data.systemPrompt:void 0})}async upsertSubagentSession($){let f=$.rootSessionId;if(!f)return;let J=await this.adapter.getSession(f);if(!J)return;let Q=e4(f,$.agentId),Z=await this.adapter.getSession(Q),W=n(),j=this.manifestStore.artifacts.subagentArtifactPaths(Q,$.agentId,this.activeTeamTaskSessionId(f,$.parentAgentId)),X=$.prompt??Z?.prompt??void 0;if(!X)X=await this.adapter.claimSpawnRequest(f,$.parentAgentId)??`Subagent run by ${$.parentAgentId}`;if(!Z)return await this.adapter.upsertSession(this.buildSubsessionRow(J,{sessionId:Q,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:X,startedAt:W,...j})),this.manifestStore.initializeMessagesFile(Q,j.messagesPath,W),Q;return await this.adapter.updateSession({sessionId:Q,setRunning:!0,parentSessionId:f,parentAgentId:$.parentAgentId,agentId:$.agentId,conversationId:$.conversationId,prompt:Z.prompt??X??null,metadata:$8({metadata:Z.metadata??void 0,prompt:Z.prompt??X??null}),expectedStatusLock:Z.statusLock}),Q}async upsertSubagentSessionFromHook($){if(!$.parent_agent_id)return;let f=Ij($.sessionContext);if(!f)return;if($.hookName==="session_shutdown"){let J=e4(f,$.agent_id);return await this.adapter.getSession(J)?J:void 0}return await this.upsertSubagentSession({agentId:$.agent_id,parentAgentId:$.parent_agent_id,conversationId:$.taskId,rootSessionId:f})}async applySubagentStatus($,f){await this.applySubagentStatusBySessionId($,h5(f))}async applySubagentStatusBySessionId($,f){let J=await this.adapter.getSession($);if(!J)return;let Q=f0(f)?null:n(),Z=f0(f)?null:f==="failed"?1:0;await this.adapter.updateSession({sessionId:$,status:f,endedAt:Q,exitCode:Z,expectedStatusLock:J.statusLock})}async applyStatusToRunningChildSessions($,f){if(!$)return;let J=await this.adapter.listSessions({limit:2000,parentSessionId:$,status:"running"});for(let Q of J)await this.applySubagentStatusBySessionId(Q.sessionId,f)}async onTeamTaskStart($,f,J){let Q=await this.adapter.getSession($);if(!Q)return;let Z=S5($,f),W=n(),{messagesPath:j}=this.manifestStore.artifacts.subagentArtifactPaths(Z,f);await this.adapter.upsertSession(this.buildSubsessionRow(Q,{sessionId:Z,parentSessionId:$,parentAgentId:"lead",agentId:f,prompt:J||`Team task for ${f}`,startedAt:W,messagesPath:j})),this.manifestStore.initializeMessagesFile(Z,j,W);let X=this.teamTaskQueueKey($,f),H=this.teamTaskSessionsByAgent.get(X)??[];H.push(Z),this.teamTaskSessionsByAgent.set(X,H)}async onTeamTaskEnd($,f,J,Q,Z,W){let j=this.teamTaskQueueKey($,f),X=this.teamTaskSessionsByAgent.get(j);if(!X||X.length===0)return;let H=X.shift();if(X.length===0)this.teamTaskSessionsByAgent.delete(j);if(!H)return;let Y=Z?.messages??W,V=this.toPersistedMessages(Y,Z,W);if(V)await this.manifestStore.persistSessionMessages(H,V);await this.applySubagentStatusBySessionId(H,J),this.teamTaskLastHeartbeatBySession.delete(H),this.teamTaskLastProgressLineBySession.delete(H)}async onTeamTaskProgress($,f,J,Q){let Z=this.teamTaskQueueKey($,f),W=this.teamTaskSessionsByAgent.get(Z)?.[0];if(!W)return;let j=J.trim();if(!j)return;let X=Q?.kind??"progress";if(X==="heartbeat"){let Y=Date.now(),V=this.teamTaskLastHeartbeatBySession.get(W)??0;if(Y-V<this.heartbeatLogIntervalMs)return;this.teamTaskLastHeartbeatBySession.set(W,Y)}let H=X==="heartbeat"?"[progress] heartbeat":X==="text"?`[progress] text: ${j}`:`[progress] ${j}`;if(this.teamTaskLastProgressLineBySession.get(W)===H)return;this.teamTaskLastProgressLineBySession.set(W,H)}async handleSubAgentStart($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;await this.applySubagentStatusBySessionId(J,"running")}async handleSubAgentEnd($,f){let J=await this.upsertSubagentSession({agentId:f.subAgentId,parentAgentId:f.parentAgentId,conversationId:f.conversationId,prompt:f.input.task,rootSessionId:$});if(!J)return;if(f.error){await this.applySubagentStatusBySessionId(J,"failed");return}let Q=this.toPersistedMessages(f.agentResult?.messages,f.agentResult);if(Q)await this.manifestStore.persistSessionMessages(J,Q);let Z=f.result?.finishReason??"completed";await this.applySubagentStatusBySessionId(J,Z==="aborted"?"cancelled":"completed")}appendSubagentHookAudit($){let J=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??CL(EL(),"hooks.jsonl");hL(J,`${JSON.stringify({ts:n(),...$})}
454
+ `,"utf8")}}import{formatUserInputBlock as uL}from"@cline/shared";function t0(){return new Date().toISOString()}function xj($,f){if(f<=0)return 0;return Math.round($/f*100)}function IL($,f){let J=new Set;for(let Z of f)if(Z.status==="reviewed")J.add(`${Z.outcomeId}:${Z.section}`);let Q=new Set;for(let Z of $){if(Z.status==="finalized")continue;for(let W of Z.requiredSections)if(!J.has(`${Z.id}:${W}`))Q.add(`${Z.id}:${W}`)}return[...Q].sort((Z,W)=>Z.localeCompare(W))}function K6($,f){let J={idle:0,running:0,stopped:0},Q={pending:0,in_progress:0,blocked:0,completed:0},Z={queued:0,running:0,completed:0,failed:0,cancelled:0,interrupted:0},W={draft:0,in_review:0,finalized:0},j={draft:0,reviewed:0,rejected:0},X=0,H=0;for(let F of f.members)if(J[F.status]+=1,F.role==="lead")X+=1;else H+=1;let Y=[],V=[],A=f.tasks.filter((F)=>F.status==="completed").length,B=new Map(f.tasks.map((F)=>[F.id,F]));for(let F of f.tasks){if(Q[F.status]+=1,F.status==="blocked"){Y.push(F.id);continue}if(F.status!=="pending")continue;if(F.dependsOn.every((U)=>{return B.get(U)?.status==="completed"}))V.push(F.id)}let G=[],K,D=0;for(let F of f.runs){if(Z[F.status]+=1,F.status==="queued"||F.status==="running")G.push(F.id);let P=F.startedAt.getTime();if(P>=D)D=P,K=F.id}for(let F of f.outcomes)W[F.status]+=1;for(let F of f.outcomeFragments)j[F.status]+=1;return{teamName:$,updatedAt:t0(),members:{total:f.members.length,byStatus:J,leadCount:X,teammateCount:H},tasks:{total:f.tasks.length,byStatus:Q,blockedTaskIds:Y,readyTaskIds:V,completionPct:xj(A,f.tasks.length)},runs:{total:f.runs.length,byStatus:Z,activeRunIds:G,latestRunId:K},outcomes:{total:f.outcomes.length,byStatus:W,finalizedPct:xj(W.finalized,f.outcomes.length),missingRequiredSections:IL(f.outcomes,f.outcomeFragments)},fragments:{total:f.outcomeFragments.length,byStatus:j}}}function F6($){let{event:f}=$;switch(f.type){case"team_task_updated":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.task.id,agentId:f.task.assignee??f.task.createdBy};case"run_queued":case"run_started":case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.run.error};case"run_progress":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),runId:f.run.id,taskId:f.run.taskId,agentId:f.run.agentId,message:f.message};case"outcome_created":case"outcome_finalized":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),outcomeId:f.outcome.id};case"outcome_fragment_attached":case"outcome_fragment_reviewed":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),outcomeId:f.fragment.outcomeId,fragmentId:f.fragment.id,agentId:f.fragment.sourceAgentId};case"team_message":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.message.taskId,agentId:f.message.fromAgentId,message:f.message.subject};case"team_mission_log":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),taskId:f.entry.taskId,agentId:f.entry.agentId,message:f.entry.summary};case"teammate_spawned":case"teammate_shutdown":case"task_start":case"task_end":case"agent_event":return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0(),agentId:f.agentId}}return{teamName:$.teamName,sessionId:$.sessionId,eventType:f.type,ts:t0()}}import{sanitizeFileName as xL,TeamMessageType as S}from"@cline/shared";import{nanoid as mL}from"nanoid";import{TeamMessageType as Zk}from"@cline/shared";function W9($){if(typeof DOMException<"u"&&$ instanceof DOMException&&$.name==="AbortError")return!0;if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.toLowerCase().includes("aborted")}function mj($,f){return $?.status==="stopped"&&W9(f)}var gL=600000,gj="recovered_queued";function vL($){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.
455
+
456
+ ${$.message}`}class j9{agents=new Map;configs=new Map;onTeamEvent;constructor($,f){if(this.onTeamEvent=f,$)for(let[J,Q]of Object.entries($))this.addAgent(J,Q)}addAgent($,f){if(this.agents.has($))throw Error(`Agent with id "${$}" already exists in the team`);let J={...f,onEvent:(Z)=>{f.onEvent?.(Z),this.emitEvent({type:S.AgentEvent,agentId:$,event:Z})}},Q=new T$(J);if(J.onEvent)Q.subscribeEvents(J.onEvent);this.agents.set($,Q),this.configs.set($,f)}removeAgent($){return this.configs.delete($),this.agents.delete($)}getAgent($){return this.agents.get($)}getAgentIds(){return Array.from(this.agents.keys())}get size(){return this.agents.size}async routeTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Q=await J.run(f);return this.emitEvent({type:S.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:S.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async continueTo($,f){let J=this.agents.get($);if(!J)throw Error(`Agent "${$}" not found in team`);this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Q=await J.continue(f);return this.emitEvent({type:S.TaskEnd,agentId:$,result:Q}),Q}catch(Q){let Z=Q instanceof Error?Q:Error(String(Q));throw this.emitEvent({type:S.TaskEnd,agentId:$,error:Z,messages:J.getMessages()}),Q}}async runParallel($){let f=$.map(async(J)=>{let Q=this.agents.get(J.agentId);if(!Q)return{agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata};this.emitEvent({type:S.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);return this.emitEvent({type:S.TaskEnd,agentId:J.agentId,result:Z}),{agentId:J.agentId,result:Z,metadata:J.metadata}}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));return this.emitEvent({type:S.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),{agentId:J.agentId,result:void 0,error:W,metadata:J.metadata}}});return Promise.all(f)}async runSequential($){let f=[];for(let J of $){let Q=this.agents.get(J.agentId);if(!Q){f.push({agentId:J.agentId,result:void 0,error:Error(`Agent "${J.agentId}" not found in team`),metadata:J.metadata});continue}this.emitEvent({type:S.TaskStart,agentId:J.agentId,message:J.message});try{let Z=await Q.run(J.message);this.emitEvent({type:S.TaskEnd,agentId:J.agentId,result:Z}),f.push({agentId:J.agentId,result:Z,metadata:J.metadata})}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));this.emitEvent({type:S.TaskEnd,agentId:J.agentId,error:W,messages:Q.getMessages()}),f.push({agentId:J.agentId,result:void 0,error:W,metadata:J.metadata})}}return f}async runPipeline($,f,J){let Q=[],Z=f;for(let W of $){let j=this.agents.get(W);if(!j){Q.push({agentId:W,result:void 0,error:Error(`Agent "${W}" not found in team`)});break}this.emitEvent({type:S.TaskStart,agentId:W,message:Z});try{let X=await j.run(Z);this.emitEvent({type:S.TaskEnd,agentId:W,result:X}),Q.push({agentId:W,result:X});let H=$.indexOf(W)+1;if(H<$.length){let Y=$[H];Z=J?J(X,Y):`Previous agent output:
457
457
  ${X.text}
458
458
 
459
- Please continue from here.`}}catch(X){let H=X instanceof Error?X:Error(String(X));this.emitEvent({type:S.TaskEnd,agentId:W,error:H,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:H});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}class X2{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_${oU(eU(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,Q=f?.markRead??!0,Z=f?.limit,W=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let X=new Date;for(let H of j)if(!H.readAt)H.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,s1($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,s1($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,s1($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,s1(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,s1(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,s1(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...f,apiTimeoutMs:$L,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:S.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new N$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,W),this.emitEvent({type:S.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:W.agentId,role:W.role,description:W.description,status:W.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(Q){if(!r5(Q))throw Q}J.status="stopped",this.emitEvent({type:S.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,Q),this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:S.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...Q}}completeTask($,f,J){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=f;return this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...Q}}async routeToTeammate($,f,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
459
+ Please continue from here.`}}catch(X){let H=X instanceof Error?X:Error(String(X));this.emitEvent({type:S.TaskEnd,agentId:W,error:H,messages:j.getMessages()}),Q.push({agentId:W,result:void 0,error:H});break}}return Q}abortAll(){for(let $ of this.agents.values())$.abort(Error("Agent team abortAll requested"))}clear(){this.abortAll(),this.agents.clear(),this.configs.clear()}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}class V8{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_${xL(mL(10))}`,this.onTeamEvent=$.onTeamEvent,this.missionLogIntervalSteps=Math.max(1,$.missionLogIntervalSteps??3),this.missionLogIntervalMs=Math.max(1000,$.missionLogIntervalMs??120000),this.maxConcurrentRuns=Math.max(1,$.maxConcurrentRuns??2);let f=$.leadAgentId??"lead";this.members.set(f,{agentId:f,role:"lead",status:"idle",runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()})}getTeamId(){return this.teamId}getTeamName(){return this.teamName}getMemberRole($){return this.members.get($)?.role}getMemberIds(){return Array.from(this.members.keys())}getTeammateIds(){return Array.from(this.members.values()).filter(($)=>$.role==="teammate").map(($)=>$.agentId)}getTask($){return this.tasks.get($)}listTasks(){return Array.from(this.tasks.values())}listTaskItems($){return Array.from(this.tasks.values()).map((f)=>{let J=this.getUnresolvedDependencies(f);return{...f,blockedBy:J,isReady:f.status==="pending"&&!f.assignee&&J.length===0}}).filter((f)=>{if($?.status&&f.status!==$.status)return!1;if($?.assignee&&f.assignee!==$.assignee)return!1;return!0})}listMissionLog($){if(!$||$<=0)return[...this.missionLog];return this.missionLog.slice(Math.max(0,this.missionLog.length-$))}listMailbox($,f){let J=f?.unreadOnly??!0,Q=f?.markRead??!0,Z=f?.limit,W=this.mailbox.filter((X)=>X.toAgentId===$&&(!J||!X.readAt)),j=typeof Z==="number"&&Z>0?W.slice(Math.max(0,W.length-Z)):W;if(Q){let X=new Date;for(let H of j)if(!H.readAt)H.readAt=X}return j.map((X)=>({...X}))}getSnapshot(){let $={pending:0,in_progress:0,blocked:0,completed:0};for(let J of this.tasks.values())$[J.status]++;let f={draft:0,in_review:0,finalized:0};for(let J of this.outcomes.values())f[J.status]++;return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map((J)=>({agentId:J.agentId,role:J.role,description:J.description,status:J.status})),taskCounts:$,unreadMessages:this.mailbox.filter((J)=>!J.readAt).length,missionLogEntries:this.missionLog.length,activeRuns:Array.from(this.runs.values()).filter((J)=>J.status==="running").length,queuedRuns:Array.from(this.runs.values()).filter((J)=>J.status==="queued").length,outcomeCounts:f}}exportState(){return{teamId:this.teamId,teamName:this.teamName,members:Array.from(this.members.values()).map(($)=>({agentId:$.agentId,role:$.role,description:$.description,status:$.status})),tasks:Array.from(this.tasks.values()).map(($)=>({...$})),mailbox:this.mailbox.map(($)=>({...$})),missionLog:this.missionLog.map(($)=>({...$})),runs:Array.from(this.runs.values()).map(($)=>({...$})),outcomes:Array.from(this.outcomes.values()).map(($)=>({...$})),outcomeFragments:Array.from(this.outcomeFragments.values()).map(($)=>({...$}))}}hydrateState($){this.clearQueuedRunDispatchTimer(),this.tasks.clear();for(let J of $.tasks)this.tasks.set(J.id,{...J});this.mailbox.length=0,this.mailbox.push(...$.mailbox.map((J)=>({...J}))),this.missionLog.length=0,this.missionLog.push(...$.missionLog.map((J)=>({...J}))),this.runs.clear();for(let J of $.runs??[])this.runs.set(J.id,{...J});this.runQueue.length=0,this.runQueue.push(...Array.from(this.runs.values()).filter((J)=>J.status==="queued").map((J)=>J.id)),this.outcomes.clear();for(let J of $.outcomes??[])this.outcomes.set(J.id,{...J});this.outcomeFragments.clear();for(let J of $.outcomeFragments??[])this.outcomeFragments.set(J.id,{...J});let f=Array.from(this.members.values()).filter((J)=>J.role==="lead");this.members.clear();for(let J of f)this.members.set(J.agentId,{...J,status:"idle",runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()});for(let J of $.members){if(J.role!=="teammate")continue;this.members.set(J.agentId,{agentId:J.agentId,role:"teammate",description:J.description,status:"stopped",agent:void 0,runningCount:0,lastMissionStep:this.missionStepCounter,lastMissionAt:Date.now()})}this.taskCounter=Math.max(this.taskCounter,$2($.tasks.map((J)=>J.id),"task_")),this.messageCounter=Math.max(this.messageCounter,$2($.mailbox.map((J)=>J.id),"msg_")),this.missionCounter=Math.max(this.missionCounter,$2($.missionLog.map((J)=>J.id),"log_")),this.runCounter=Math.max(this.runCounter,$2(($.runs??[]).map((J)=>J.id),"run_")),this.outcomeCounter=Math.max(this.outcomeCounter,$2(($.outcomes??[]).map((J)=>J.id),"out_")),this.outcomeFragmentCounter=Math.max(this.outcomeFragmentCounter,$2(($.outcomeFragments??[]).map((J)=>J.id),"frag_"))}isTeammateActive($){let f=this.members.get($);return!!f&&f.role==="teammate"&&!!f.agent}spawnTeammate({agentId:$,config:f}){let J=this.members.get($);if(J&&J.role!=="teammate")throw Error(`Team member "${$}" already exists and is not a teammate`);if(J&&J.runningCount>0)throw Error(`Teammate "${$}" is currently running and cannot be respawned`);let Q={...f,apiTimeoutMs:gL,consumePendingUserMessage:()=>{let j=this.members.get($);if(!j||!j.pendingSteerMessage)return;let X=j.pendingSteerMessage;return j.pendingSteerMessage=void 0,X},onEvent:(j)=>{f.onEvent?.(j),this.emitEvent({type:S.AgentEvent,agentId:$,event:j}),this.trackMeaningfulEvent($,j)}},Z=new T$(Q);if(Q.onEvent)Z.subscribeEvents(Q.onEvent);let W={agentId:$,role:"teammate",description:f.role,status:"idle",agent:Z,runningCount:0,lastMissionStep:0,lastMissionAt:Date.now()};return this.members.set($,W),this.emitEvent({type:S.TeammateSpawned,agentId:$,role:f.role,teammate:{rolePrompt:f.systemPrompt,modelId:f.modelId,maxIterations:f.maxIterations,runtimeAgentId:Z.getAgentId(),conversationId:Z.getConversationId(),parentAgentId:null}}),{agentId:W.agentId,role:W.role,description:W.description,status:W.status}}shutdownTeammate($,f){let J=this.members.get($);if(!J||J.role!=="teammate")throw Error(`Teammate "${$}" was not found`);try{J.agent?.abort()}catch(Q){if(!W9(Q))throw Q}J.status="stopped",this.emitEvent({type:S.TeammateShutdown,agentId:$,reason:f})}updateTeammateConnections($){for(let f of this.members.values()){if(f.role!=="teammate"||!f.agent)continue;f.agent.updateConnection($)}}createTask($){let f=`task_${String(++this.taskCounter).padStart(4,"0")}`,J=new Date,Q={id:f,title:$.title,description:$.description,status:$.assignee?"in_progress":"pending",createdAt:J,updatedAt:J,createdBy:$.createdBy,assignee:$.assignee,dependsOn:$.dependsOn??[]};return this.tasks.set(f,Q),this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),{...Q}}claimTask($,f){let J=this.requireTask($);return this.assertDependenciesResolved(J),J.status="in_progress",J.assignee=f,J.updatedAt=new Date,this.emitEvent({type:S.TeamTaskUpdated,task:{...J}}),this.appendMissionLog({agentId:f,taskId:$,kind:"progress",summary:`Claimed task "${J.title}"`}),{...J}}blockTask($,f,J){let Q=this.requireTask($);return Q.status="blocked",Q.updatedAt=new Date,Q.summary=J,this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"blocked",summary:J}),{...Q}}completeTask($,f,J){let Q=this.requireTask($);if(Q.status="completed",Q.updatedAt=new Date,Q.summary=J,!Q.assignee)Q.assignee=f;return this.emitEvent({type:S.TeamTaskUpdated,task:{...Q}}),this.appendMissionLog({agentId:f,taskId:$,kind:"done",summary:J}),{...Q}}async routeToTeammate($,f,J){let Q=this.members.get($);if(!Q||Q.role!=="teammate"||!Q.agent)throw Error(`Teammate "${$}" was not found`);if(!Q.agent.canStartRun())throw Error("Cannot start a new run while another run is already in progress");Q.runningCount++,Q.status="running",this.emitEvent({type:S.TaskStart,agentId:$,message:f});try{let Z=this.listMailbox($,{unreadOnly:!0,markRead:!0}),W=Z.length>0?`${this.buildMailboxNotification(Z)}
460
460
 
461
- ${f}`:f,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:S.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:S.TaskEnd,agentId:$,error:W,messages:Q.agent.getMessages()}),!Lj(Q,W))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,f,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:S.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>f)f=W.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===Oj;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:S.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=f?fL($):$.message,Z=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:S.RunCompleted,run:{...$}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=Z,$.endedAt=new Date;let W=this.members.get($.agentId);if(Lj(W,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:S.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:S.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await zj(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await zj($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:S.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:S.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=Oj,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:S.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:S.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,Q,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let W=this.members.get(f);if(!W)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:S.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===$)continue;if(W.role==="lead")continue;Z.push(this.sendMessage($,W.agentId,f,J,Q?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:S.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:S.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:S.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:S.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let Q of f.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:S.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!r5(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:S.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${Q}`}recordProgressStep($,f,J,Q=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
462
- `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function zj($){return new Promise((f)=>setTimeout(f,$))}function s1($,f){let J=0;for(let Q of $){if(!Q.startsWith(f))continue;let Z=Number.parseInt(Q.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function n5($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),H4($);break}default:break}}async function a5($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let Q=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await J("onTeamTaskProgress",$,f.agentId,Q,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function t5($,f,J,Q){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:X4({teamName:Z,sessionId:f,event:J}),summary:j4(Z,$.runtime.teamRuntime.exportState())}})}function H2($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function s5($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&H2($)}function H4($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function o5($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function e5($,f){let J=f.map((W)=>{let j=[`- ${W.runId} (${W.agentId}) -> ${W.status}`];if(W.taskId)j.push(` task=${W.taskId}`);if(typeof W.iterations==="number")j.push(` iterations=${W.iterations}`);if(W.error)j.push(` error=${W.error}`);return j.join("")}),Q=$.activeTeamRunIds.size,Z=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return Y2(`System-delivered teammate async run updates:
461
+ ${f}`:f,j=J?.continueConversation?await Q.agent.continue(W):await Q.agent.run(W);return this.emitEvent({type:S.TaskEnd,agentId:$,result:j}),this.recordProgressStep($,`Completed a delegated run (${j.iterations} iterations)`,J?.taskId,!0),j}catch(Z){let W=Z instanceof Error?Z:Error(String(Z));if(this.emitEvent({type:S.TaskEnd,agentId:$,error:W,messages:Q.agent.getMessages()}),!mj(Q,W))this.appendMissionLog({agentId:$,taskId:J?.taskId,kind:"error",summary:W.message});throw W}finally{if(Q.runningCount--,Q.runningCount<=0&&this.members.get($)?.status!=="stopped")Q.status="idle"}}startTeammateRun($,f,J){let Q=`run_${String(++this.runCounter).padStart(5,"0")}`,Z={id:Q,agentId:$,taskId:J?.taskId,status:"queued",message:f,priority:J?.priority??0,retryCount:0,maxRetries:Math.max(0,J?.maxRetries??0),continueConversation:J?.continueConversation,startedAt:new Date(0),leaseOwner:J?.leaseOwner,heartbeatAt:void 0,lastProgressAt:new Date,lastProgressMessage:"queued",currentActivity:"queued"};return this.runs.set(Q,Z),this.runQueue.push(Q),this.emitEvent({type:S.RunQueued,run:{...Z}}),this.dispatchQueuedRuns(),{...Z}}dispatchQueuedRuns(){this.clearQueuedRunDispatchTimer();let $;while(this.countActiveRuns()<this.maxConcurrentRuns&&this.runQueue.length>0){let f=this.selectNextDispatchableQueuedRun();$=f.nextDelayedAttemptAt;let J=f.index;if(J<0){this.scheduleQueuedRunDispatch($);return}let[Q]=this.runQueue.splice(J,1),Z=Q?this.runs.get(Q):void 0;if(!Z||Z.status!=="queued")continue;this.executeQueuedRun(Z)}this.scheduleQueuedRunDispatch($)}selectNextDispatchableQueuedRun(){let $=-1,f=Number.NEGATIVE_INFINITY,J,Q=Date.now();for(let Z=0;Z<this.runQueue.length;Z++){let W=this.runs.get(this.runQueue[Z]);if(!W||W.status!=="queued")continue;if(W.nextAttemptAt&&W.nextAttemptAt.getTime()>Q){if(!J||W.nextAttemptAt<J)J=W.nextAttemptAt;continue}if(W.priority>f)f=W.priority,$=Z}return{index:$,nextDelayedAttemptAt:J}}scheduleQueuedRunDispatch($){if(!$)return;let f=Math.max(0,$.getTime()-Date.now());this.queuedRunDispatchTimer=setTimeout(()=>{this.queuedRunDispatchTimer=void 0,this.dispatchQueuedRuns()},f)}clearQueuedRunDispatchTimer(){if(!this.queuedRunDispatchTimer)return;clearTimeout(this.queuedRunDispatchTimer),this.queuedRunDispatchTimer=void 0}countActiveRuns(){let $=0;for(let f of this.runs.values())if(f.status==="running")$++;return $}async executeQueuedRun($){let f=$.currentActivity===gj;$.nextAttemptAt=void 0,$.status="running",$.startedAt=new Date,$.heartbeatAt=new Date,$.currentActivity="run_started",this.emitEvent({type:S.RunStarted,run:{...$}});let J=setInterval(()=>{if($.status!=="running")return;this.recordRunProgress($,"heartbeat")},2000);try{let Q=f?vL($):$.message,Z=await this.routeToTeammate($.agentId,Q,{taskId:$.taskId,continueConversation:$.continueConversation});$.status="completed",$.result=Z,$.endedAt=new Date,$.currentActivity="completed",this.emitEvent({type:S.RunCompleted,run:{...$}})}catch(Q){let Z=Q instanceof Error?Q.message:String(Q??"Unknown error");$.error=Z,$.endedAt=new Date;let W=this.members.get($.agentId);if(mj(W,Q))$.status="cancelled",$.currentActivity="cancelled",this.emitEvent({type:S.RunCancelled,run:{...$},reason:Z});else if($.retryCount<$.maxRetries)$.retryCount++,$.status="queued",$.nextAttemptAt=new Date(Date.now()+Math.min(30000,1000*2**$.retryCount)),this.runQueue.push($.id),this.recordRunProgress($,`retry_scheduled_${$.retryCount}`);else $.status="failed",$.currentActivity="failed",this.emitEvent({type:S.RunFailed,run:{...$}})}finally{clearInterval(J),this.dispatchQueuedRuns()}}listRuns($){let f=$?.includeCompleted??!0;return Array.from(this.runs.values()).filter((J)=>{if(!f&&!["running","queued"].includes(J.status))return!1;if($?.status&&J.status!==$.status)return!1;if($?.agentId&&J.agentId!==$.agentId)return!1;return!0}).map((J)=>({...J}))}getRun($){let f=this.runs.get($);return f?{...f}:void 0}async awaitRun($,f=250){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);while(J.status==="queued"||J.status==="running")await vj(f);return{...J}}async awaitAllRuns($=250){while(Array.from(this.runs.values()).some((f)=>["queued","running"].includes(f.status)))await vj($);return this.listRuns()}cancelRun($,f){let J=this.runs.get($);if(!J)throw Error(`Run "${$}" was not found`);if(J.status==="completed"||J.status==="failed")return{...J};J.status="cancelled",J.error=f,J.endedAt=new Date,J.currentActivity="cancelled";let Q=this.runQueue.indexOf($);if(Q>=0)this.runQueue.splice(Q,1);return this.emitEvent({type:S.RunCancelled,run:{...J},reason:f}),{...J}}recoverActiveRuns($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;let Q=this.members.get(J.agentId);if(!Q||Q.role!=="teammate"||!Q.agent){J.status="interrupted",J.error="teammate_unavailable_after_recovery",J.endedAt=new Date,J.currentActivity="interrupted",this.emitEvent({type:S.RunInterrupted,run:{...J},reason:J.error});continue}let Z=new Date;if(J.status="queued",J.error=void 0,J.endedAt=void 0,J.heartbeatAt=Z,J.lastProgressAt=Z,J.lastProgressMessage=$,J.currentActivity=gj,!this.runQueue.includes(J.id))this.runQueue.push(J.id);f.push({...J}),this.emitEvent({type:S.RunQueued,run:{...J}})}return this.dispatchQueuedRuns(),f}markStaleRunsInterrupted($="runtime_recovered"){let f=[];for(let J of this.runs.values()){if(!["queued","running"].includes(J.status))continue;J.status="interrupted",J.error=$,J.endedAt=new Date,J.currentActivity="interrupted",f.push({...J}),this.emitEvent({type:S.RunInterrupted,run:{...J},reason:$})}return this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),f}sendMessage($,f,J,Q,Z){if(!this.members.has($))throw Error(`Unknown sender "${$}"`);let W=this.members.get(f);if(!W)throw Error(`Unknown recipient "${f}"`);let j={id:`msg_${String(++this.messageCounter).padStart(5,"0")}`,teamId:this.teamId,fromAgentId:$,toAgentId:f,subject:J,body:Q,taskId:Z,sentAt:new Date};if(this.mailbox.push(j),this.emitEvent({type:S.TeamMessage,message:{...j}}),W.role==="teammate"&&W.runningCount>0&&W.agent)W.pendingSteerMessage=`[MAILBOX] You got a message from ${$}. Subject: "${J}". Use the team_read_mailbox tool to read it at your convenience.`;return{...j}}broadcast($,f,J,Q){let Z=[];for(let W of this.members.values()){if(W.agentId===$)continue;if(W.role==="lead")continue;Z.push(this.sendMessage($,W.agentId,f,J,Q?.taskId))}return Z}appendMissionLog($){if(!this.members.has($.agentId))throw Error(`Unknown team member "${$.agentId}"`);let f={id:`log_${String(++this.missionCounter).padStart(6,"0")}`,ts:new Date,teamId:this.teamId,agentId:$.agentId,taskId:$.taskId,kind:$.kind,summary:$.summary,evidence:$.evidence,nextAction:$.nextAction};this.missionLog.push(f);let J=this.members.get($.agentId);if(J)J.lastMissionAt=Date.now(),J.lastMissionStep=this.missionStepCounter;return this.emitEvent({type:S.TeamMissionLog,entry:{...f}}),{...f}}createOutcome($){let f={id:`out_${String(++this.outcomeCounter).padStart(4,"0")}`,teamId:this.teamId,title:$.title,status:"draft",requiredSections:[...new Set($.requiredSections)],createdBy:$.createdBy,createdAt:new Date};return this.outcomes.set(f.id,f),this.emitEvent({type:S.OutcomeCreated,outcome:{...f}}),{...f}}listOutcomes(){return Array.from(this.outcomes.values()).map(($)=>({...$}))}attachOutcomeFragment($){let f=this.outcomes.get($.outcomeId);if(!f)throw Error(`Outcome "${$.outcomeId}" was not found`);if(!f.requiredSections.includes($.section))throw Error(`Section "${$.section}" is not part of outcome "${$.outcomeId}"`);let J={id:`frag_${String(++this.outcomeFragmentCounter).padStart(5,"0")}`,teamId:this.teamId,outcomeId:$.outcomeId,section:$.section,sourceAgentId:$.sourceAgentId,sourceRunId:$.sourceRunId,content:$.content,status:"draft",createdAt:new Date};if(this.outcomeFragments.set(J.id,J),f.status==="draft")f.status="in_review";return this.emitEvent({type:S.OutcomeFragmentAttached,fragment:{...J}}),{...J}}reviewOutcomeFragment($){let f=this.outcomeFragments.get($.fragmentId);if(!f)throw Error(`Fragment "${$.fragmentId}" was not found`);return f.status=$.approved?"reviewed":"rejected",f.reviewedBy=$.reviewedBy,f.reviewedAt=new Date,this.emitEvent({type:S.OutcomeFragmentReviewed,fragment:{...f}}),{...f}}listOutcomeFragments($){return Array.from(this.outcomeFragments.values()).filter((f)=>f.outcomeId===$).map((f)=>({...f}))}finalizeOutcome($){let f=this.outcomes.get($);if(!f)throw Error(`Outcome "${$}" was not found`);let J=this.listOutcomeFragments($);for(let Q of f.requiredSections)if(!J.some((W)=>W.section===Q&&W.status==="reviewed"))throw Error(`Outcome "${$}" cannot be finalized. Section "${Q}" is missing a reviewed fragment.`);return f.status="finalized",f.finalizedAt=new Date,this.emitEvent({type:S.OutcomeFinalized,outcome:{...f}}),{...f}}cleanup(){for(let $ of this.members.values())if($.role==="teammate"&&$.runningCount>0)throw Error(`Cannot cleanup team while teammate "${$.agentId}" is still running`);if(Array.from(this.runs.values()).some(($)=>["queued","running"].includes($.status)))throw Error("Cannot cleanup team while async teammate runs are still active");for(let $ of this.members.values())if($.role==="teammate")try{$.agent?.abort()}catch(f){if(!W9(f))throw f}this.tasks.clear(),this.mailbox.length=0,this.missionLog.length=0,this.runs.clear(),this.runQueue.length=0,this.clearQueuedRunDispatchTimer(),this.outcomes.clear(),this.outcomeFragments.clear();for(let[$,f]of this.members.entries())if(f.role==="teammate")this.members.delete($)}requireTask($){let f=this.tasks.get($);if(!f)throw Error(`Task "${$}" was not found`);return f}assertDependenciesResolved($){let f=this.getUnresolvedDependencies($);if(f.length>0)throw Error(`Task "${$.id}" is blocked by "${f[0]}"`)}getUnresolvedDependencies($){return $.dependsOn.filter((f)=>{let J=this.tasks.get(f);return!J||J.status!=="completed"})}trackMeaningfulEvent($,f){if(this.recordRunActivityFromAgentEvent($,f),f.type==="iteration_end"&&f.hadToolCalls){this.recordProgressStep($,`Completed iteration ${f.iteration} with ${f.toolCallCount} tool call(s)`);return}if(f.type==="content_end"&&f.contentType==="tool"&&!f.error){this.recordProgressStep($,`Finished tool "${f.toolName??"unknown"}"`);return}if(f.type==="done"){this.appendMissionLog({agentId:$,kind:"done",summary:`Completed a delegated run (${f.iterations} iterations)`});return}if(f.type==="error")this.appendMissionLog({agentId:$,kind:"error",summary:f.error.message})}recordRunActivityFromAgentEvent($,f){let J;switch(f.type){case"iteration_start":J=`iteration_${f.iteration}_started`;break;case"content_start":if(f.contentType==="tool")J=`running_tool_${f.toolName??"unknown"}`;break;case"content_end":if(f.contentType==="tool")J=f.error?this.formatProgressErrorActivity(`tool_${f.toolName??"unknown"}_error`,f.error):`finished_tool_${f.toolName??"unknown"}`;break;case"done":J="finalizing_response";break;case"error":J=this.formatProgressErrorActivity("run_error",f.error.message);break;default:break}if(!J)return;for(let Q of this.runs.values()){if(Q.agentId!==$||Q.status!=="running")continue;this.recordRunProgress(Q,J)}}recordRunProgress($,f){let J=new Date;$.heartbeatAt=J,$.lastProgressAt=J,$.lastProgressMessage=f,$.currentActivity=f,this.emitEvent({type:S.RunProgress,run:{...$},message:f})}formatProgressErrorActivity($,f){let J=f.replace(/\s+/g," ").trim();if(J.length===0)return $;let Q=J.length>240?`${J.slice(0,237).trimEnd()}...`:J;return`${$}: ${Q}`}recordProgressStep($,f,J,Q=!1){this.missionStepCounter++;let Z=this.members.get($);if(!Z)return;let W=this.missionStepCounter-Z.lastMissionStep,j=Date.now()-Z.lastMissionAt;if(!Q&&W<this.missionLogIntervalSteps&&j<this.missionLogIntervalMs)return;this.appendMissionLog({agentId:$,taskId:J,kind:"progress",summary:f})}buildMailboxNotification($){if($.length===0)return"";let f=[`[MAILBOX] You have ${$.length} unread message(s):`];for(let J of $)f.push(`--- Message from ${J.fromAgentId} | subject: ${J.subject} ---`),f.push(J.body);return f.push("---"),f.join(`
462
+ `)}emitEvent($){try{this.onTeamEvent?.($)}catch{}}}function vj($){return new Promise((f)=>setTimeout(f,$))}function $2($,f){let J=0;for(let Q of $){if(!Q.startsWith(f))continue;let Z=Number.parseInt(Q.slice(f.length),10);if(Number.isFinite(Z))J=Math.max(J,Z)}return J}function X9($,f){switch(f.type){case"run_queued":case"run_started":$.activeTeamRunIds.add(f.run.id);break;case"run_completed":case"run_failed":case"run_cancelled":case"run_interrupted":{let J;if(f.type==="run_failed")J=f.run.error;else if(f.type==="run_cancelled"||f.type==="run_interrupted")J=f.run.error??f.reason;$.activeTeamRunIds.delete(f.run.id),$.pendingTeamRunUpdates.push({runId:f.run.id,agentId:f.run.agentId,taskId:f.run.taskId,status:f.type.replace("run_",""),error:J,iterations:f.run.result?.iterations}),P6($);break}default:break}}async function H9($,f,J){switch(f.type){case"run_progress":await J("onTeamTaskProgress",$,f.run.agentId,f.message,{kind:f.message==="heartbeat"?"heartbeat":"progress"});break;case"agent_event":if(f.event.type==="content_start"&&f.event.contentType==="text"&&typeof f.event.text==="string"){let Q=f.event.text.replace(/\s+/g," ").trim().slice(0,120);if(Q)await J("onTeamTaskProgress",$,f.agentId,Q,{kind:"text"})}break;case"task_start":await J("onTeamTaskStart",$,f.agentId,f.message);break;case"task_end":{if(f.error)await J("onTeamTaskEnd",$,f.agentId,"failed",`[error] ${f.error.message}`,void 0,f.messages);else if(f.result?.finishReason==="aborted")await J("onTeamTaskEnd",$,f.agentId,"cancelled","[done] aborted",f.result,f.result.messages);else await J("onTeamTaskEnd",$,f.agentId,"completed",`[done] ${f.result?.finishReason??"completed"}`,f.result,f.result?.messages);break}default:break}}function Y9($,f,J,Q){if(!$.runtime.teamRuntime)return;let Z=$.runtime.teamRuntime.getTeamName();Q({type:"team_progress",payload:{sessionId:f,teamName:Z,lifecycle:F6({teamName:Z,sessionId:f,event:J}),summary:K6(Z,$.runtime.teamRuntime.exportState())}})}function A8($){return $.activeTeamRunIds.size>0||$.pendingTeamRunUpdates.length>0}function V9($,f){if($.aborting)return!1;if(!(f==="completed"||f==="max_iterations"))return!1;return $.config.enableAgentTeams===!0&&A8($)}function P6($){let f=$.teamRunWaiters.splice(0);for(let J of f)J()}async function A9($){while(!0){if($.aborting)return[];if($.pendingTeamRunUpdates.length>0){let f=[...$.pendingTeamRunUpdates];return $.pendingTeamRunUpdates.length=0,f}if($.activeTeamRunIds.size===0)return[];await new Promise((f)=>{$.teamRunWaiters.push(f)})}}function B9($,f){let J=f.map((W)=>{let j=[`- ${W.runId} (${W.agentId}) -> ${W.status}`];if(W.taskId)j.push(` task=${W.taskId}`);if(typeof W.iterations==="number")j.push(` iterations=${W.iterations}`);if(W.error)j.push(` error=${W.error}`);return j.join("")}),Q=$.activeTeamRunIds.size,Z=Q>0?`There are still ${Q} teammate run(s) in progress. Continue coordination and decide whether to wait for more updates.`:"No teammate runs are currently in progress. Continue coordination using these updates.";return B8(`System-delivered teammate async run updates:
463
463
  ${J.join(`
464
464
  `)}
465
465
 
466
- ${Z}`,$.config.mode)}function Y2($,f){return JL($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var $9=4;class Y${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new l5($,f.messagesArtifactUploader,f.logger),this.teamChildren=new W4($,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),Y$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?n8(f.messages,f,J):i8($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??n(),J=$.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${ZL(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=sf({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:w$(X.metadata),hookPath:"",messagesPath:Z,updatedAt:n()}),this.manifestStore.initializeMessagesFile(Q,Z,f),this.manifestStore.writeSessionManifest(W,X),{manifestPath:W,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let Q;if((await NW(()=>this.adapter.getSession($),async(W)=>{return Q=f==="running"?void 0:n(),this.adapter.updateSession({sessionId:$,status:f,endedAt:Q??null,exitCode:f==="running"?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},$9)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let f=0;f<$9;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=$.metadata!==void 0?w$($.metadata)??{}:w$(Q)??{},W=V1(typeof Q?.title==="string"?Q.title:void 0),j=$.title!==void 0?V1($.title):W??O5($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:Y,manifest:V}=this.manifestStore.readManifestFile($.sessionId);if(V){if($.prompt!==void 0)V.prompt=$.prompt??void 0;let A=$.metadata!==void 0?w$($.metadata)??{}:w$(V.metadata)??{};if(j)A.title=j;V.metadata=Object.keys(A).length>0?A:void 0,this.manifestStore.writeSessionManifest(Y,V)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let Q=i8(f);return this.manifestStore.persistSessionMessages($,Q,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,Q,Z,W){return this.teamChildren.onTeamTaskEnd($,f,J,Q,Z,W)}onTeamTaskProgress($,f,J,Q){return this.teamChildren.onTeamTaskProgress($,f,J,Q)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if($.status!=="running"||this.isPidAlive($.pid))return $;let f=n(),J=Y$.STALE_REASON;for(let Q=0;Q<$9;Q++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(Z.status!=="running")return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:Y$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=yW(Z,{status:"failed",endedAt:f,exitCode:1,metadata:W}),{path:H}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(H,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,Y$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let W=w$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=V1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),H=X?{...W??{},title:X}:W;return{...Z,metadata:H}})}async reconcileDeadSessions($=2000){let f=await this.adapter.listSessions({limit:Math.max(1,Math.floor($)),status:"running"}),J=0;for(let Q of f){let Z=await this.reconcileDeadRunningSession(Q);if(Z&&Z.status!==Q.status)J++}return J}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(Q.map(async(Z)=>{await u5(Z.cwd,Z.sessionId),j2(Z.messagesPath),j2(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await u5(J.cwd,f),j2(J.messagesPath),j2(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(QL(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function J9(){return new Date().toISOString()}function Nj($,f){let J=`${$}.tmp`;XL(J,`${JSON.stringify(f,null,2)}
467
- `,"utf8"),jL(J,$)}class Tj{sessionsDirPath;constructor($=HL()){this.sessionsDirPath=$}ensureSessionsDir(){if(!f9(this.sessionsDirPath))WL(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return yj(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return yj(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!f9($))return{version:1,sessions:{}};try{let f=JSON.parse(_j($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){Nj(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!f9($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(_j($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){Nj(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:J9()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:J9()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=J9(),this.writeQueue(J),Q.task}}class Q9 extends Y${constructor($,f={}){super(new Tj($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as YL,mkdirSync as VL}from"node:fs";import{resolveSessionDataDir as AL}from"@cline/shared/storage";var Z9=`
466
+ ${Z}`,$.config.mode)}function B8($,f){return uL($,f==="plan"?"plan":f==="yolo"?"yolo":"act")}var G9=4;class Y${adapter;manifestStore;teamChildren;static STALE_REASON="failed_external_process_exit";static STALE_SOURCE="stale_session_reconciler";static TEAM_HEARTBEAT_LOG_INTERVAL_MS=30000;constructor($,f={}){this.adapter=$;this.manifestStore=new Q9($,f.messagesArtifactUploader,f.logger),this.teamChildren=new G6($,this.manifestStore,(J,Q,Z)=>this.toPersistedMessages(J,Q,Z),Y$.TEAM_HEARTBEAT_LOG_INTERVAL_MS)}toPersistedMessages($,f,J){if(!$)return;return f?J6(f.messages,f,J):f6($)}ensureSessionsDir(){return this.manifestStore.ensureSessionsDir()}writeSessionManifest($,f){this.manifestStore.writeSessionManifest($,f)}readSessionManifest($){return this.manifestStore.readSessionManifest($)}async createRootSessionWithArtifacts($){let f=$.startedAt??n(),J=$.sessionId.trim(),Q=J.length>0?J:`${Date.now()}_${dL(5)}`,Z=this.manifestStore.artifacts.sessionMessagesPath(Q),W=this.manifestStore.artifacts.sessionManifestPath(Q),j=$8({metadata:$.metadata,prompt:$.prompt}),X={version:1,session_id:Q,source:$.source,pid:$.pid,started_at:f,status:"running",interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspace_root:$.workspaceRoot,team_name:$.teamName,enable_tools:$.enableTools,enable_spawn:$.enableSpawn,enable_teams:$.enableTeams,prompt:$.prompt?.trim()||void 0,metadata:j,messages_path:Z};return await this.adapter.upsertSession({sessionId:Q,source:$.source,pid:$.pid,startedAt:f,endedAt:null,exitCode:null,status:"running",statusLock:0,interactive:$.interactive,provider:$.provider,model:$.model,cwd:$.cwd,workspaceRoot:$.workspaceRoot,teamName:$.teamName??null,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,parentSessionId:null,parentAgentId:null,agentId:null,conversationId:null,isSubagent:!1,prompt:X.prompt??null,metadata:S$(X.metadata),hookPath:"",messagesPath:Z,updatedAt:n()}),this.manifestStore.initializeMessagesFile(Q,Z,f),this.manifestStore.writeSessionManifest(W,X),{manifestPath:W,messagesPath:Z,manifest:X}}async updateSessionStatus($,f,J){let Q;if((await uW(()=>this.adapter.getSession($),async(W)=>{return Q=f0(f)?void 0:n(),this.adapter.updateSession({sessionId:$,status:f,endedAt:Q??null,exitCode:f0(f)?null:typeof J==="number"?J:null,expectedStatusLock:W.statusLock})},G9)).updated){if(f==="cancelled")await this.teamChildren.applyStatusToRunningChildSessions($,"cancelled");return{updated:!0,endedAt:Q}}return{updated:!1}}async updateSession($){for(let f=0;f<G9;f++){let J=await this.adapter.getSession($.sessionId);if(!J)return{updated:!1};let Q=J.metadata??void 0,Z=$.metadata!==void 0?S$($.metadata)??{}:S$(Q)??{},W=G1(typeof Q?.title==="string"?Q.title:void 0),j=$.title!==void 0?G1($.title):W??b5($.prompt);if(j)Z.title=j;else delete Z.title;let X=$.metadata!==void 0||$.prompt!==void 0||$.title!==void 0;if(!(await this.adapter.updateSession({sessionId:$.sessionId,prompt:$.prompt,metadata:X?Object.keys(Z).length>0?Z:null:void 0,title:j,expectedStatusLock:J.statusLock})).updated)continue;let{path:Y,manifest:V}=this.manifestStore.readManifestFile($.sessionId);if(V){if($.prompt!==void 0)V.prompt=$.prompt??void 0;let A=$.metadata!==void 0?S$($.metadata)??{}:S$(V.metadata)??{};if(j)A.title=j;V.metadata=Object.keys(A).length>0?A:void 0,this.manifestStore.writeSessionManifest(Y,V)}return{updated:!0}}return{updated:!1}}queueSpawnRequest($){return this.teamChildren.queueSpawnRequest($)}upsertSubagentSession($){return this.teamChildren.upsertSubagentSession($)}upsertSubagentSessionFromHook($){return this.teamChildren.upsertSubagentSessionFromHook($)}appendSubagentHookAudit($,f){return this.teamChildren.appendSubagentHookAudit(f),Promise.resolve()}persistSessionMessages($,f,J){let Q=f6(f);return this.manifestStore.persistSessionMessages($,Q,J)}applySubagentStatus($,f){return this.teamChildren.applySubagentStatus($,f)}applySubagentStatusBySessionId($,f){return this.teamChildren.applySubagentStatusBySessionId($,f)}applyStatusToRunningChildSessions($,f){return this.teamChildren.applyStatusToRunningChildSessions($,f)}onTeamTaskStart($,f,J){return this.teamChildren.onTeamTaskStart($,f,J)}onTeamTaskEnd($,f,J,Q,Z,W){return this.teamChildren.onTeamTaskEnd($,f,J,Q,Z,W)}onTeamTaskProgress($,f,J,Q){return this.teamChildren.onTeamTaskProgress($,f,J,Q)}handleSubAgentStart($,f){return this.teamChildren.handleSubAgentStart($,f)}handleSubAgentEnd($,f){return this.teamChildren.handleSubAgentEnd($,f)}isPidAlive($){if(!Number.isFinite($)||$<=0)return!1;try{return process.kill(Math.floor($),0),!0}catch(f){return typeof f==="object"&&f!==null&&"code"in f&&f.code==="EPERM"}}async reconcileDeadRunningSession($){if(f0($.status)===!1||this.isPidAlive($.pid))return $;let f=n(),J=Y$.STALE_REASON;for(let Q=0;Q<G9;Q++){let Z=await this.adapter.getSession($.sessionId);if(!Z)return;if(f0(Z.status)===!1)return Z;let W={...Z.metadata??{},terminal_marker:J,terminal_marker_at:f,terminal_marker_pid:Z.pid,terminal_marker_source:Y$.STALE_SOURCE},j=await this.adapter.updateSession({sessionId:Z.sessionId,status:"failed",endedAt:f,exitCode:1,metadata:W,expectedStatusLock:Z.statusLock});if(!j.updated)continue;await this.teamChildren.applyStatusToRunningChildSessions(Z.sessionId,"failed");let X=vW(Z,{status:"failed",endedAt:f,exitCode:1,metadata:W}),{path:H}=this.manifestStore.readManifestFile(Z.sessionId);return this.manifestStore.writeSessionManifest(H,X),this.manifestStore.appendStaleSessionHookLog(f,Z.sessionId,Z.pid,J,Y$.STALE_SOURCE),{...Z,status:"failed",endedAt:f,exitCode:1,metadata:W,statusLock:j.statusLock,updatedAt:f}}return await this.adapter.getSession($.sessionId)}async listSessions($=200){let f=Math.max(1,Math.floor($)),J=Math.min(f*5,2000);return await this.reconcileDeadSessions(J),(await this.adapter.listSessions({limit:J})).slice(0,f).map((Z)=>{let W=S$(Z.metadata??void 0),j=this.manifestStore.readSessionManifest(Z.sessionId),X=G1(typeof j?.metadata?.title==="string"?j.metadata.title:void 0),H=X?{...W??{},title:X}:W;return{...Z,metadata:H}})}async reconcileDeadSessions($=2000){let f=Math.max(1,Math.floor($)),J=(await Promise.all(["idle","running","pending"].map((Z)=>this.adapter.listSessions({limit:f,status:Z})))).flat(),Q=0;for(let Z of J){let W=await this.reconcileDeadRunningSession(Z);if(W&&W.status!==Z.status)Q++}return Q}async deleteSession($){let f=$.trim();if(!f)throw Error("session id is required");let J=await this.adapter.getSession(f);if(!J)return{deleted:!1};if(await this.adapter.deleteSession(f,!1),!J.isSubagent){let Q=await this.adapter.listSessions({limit:2000,parentSessionId:f});await this.adapter.deleteSession(f,!0),await Promise.allSettled(Q.map(async(Z)=>{await f9(Z.cwd,Z.sessionId),Y8(Z.messagesPath),Y8(this.manifestStore.artifacts.sessionManifestPath(Z.sessionId,!1)),this.manifestStore.artifacts.removeSessionDirIfEmpty(Z.sessionId)}))}if(await f9(J.cwd,f),Y8(J.messagesPath),Y8(this.manifestStore.artifacts.sessionManifestPath(f,!1)),J.isSubagent)this.manifestStore.artifacts.removeSessionDirIfEmpty(f);else{let Q=new Set([this.manifestStore.artifacts.sessionArtifactsDir(f)]);for(let Z of[J.messagesPath])if(typeof Z==="string"&&Z.trim().length>0)Q.add(cL(Z));for(let Z of Q)this.manifestStore.artifacts.removeDir(Z)}return{deleted:!0}}}function F9(){return new Date().toISOString()}function dj($,f){let J=`${$}.tmp`;rL(J,`${JSON.stringify(f,null,2)}
467
+ `,"utf8"),pL(J,$)}class lj{sessionsDirPath;constructor($=iL()){this.sessionsDirPath=$}ensureSessionsDir(){if(!K9(this.sessionsDirPath))lL(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}indexPath(){return cj(this.ensureSessionsDir(),"sessions.index.json")}spawnQueuePath(){return cj(this.ensureSessionsDir(),"subagent-spawn-queue.json")}readIndex(){let $=this.indexPath();if(!K9($))return{version:1,sessions:{}};try{let f=JSON.parse(uj($,"utf8"));if(f?.version===1&&f.sessions)return f}catch{}return{version:1,sessions:{}}}writeIndex($){dj(this.indexPath(),$)}readQueue(){let $=this.spawnQueuePath();if(!K9($))return{version:1,nextId:1,requests:[]};try{let f=JSON.parse(uj($,"utf8"));if(f?.version===1&&typeof f.nextId==="number"&&Array.isArray(f.requests))return f}catch{}return{version:1,nextId:1,requests:[]}}writeQueue($){dj(this.spawnQueuePath(),$)}async upsertSession($){let f=this.readIndex();f.sessions[$.sessionId]=$,this.writeIndex(f)}async getSession($){return this.readIndex().sessions[$]}async listSessions($){return Object.values(this.readIndex().sessions).filter((f)=>$.parentSessionId!==void 0?f.parentSessionId===$.parentSessionId:!0).filter((f)=>$.status!==void 0?f.status===$.status:!0).sort((f,J)=>J.startedAt.localeCompare(f.startedAt)).slice(0,$.limit)}async updateSession($){let f=this.readIndex(),J=f.sessions[$.sessionId];if(!J)return{updated:!1,statusLock:0};if($.expectedStatusLock!==void 0&&J.statusLock!==$.expectedStatusLock)return{updated:!1,statusLock:J.statusLock};let Q=$.expectedStatusLock!==void 0?$.expectedStatusLock+1:J.statusLock,Z={...J,status:$.status??J.status,endedAt:$.endedAt!==void 0?$.endedAt:J.endedAt??null,exitCode:$.exitCode!==void 0?$.exitCode:J.exitCode??null,prompt:$.prompt!==void 0?$.prompt:J.prompt??null,metadata:$.metadata!==void 0?$.metadata??null:J.metadata??null,parentSessionId:$.parentSessionId!==void 0?$.parentSessionId??null:J.parentSessionId??null,parentAgentId:$.parentAgentId!==void 0?$.parentAgentId??null:J.parentAgentId??null,agentId:$.agentId!==void 0?$.agentId??null:J.agentId??null,conversationId:$.conversationId!==void 0?$.conversationId??null:J.conversationId??null,statusLock:Q,isSubagent:$.setRunning||$.parentSessionId!==void 0?!0:J.isSubagent,updatedAt:F9()};if($.setRunning)Z.status="running",Z.endedAt=null,Z.exitCode=null;return f.sessions[$.sessionId]=Z,this.writeIndex(f),{updated:!0,statusLock:Z.statusLock}}async deleteSession($,f){let J=this.readIndex();if(!J.sessions[$])return!1;if(delete J.sessions[$],f){for(let Z of Object.values(J.sessions))if(Z.parentSessionId===$)delete J.sessions[Z.sessionId]}return this.writeIndex(J),!0}async enqueueSpawnRequest($){let f=this.readQueue();f.requests.push({id:f.nextId,rootSessionId:$.rootSessionId,parentAgentId:$.parentAgentId,task:$.task,systemPrompt:$.systemPrompt,createdAt:F9()}),f.nextId+=1,this.writeQueue(f)}async claimSpawnRequest($,f){let J=this.readQueue(),Q=J.requests.find((Z)=>Z.rootSessionId===$&&Z.parentAgentId===f&&!Z.consumedAt);if(!Q)return;return Q.consumedAt=F9(),this.writeQueue(J),Q.task}}class P9 extends Y${constructor($,f={}){super(new lj($),f)}ensureSessionsDir(){return super.ensureSessionsDir()}}import{existsSync as nL,mkdirSync as aL}from"node:fs";import{resolveSessionDataDir as tL}from"@cline/shared/storage";var U9=`
468
468
  session_id AS sessionId,
469
469
  source,
470
470
  pid,
@@ -491,43 +491,43 @@ ${Z}`,$.config.mode)}function Y2($,f){return JL($,f==="plan"?"plan":f==="yolo"?"
491
491
  metadata_json AS metadata,
492
492
  hook_path AS hookPath,
493
493
  messages_path AS messagesPath,
494
- updated_at AS updatedAt`;function W9($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let f=$.metadata;if(typeof f==="string"&&f.trim())try{let J=JSON.parse(f);$.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{$.metadata=null}else $.metadata=null;return $}function j9($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function Mj($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class qj{store;sessionsDirPath;constructor($,f=AL()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!YL(this.sessionsDirPath))VL(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
494
+ updated_at AS updatedAt`;function D9($){$.interactive=$.interactive===1,$.enableTools=$.enableTools===1,$.enableSpawn=$.enableSpawn===1,$.enableTeams=$.enableTeams===1,$.isSubagent=$.isSubagent===1;let f=$.metadata;if(typeof f==="string"&&f.trim())try{let J=JSON.parse(f);$.metadata=J&&typeof J==="object"&&!Array.isArray(J)?J:null}catch{$.metadata=null}else $.metadata=null;return $}function R9($){if(!$||Object.keys($).length===0)return null;return JSON.stringify($)}function pj($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class rj{store;sessionsDirPath;constructor($,f=tL()){this.store=$;this.sessionsDirPath=f}ensureSessionsDir(){if(!nL(this.sessionsDirPath))aL(this.sessionsDirPath,{recursive:!0});return this.sessionsDirPath}async upsertSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
495
495
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
496
496
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
497
497
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
498
498
  metadata_json, transcript_path, hook_path, messages_path, updated_at
499
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,j9($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${Z9} FROM sessions WHERE session_id = ?`,[$]);return f?W9(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${Z9}
499
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,[$.sessionId,$.source,$.pid,$.startedAt,$.endedAt??null,$.exitCode??null,$.status,$.statusLock,$.interactive?1:0,$.provider,$.model,$.cwd,$.workspaceRoot,$.teamName??null,$.enableTools?1:0,$.enableSpawn?1:0,$.enableTeams?1:0,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.isSubagent?1:0,$.prompt??null,R9($.metadata),"",$.hookPath??"",$.messagesPath??null,$.updatedAt])}async getSession($){let f=this.store.queryOne(`SELECT ${U9} FROM sessions WHERE session_id = ?`,[$]);return f?D9(f):void 0}async listSessions($){let f=[],J=[];if($.parentSessionId)f.push("parent_session_id = ?"),J.push($.parentSessionId);if($.status)f.push("status = ?"),J.push($.status);let Q=f.length>0?`WHERE ${f.join(" AND ")}`:"";return this.store.queryAll(`SELECT ${U9}
500
500
  FROM sessions
501
501
  ${Q}
502
502
  ORDER BY started_at DESC
503
- LIMIT ?`,[...J,$.limit]).map(W9)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
503
+ LIMIT ?`,[...J,$.limit]).map(D9)}async updateSession($){if($.setRunning){if($.expectedStatusLock===void 0)return{updated:!1,statusLock:0};return{updated:(this.store.run(`UPDATE sessions
504
504
  SET status = 'running', ended_at = NULL, exit_code = NULL, updated_at = ?, status_lock = ?,
505
505
  parent_session_id = ?, parent_agent_id = ?, agent_id = ?, conversation_id = ?, is_subagent = 1,
506
506
  prompt = COALESCE(prompt, ?)
507
- WHERE session_id = ? AND status_lock = ?`,[n(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(j9($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(Q);f.push("updated_at = ?"),J.push(n());let Z=`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`;if(J.push($.sessionId),$.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push($.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
507
+ WHERE session_id = ? AND status_lock = ?`,[n(),$.expectedStatusLock+1,$.parentSessionId??null,$.parentAgentId??null,$.agentId??null,$.conversationId??null,$.prompt??null,$.sessionId,$.expectedStatusLock]).changes??0)>0,statusLock:$.expectedStatusLock+1}}let f=[],J=[];if($.status!==void 0)f.push("status = ?"),J.push($.status);if($.endedAt!==void 0)f.push("ended_at = ?"),J.push($.endedAt);if($.exitCode!==void 0)f.push("exit_code = ?"),J.push($.exitCode);if($.prompt!==void 0)f.push("prompt = ?"),J.push($.prompt??null);if($.metadata!==void 0)f.push("metadata_json = ?"),J.push(R9($.metadata));if($.parentSessionId!==void 0)f.push("parent_session_id = ?"),J.push($.parentSessionId??null);if($.parentAgentId!==void 0)f.push("parent_agent_id = ?"),J.push($.parentAgentId??null);if($.agentId!==void 0)f.push("agent_id = ?"),J.push($.agentId??null);if($.conversationId!==void 0)f.push("conversation_id = ?"),J.push($.conversationId??null);if(f.length===0){let j=await this.getSession($.sessionId);return{updated:!!j,statusLock:j?.statusLock??0}}let Q=0;if($.expectedStatusLock!==void 0)Q=$.expectedStatusLock+1,f.push("status_lock = ?"),J.push(Q);f.push("updated_at = ?"),J.push(n());let Z=`UPDATE sessions SET ${f.join(", ")} WHERE session_id = ?`;if(J.push($.sessionId),$.expectedStatusLock!==void 0)Z+=" AND status_lock = ?",J.push($.expectedStatusLock);if((this.store.run(Z,J).changes??0)===0)return{updated:!1,statusLock:0};if($.expectedStatusLock===void 0)Q=(await this.getSession($.sessionId))?.statusLock??0;return{updated:!0,statusLock:Q}}async deleteSession($,f){let J=this.store.run("DELETE FROM sessions WHERE session_id = ?",[$]).changes??0;if(f)this.store.run("DELETE FROM sessions WHERE parent_session_id = ?",[$]);return J>0}async enqueueSpawnRequest($){this.store.run(`INSERT INTO subagent_spawn_queue (root_session_id, parent_agent_id, task, system_prompt, created_at, consumed_at)
508
508
  VALUES (?, ?, ?, ?, ?, NULL)`,[$.rootSessionId,$.parentAgentId,$.task??null,$.systemPrompt??null,n()])}async claimSpawnRequest($,f){let J=this.store.queryOne(`SELECT id, task FROM subagent_spawn_queue
509
509
  WHERE root_session_id = ? AND parent_agent_id = ? AND consumed_at IS NULL
510
- ORDER BY id ASC LIMIT 1`,[$,f]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[n(),J.id]),J.task??void 0}}class I$ extends Y${store;constructor($,f={}){super(new qj($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
510
+ ORDER BY id ASC LIMIT 1`,[$,f]);if(!J||typeof J.id!=="number")return;return this.store.run("UPDATE subagent_spawn_queue SET consumed_at = ? WHERE id = ?",[n(),J.id]),J.task??void 0}}class m$ extends Y${store;constructor($,f={}){super(new rj($,f.sessionArtifactsDir),f);this.store=$}createRootSession($){this.store.run(`INSERT OR REPLACE INTO sessions (
511
511
  session_id, source, pid, started_at, ended_at, exit_code, status, status_lock, interactive,
512
512
  provider, model, cwd, workspace_root, team_name, enable_tools, enable_spawn, enable_teams,
513
513
  parent_session_id, parent_agent_id, agent_id, conversation_id, is_subagent, prompt,
514
514
  metadata_json, transcript_path, hook_path, messages_path, updated_at
515
- ) 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,n()])}}import{readdirSync as az}from"node:fs";import{homedir as tz}from"node:os";import{isAbsolute as sz,join as l9,resolve as p9}from"node:path";import{captureSdkError as L1,createSessionId as oz,isLikelyAuthError as ez,normalizeUserInput as $_}from"@cline/shared";import{setHomeDirIfUnset as f_}from"@cline/shared/storage";import{createHandlerAsync as FL}from"@cline/llms";import{estimateTokens as X9}from"@cline/shared";var Cj=200000,H9=0.9,Ej=16384,Y9=20000,wj=1024,Sj=2000,hj=2000,bj=8;function x$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
516
- ...[truncated ${$.length-f} chars]`}function BL($){let f=V9($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
515
+ ) 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,n()])}}import{readdirSync as h_}from"node:fs";import{homedir as C_}from"node:os";import{isAbsolute as E_,join as Q7,resolve as Z7}from"node:path";import{captureSdkError as z1,createSessionId as b_,isLikelyAuthError as k_,normalizeUserInput as I_}from"@cline/shared";import{setHomeDirIfUnset as x_}from"@cline/shared/storage";G0();import{createHandlerAsync as fO}from"@cline/llms";import{estimateTokens as L9}from"@cline/shared";var aj=200000,O9=0.9,tj=16384,z9=20000,ij=1024,nj=2000,sj=2000,oj=8;function g$($,f){if($.length<=f)return $;return`${$.slice(0,f)}
516
+ ...[truncated ${$.length-f} chars]`}function sL($){let f=_9($);if(typeof f==="string")return f;return f.map((J)=>{switch(J.type){case"text":return J.text;case"file":return`<file path="${J.path}">
517
517
  ${J.content}
518
518
  </file>`;case"image":return`[image:${J.mediaType}]`;default:return""}}).join(`
519
- `)}function V9($){if(typeof $==="string")return x$($,Sj);return $.map((f)=>{switch(f.type){case"text":return{...f,text:x$(f.text,Sj)};case"file":return{...f,content:x$(f.content,hj)};case"image":return f;default:return f}})}function KL($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function kj($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${x$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${KL(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${BL(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${x$(J.content,hj)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
520
- `)}function Ij($){return $.map(kj).join(`
519
+ `)}function _9($){if(typeof $==="string")return g$($,nj);return $.map((f)=>{switch(f.type){case"text":return{...f,text:g$(f.text,nj)};case"file":return{...f,content:g$(f.content,sj)};case"image":return f;default:return f}})}function oL($){return Object.entries($).map(([f,J])=>`${f}=${JSON.stringify(J)}`).join(", ")}function ej($){if(typeof $.content==="string")return`[${$.role==="user"?"User":"Bot"}]: ${$.content}`;let f=[];for(let J of $.content)switch(J.type){case"text":f.push(`[${$.role==="user"?"User":"Bot"}]: ${J.text}`);break;case"thinking":f.push(`[Bot thinking]: ${g$(J.thinking,2000)}`);break;case"redacted_thinking":f.push("[Bot thinking]: [redacted]");break;case"tool_use":f.push(`[Bot tool calls]: ${J.name}(${oL(J.input)})`);break;case"tool_result":f.push(`[Tool result]: ${sL(J.content)}`);break;case"file":f.push(`[${$.role==="user"?"User":"Bot"} file ${J.path}]: ${g$(J.content,sj)}`);break;case"image":f.push(`[${$.role==="user"?"User":"Bot"} image]: ${J.mediaType}`);break}return f.join(`
520
+ `)}function $X($){return $.map(ej).join(`
521
521
 
522
- `).trim()}function xj(){let $=new WeakMap;return(f)=>{let J=f,Q=$.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify(f)}catch{Z=kj(f)}let W=X9(Z.length);return $.set(J,W),W}}function B2($){return $.metadata?.kind==="compaction_summary"}function A9($){if(!B2($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function GL($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function K2($){return $.role==="user"&&!GL($)&&!B2($)}function gj($){for(let f=0;f<$.length;f+=1)if(K2($[f]))return f;return-1}function Y4($){for(let f=$.length-1;f>=0;f-=1)if(K2($[f]))return f;return 0}function mj($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function vj($){for(let f=$.length-1;f>=0;f-=1)if(B2($[f]))return f;return-1}function cj($,f,J){let Q=Y4($);if(Q<=0)return 0;let Z=0,W=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),W=X,Z>=f)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!K2($[j]))j-=1;return j}function A2($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>A2(f));if($&&typeof $==="object"){let f=$,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...A2(f[Q]));if(Array.isArray(f.files)){for(let Q of f.files)if(Q&&typeof Q==="object")J.push(...A2(Q.path))}if(Array.isArray(f.file_paths))J.push(...A2(f.file_paths));return J}return[]}function V2($,f){let J=new Set($);for(let Q of f){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function uj($){let f=[],J=[];for(let Q of $){let Z=A9(Q);if(Z){f=V2(f,Z.details.readFiles),J=V2(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){f=V2(f,[W.path]);continue}if(W.type!=="tool_use")continue;let j=A2(W.input);if(W.name==="read_files"){f=V2(f,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=V2(J,j)}}return{readFiles:f,modifiedFiles:J}}function PL($){let f=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
522
+ `).trim()}function fX(){let $=new WeakMap;return(f)=>{let J=f,Q=$.get(J);if(typeof Q==="number")return Q;let Z;try{Z=JSON.stringify(f)}catch{Z=ej(f)}let W=L9(Z.length);return $.set(J,W),W}}function F8($){return $.metadata?.kind==="compaction_summary"}function N9($){if(!F8($))return;let f=$.metadata;if(!f)return;let J=f.details;return{kind:"compaction_summary",summary:String(f.summary??""),details:{readFiles:Array.isArray(J?.readFiles)?J.readFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[],modifiedFiles:Array.isArray(J?.modifiedFiles)?J.modifiedFiles.filter((Q)=>typeof Q==="string").map((Q)=>Q.trim()).filter((Q)=>Q.length>0):[]},tokensBefore:Number(f.tokensBefore??0),generatedAt:Number(f.generatedAt??0)}}function eL($){if($.role!=="user"||!Array.isArray($.content))return!1;return $.content.length>0&&$.content.every((f)=>f.type==="tool_result")}function P8($){return $.role==="user"&&!eL($)&&!F8($)}function JX($){for(let f=0;f<$.length;f+=1)if(P8($[f]))return f;return-1}function U6($){for(let f=$.length-1;f>=0;f-=1)if(P8($[f]))return f;return 0}function QX($){for(let f=$.length-1;f>=0;f-=1)if($[f].role==="assistant")return f;return-1}function ZX($){for(let f=$.length-1;f>=0;f-=1)if(F8($[f]))return f;return-1}function WX($,f,J){let Q=U6($);if(Q<=0)return 0;let Z=0,W=$.length;for(let X=$.length-1;X>=0;X-=1)if(Z+=J($[X]),W=X,Z>=f)break;if(W<=0)return 0;let j=Math.min(W,Q);while(j>0&&!P8($[j]))j-=1;return j}function K8($){if(typeof $==="string"&&$.trim().length>0)return[$];if(Array.isArray($))return $.flatMap((f)=>K8(f));if($&&typeof $==="object"){let f=$,J=[];for(let Q of["path","file_path","target_file","new_file_path","old_file_path"])J.push(...K8(f[Q]));if(Array.isArray(f.files)){for(let Q of f.files)if(Q&&typeof Q==="object")J.push(...K8(Q.path))}if(Array.isArray(f.file_paths))J.push(...K8(f.file_paths));return J}return[]}function G8($,f){let J=new Set($);for(let Q of f){let Z=Q.trim();if(!Z)continue;J.add(Z)}return[...J].sort((Q,Z)=>Q.localeCompare(Z))}function jX($){let f=[],J=[];for(let Q of $){let Z=N9(Q);if(Z){f=G8(f,Z.details.readFiles),J=G8(J,Z.details.modifiedFiles);continue}if(!Array.isArray(Q.content))continue;for(let W of Q.content){if(W.type==="file"){f=G8(f,[W.path]);continue}if(W.type!=="tool_use")continue;let j=K8(W.input);if(W.name==="read_files"){f=G8(f,j);continue}if(W.name==="editor"||W.name==="apply_patch")J=G8(J,j)}}return{readFiles:f,modifiedFiles:J}}function $O($){let f=$.readFiles.length>0?$.readFiles.map((Q)=>`- ${Q}`).join(`
523
523
  `):"- none",J=$.modifiedFiles.length>0?$.modifiedFiles.map((Q)=>`- ${Q}`).join(`
524
524
  `):"- none";return`## Files
525
525
  Read:
526
526
  ${f}
527
527
  Modified:
528
- ${J}`}function dj($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
528
+ ${J}`}function XX($,f){if(/^## Files$/im.test($))return $.trim();return`${$.trim()}
529
529
 
530
- ${PL(f)}`.trim()}function lj($){let f=[`Summarize this session for continuation. Be concise and factual.
530
+ ${$O(f)}`.trim()}function HX($){let f=[`Summarize this session for continuation. Be concise and factual.
531
531
 
532
532
  ## Goal
533
533
  One sentence: what is being built or fixed.
@@ -549,18 +549,18 @@ Edited: ${$.fileOps.modifiedFiles.join(", ")||"none"}`];if($.previousSummary?.tr
549
549
  ${$.previousSummary.trim()}`);return f.push(`Conversation:
550
550
  ${$.conversationText||"(empty)"}`),f.join(`
551
551
 
552
- `)}function pj($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??wj,thinking:!1}};if(!f)return J($.activeProviderConfig);let Q=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...Q??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.headers??Q?.headers,knownModels:f.knownModels??Q?.knownModels,maxOutputTokens:f.maxOutputTokens??wj})}function rj($){return{role:"user",content:`Context summary:
553
-
554
- ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function DL($){let f=await FL($.providerConfig),J="";for await(let Q of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function RL($){try{return JSON.stringify($).length}catch{return String($).length}}async function ij($){let f=$.context.messages;if(f.length<2)return;let J=cj(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let Q=f.slice(0,J),Z=vj(Q),W=Z>=0?A9(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let X=uj(Q),H=Ij(j),Y=lj({previousSummary:W,conversationText:H,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:W?.length??0,conversationTextChars:H.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:X9(Y.length),newMessagesJsonChars:RL(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let V=await DL({providerConfig:pj({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!V.trim())return;let A=dj(V,X),B=f.reduce((R,F)=>R+$.estimateMessageTokens(F),0),K=[rj({summary:A,fileOps:X,tokensBefore:B}),...f.slice(J)],G=K.reduce((R,F)=>R+$.estimateMessageTokens(F),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:K.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:G,maxInputTokens:$.context.maxInputTokens}),{messages:K}}function tj($){if(B2($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:V9(J.content)}:J)}}function G2($,f){return $.reduce((J,Q)=>J+f(Q),0)}function nj($,f){let J=Math.max(1,f),Q=Math.max(16,J*4);if(typeof $.content==="string"){let j=x$($.content,Q).trim();return{...$,content:j||"..."}}let Z=Q,W=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=x$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:W}}function UL($,f){let J=gj($),Q=Y4($),Z=mj($),W=[];for(let j=0;j<$.length;j+=1){let X=tj($[j]);if(!X)continue;W.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function aj($,f,J,Q){let Z=$[f];Z.message=J,Z.estimatedTokens=Q(J)}function LL($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function OL($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function sj($){return new Set([...LL($.message),...OL($.message)])}function zL($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let Q of sj($[J])){let Z=f.get(Q);if(Z)Z.add(J);else f.set(Q,new Set([J]))}return f}function _L($,f){let J=zL($),Q=new Set,Z=[f];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of sj($[W]))for(let X of J.get(j)??[])if(!Q.has(X))Z.push(X)}return Q}function V4($,f,J,Q){let Z=G2($.map((W)=>W.message),Q);for(let W=0;W<$.length&&Z>J;){if(!f($[W])){W+=1;continue}let j=_L($,W);Z-=Array.from(j).reduce((X,H)=>X+$[H].estimatedTokens,0);for(let X of Array.from(j).sort((H,Y)=>Y-H))$.splice(X,1)}}function yL($,f,J){let Q=G2($.map((W)=>W.message),J);if(Q<=f)return;for(let W=$.length-1;W>=0&&Q>f;W-=1){let j=$[W];if(j.isFirstUser)continue;let X=Math.max(bj,j.estimatedTokens-(Q-f));if(X>=j.estimatedTokens)continue;aj($,W,nj(j.message,X),J),Q=G2($.map((H)=>H.message),J)}if(Q<=f)return;let Z=$.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,$[Z].estimatedTokens-(Q-f));aj($,Z,nj($[Z].message,W),J)}}function NL($,f){return JSON.stringify($)!==JSON.stringify(f)}function TL($){let f=Y4($);if(f<0||f===0&&!K2($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function oj($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:Q}=TL($.context.messages);if(J.length===0)return;let Z=UL(J,$.estimateMessageTokens);if(Z.length===0)return;V4(Z,(H)=>H.message.role==="assistant"&&!H.isLastAssistant,f,$.estimateMessageTokens),V4(Z,(H)=>H.message.role==="user"&&!H.isFirstUser&&!H.isLastUser,f,$.estimateMessageTokens),V4(Z,(H)=>H.message.role==="assistant"&&H.isLastAssistant,f,$.estimateMessageTokens),V4(Z,(H)=>H.message.role==="user"&&H.isLastUser&&!H.isFirstUser,f,$.estimateMessageTokens),yL(Z,f,$.estimateMessageTokens);let W=[...Z.map((H)=>H.message),...Q];if(!NL($.context.messages,W))return;let j=G2([...J.map((H)=>tj(H)??H),...Q],$.estimateMessageTokens),X=G2(W,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:W.length,messagesRemoved:$.context.messages.length-W.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:W}}function ej($){try{return JSON.stringify($).length}catch{return String($).length}}function ML($){let f=0,J=0,Q=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=ej(W.content);f+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var qL={basic:({context:$,estimateMessageTokens:f,logger:J})=>oj({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>ij({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??Y9,$.triggerTokens):J?.preserveRecentTokens??Y9,estimateMessageTokens:Z,logger:W})};function wL($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min($.maxInputTokens-Ej,$.maxInputTokens*H9));return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}let f=$.config.thresholdRatio??H9,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function SL($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),Q=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}function B9($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=xj(),W=J?.strategy??"basic",j=qL[W],X=f.mode??"auto";return async(H)=>{let Y=H.apiMessages.reduce((P,D)=>P+Z(D),0),V=J?.maxInputTokens??H.model.info?.maxInputTokens??H.model.info?.contextWindow??Cj;if(typeof V!=="number"||!Number.isFinite(V)||V<=0)return;let A=wL({inputTokens:Y,maxInputTokens:V,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:W,iteration:H.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:Y,maxInputTokens:V,triggerTokens:A.triggerTokens,thresholdRatio:A.thresholdRatio,shouldCompact:A.shouldCompact,messageCount:H.messages.length,apiMessageCount:H.apiMessages.length,apiMessagesJsonChars:ej(H.apiMessages),...ML(H.apiMessages)}),X==="auto"&&!A.shouldCompact)return;let B=X==="manual"?SL({inputTokens:Y,maxInputTokens:V,autoTriggerTokens:A.triggerTokens,manualTargetRatio:f.manualTargetRatio}):A,K={agentId:H.agentId,conversationId:H.conversationId,parentAgentId:H.parentAgentId,iteration:H.iteration,messages:H.messages,model:H.model,maxInputTokens:V,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,utilizationRatio:V>0?Y/V:0},G=X==="manual"?"manual_compaction":"auto_compaction";H.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:G,reason:G,iteration:H.iteration,triggerTokens:B.triggerTokens,maxInputTokens:V});let R=H.messages.length,F=J?.compact?await J.compact(K):await j({context:K,providerConfig:{...Q,abortSignal:H.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger});if(F?.messages){let P=F.messages.reduce((D,O)=>D+Z(O),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:V,inputTokens:Y,afterTokens:P,tokensSaved:Y-P,utilizationBefore:`${(Y/V*100).toFixed(1)}%`,utilizationAfter:`${(P/V*100).toFixed(1)}%`,thresholdTrigger:`${(B.thresholdRatio*100).toFixed(1)}%`,messagesBefore:R,messagesAfter:F.messages.length,messagesRemoved:R-F.messages.length})}return F}}R0();function K0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function A4($){let f=K0();for(let J of $)f=H0(f,J);return f}function o1($){return typeof $==="number"&&Number.isFinite($)?$:0}function B4($){let f=K0();for(let J of $){let Q=J.metrics;if(!Q)continue;f=H0(f,{inputTokens:o1(Q.inputTokens),outputTokens:o1(Q.outputTokens),cacheReadTokens:o1(Q.cacheReadTokens),cacheWriteTokens:o1(Q.cacheWriteTokens),totalCost:o1(Q.cost)})}return f}function CL($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let Q=o1(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function EL($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function K9($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function V$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,Q=$.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function hL($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function bL($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let Q=J?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function G9($,f,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=$,X=Z.telemetry,H=W?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,V=K9(f),A=V$({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??H?.getTeamId(),teamName:J?.teamName??H?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=EL(f.input);if(B)X6(X,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...A})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",K=!f.error;if(j6(X,{ulid:Q,tool:B,autoApproved:void 0,success:K,modelId:Z.modelId,provider:Z.providerId,...A}),!K&&(B==="editor"||B==="apply_patch"))H6(X,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...A})}if(f.type==="notice"&&f.reason==="api_error")w2(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...A});if(f.type==="error")w2(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...A});if(f.type==="usage"&&W?.turnUsageBaseline){let B=hL(f);if(Y){W.turnPrimaryUsage=H0(W.turnPrimaryUsage??K0(),B);let G=H0(W.turnUsageBaseline,W.turnPrimaryUsage);$.usageBySession.set(Q,G),Hf(X,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...A}),Z6(X,{ulid:Q,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...A})}else{let G=bL({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:V}),R=W.turnUsageByAgent??new Map;W.turnUsageByAgent=R,R.set(G,H0(R.get(G)??K0(),B))}let K=H0(W.turnPrimaryUsage??K0(),A4(W.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,H0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,K))}if(f.type==="iteration_end"&&Y)$.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:zW(f),ts:Date.now()}})}function g$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as HO}from"@cline/shared";import{spawn as dL}from"node:child_process";import{appendFileSync as lL,readFileSync as pL}from"node:fs";import{join as rL}from"node:path";import{augmentNodeCommandForDebug as QX,withResolvedClineBuildEnv as L9}from"@cline/shared";import{ensureHookLogDir as fX}from"@cline/shared/storage";function K4($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as kL,readdirSync as IL}from"node:fs";import{basename as xL,extname as gL,join as mL}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as $X,resolveHooksConfigSearchPaths as vL}from"@cline/shared/storage";function P9($){return vL($)}var G4;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(G4||={});var F9={["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"},cL=new Map(Object.values(G4).map(($)=>[$.toLowerCase(),$])),uL=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function D9($){let f=gL($).toLowerCase();if(!uL.has(f))return;let J=xL($,f).trim().toLowerCase();return cL.get(J)}function e1($){let f=[],J=new Set,Q=P9($).filter((Z)=>kL(Z));for(let Z of Q)try{for(let W of IL(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=D9(W.name);if(!j)continue;let X=mL(Z,W.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:F9[j],path:X})}}catch{}return f.sort((Z,W)=>Z.path.localeCompare(W.path))}function F4($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))f[J]=typeof Q==="string"?Q:JSON.stringify(Q);return f}function P4($,f,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${f}${Q}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function iL($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
555
- `),Q=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function nL($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function R9($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function Y0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function aL($){let f=$.trim();if(!f)return{};let Q=f.split(`
556
- `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function tL($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",H),J.off("finish",Y),$.off("close",V)},X=(A)=>{if(W)return;if(W=!0,j(),A){let B=A.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){Q();return}Z(A);return}Q()},H=(A)=>X(A),Y=()=>X(),V=()=>X();J.on("error",H),J.once("finish",Y),$.once("close",V);try{J.end(f)}catch(A){X(A)}})}async function ZX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await JX($,f)}catch(J){let Q=eL(f.command,process.platform,J);if(!Q)throw J;return await JX($,{...f,command:Q})}}async function JX($,f){let J=QX(f.command,{env:f.env,debugRole:"hook"}),Q=dL(J[0],J.slice(1),{cwd:f.cwd,env:L9(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{Q.once("spawn",()=>B())}),W=new Promise((B,K)=>{Q.once("error",(G)=>K(G))}),j=JSON.stringify($);if(await Promise.race([Z,W]),await tL(Q,j),f.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let X="",H="",Y=!1,V;Q.stdout.on("data",(B)=>{X+=B.toString()}),Q.stderr.on("data",(B)=>{H+=B.toString()});let A=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{Y=!0,Q.kill("SIGKILL")},f.timeoutMs);Q.once("close",(K)=>{if(V)clearTimeout(V);let{parsedJson:G,parseError:R}=aL(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([A,W])}function sL($){try{let J=pL($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let Q=J.slice(2).trim();if(!Q)return;let Z=Q.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function oL($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function eL($,f=process.platform,J){if(f!=="win32"||!oL(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function WX($){if($.length===0)return;let[f,...J]=$,Q=f.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return WX(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function $O($){let f=sL($);if(f&&f.length>0)return[...WX(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return QX(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function fO($){let f={};for(let J of e1($)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=f[Q]??[];Z.push($O(J.path)),f[Q]=Z}return f}async function JO($){let f;for(let J of $.commands){let Q=J.join(" ");try{let Z=await ZX($.payload,{command:J,cwd:$.cwd,env:L9(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){P4($.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){P4($.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}f=iL(f,nL(Z?.parsedJson))}catch(Z){P4($.logger,`hook command failed: ${Q}`,Z)}}return f}function D1($){for(let f of $.commands){let J=f.join(" ");ZX($.payload,{command:f,cwd:$.cwd,env:L9(process.env),detached:!0}).catch((Q)=>{P4($.logger,`hook command failed: ${J}`,Q)})}}function m$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function U9($,f){return{...m$($.snapshot),userMessage:f}}function jX($){return{...m$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function XX($){return{...m$($.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 HX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function QO($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function D4($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
557
- `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??rL(fX(),"hooks.jsonl");fX(j),lL(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=U9(Q,"");J({...Y0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=jX(Q);J({...Y0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:F4(Z.call.input)}});return},afterTool:async(Q)=>{let Z=XX(Q);J({...Y0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:F4(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:Q,result:Z})=>{let W=m$(Q);if(Z.status==="completed"){J({...Y0(W,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||R9(Z.error?.message)){J({...Y0(W,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...Y0(W,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=U9({snapshot:Q.snapshot},HX(Q.message.content));J({...Y0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function O9($){let f=fO($.workspacePath);if(!Object.values(f).some((A)=>A.length>0))return;let Q=async(A,B)=>{let K=f[B]??[];if(K.length===0)return;D1({commands:K,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...Y0(A,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Y0(A,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(A)=>{let B=f.prompt_submit??[];if(B.length>0)D1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"prompt_submit",userPromptSubmit:{prompt:A.userMessage,attachments:[]}}})},W=async(A)=>{let B=f.tool_call??[];if(B.length===0)return;return JO({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...Y0(A,$),hookName:"tool_call",iteration:A.iteration,tool_call:{id:A.call.id,name:A.call.name,input:A.call.input},preToolUse:{toolName:A.call.name,parameters:F4(A.call.input)}}})},j=async(A)=>{let B=f.tool_result??[];if(B.length===0)return;D1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"tool_result",iteration:A.iteration,tool_result:A.record,postToolUse:{toolName:A.record.name,parameters:F4(A.record.input),result:typeof A.record.output==="string"?A.record.output:JSON.stringify(A.record.output),success:!A.record.error,executionTimeMs:A.record.durationMs}}})},X=async(A)=>{let B=f.agent_end??[];if(B.length===0)return;D1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_end",iteration:A.iteration,turn:A.turn,taskComplete:{taskMetadata:{}}}})},H=async(A)=>{let B=f.agent_error??[];if(B.length===0)return;D1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_error",iteration:A.iteration,error:{name:A.error.name,message:A.error.message,stack:A.error.stack}}})},Y=async(A)=>{if(R9(A.reason)){let K=f.agent_abort??[];if(K.length>0)D1({commands:K,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_abort",reason:A.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;D1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"session_shutdown",reason:A.reason}})},V={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)V.beforeRun=async(A)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(m$(A.snapshot),B);return};if((f.prompt_submit?.length??0)>0)V.onEvent=async(A)=>{if(A.type!=="message-added"||A.message.role!=="user")return;await Z(U9({snapshot:A.snapshot},HX(A.message.content)))}}if((f.tool_call?.length??0)>0)V.beforeTool=async(A)=>{let B=await W(jX(A));return QO(B)};if((f.tool_result?.length??0)>0)V.afterTool=async(A)=>{await j(XX(A));return};if((f.agent_end?.length??0)>0)V.afterRun=async({snapshot:A,result:B})=>{if(B.status!=="completed")return;await X({...m$(A),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let A=V.afterRun;V.afterRun=async(B)=>{await A?.(B);let{snapshot:K,result:G}=B;if(G.status==="aborted"||R9(G.error?.message)){await Y({...m$(K),reason:G.error?.message});return}if(G.error)await H({...m$(K),iteration:G.iterations,error:G.error})}}return V}function R4($){return K4("core.hook_config_files",O9($))}function R1($,f){let J=$.map((Q)=>Q[f]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function P2($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:R1(f,"beforeRun"),afterRun:R1(f,"afterRun"),beforeModel:R1(f,"beforeModel"),afterModel:R1(f,"afterModel"),beforeTool:R1(f,"beforeTool"),afterTool:R1(f,"afterTool"),onEvent:R1(f,"onEvent")}}import{z as v$}from"zod";var U4=E1;var YX=v$.object({settings:E1,updatedAt:v$.string().datetime(),tokenSource:v$.enum(["manual","oauth","migration"]).default("manual")}),L4=v$.object({version:v$.literal(1),lastUsedProvider:v$.string().min(1).optional(),providers:v$.record(v$.string(),YX)});function $f(){return{version:1,providers:{}}}Z$();import{upsertWorkspaceInfo as ZO,WorkspaceManifestSchema as z9}from"@cline/shared";class O4{manifest;listeners=new Set;constructor($){this.manifest=z9.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await d8($);return this.manifest=ZO(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=j1($),J=this.manifest.workspaces[f];if(J)return this.manifest=z9.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath(f);return this.manifest=z9.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=j1($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}R0();import{createHash as WO}from"node:crypto";var VX=new Set,AX=new Set;function jO($){return WO("sha256").update($).digest("hex")}function XO($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function BX($){if(!$.telemetry)return;let f=jO($.rootPath),J=$.rootCount??1;if(!VX.has(f))VX.add(f),$6($.telemetry,{root_count:J,vcs_types:XO($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!AX.has(f)){AX.add(f);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",f6($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function YO($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function VO($,f,J){if(f.length>0)for(let W of f)J?.log(W.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(YO).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of $)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function AO($,f){let J=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!J&&!Q)return f;return{...f??{},...J?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function BO($,f){return HO($,f)}function KO($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function GO($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||PO($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function PO($){let f=$?.trim();if(!f)return;let J=j0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function FO($,f,J,Q,Z){let W=J.getProviderSettings($.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,X={...W??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.providerId==="openai-codex"?GO({sessionId:f,configHeaders:$.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:$.apiKey??W?.auth?.accessToken??W?.apiKey}):$.headers??W?.headers,reasoning:AO($,W?.reasoning),modelCatalog:j},H=f$(X);if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let V=$.fetch??H.fetch??Z;if(V)H.fetch=V;return H}async function KX($){let{input:f,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:H,onTeamEvent:Y,createSpawnTool:V,localRuntime:A,readSessionMetadata:B,writeSessionMetadata:K}=$,G=g$(f.config),{modelCatalogDefaults:R,userInstructionService:F,configExtensions:P,onTeamRestored:D,...O}=A??{},_=Object.keys(O).length>0?O:void 0,{workspaceInfo:L,workspaceMetadata:z,durationMs:y,vcsType:T,initError:e}=await ZW(G),$0=_?.extensionContext,a={...$0??{},workspace:{...L,...$0?.workspace??{}},session:{...$0?.session??{},sessionId:J},logger:$0?.logger??_?.logger,telemetry:$0?.telemetry??_?.telemetry??Z};BX({telemetry:a.telemetry,rootPath:L.rootPath,workspaceInfo:L,rootCount:1,vcsType:T,durationMs:y,initError:e,featureFlagEnabled:!0});let m=R4({cwd:f.config.cwd,workspacePath:G,rootSessionId:J,logger:_?.logger,workspaceInfo:L}),V0=OW(_?.hooks)?void 0:D4({rootSessionId:J,workspacePath:G,workspaceInfo:L}),B$=P2([_?.hooks,V0]),v;if(BO(P,"plugins"))try{v=await g8({pluginPaths:_?.pluginPaths,workspacePath:G,cwd:f.config.cwd,onEvent:H,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:L,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),VO(v.failures,v.warnings,_?.logger)}catch(Xf){let u=Xf instanceof Error?Xf.message:String(Xf);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${u})`)}let E=L5(m?[m]:void 0,L5(_?.extensions,IJ(v?.extensions))),p={...f.config,..._??{},sessionId:J,hooks:B$,extensions:E,extensionContext:a,telemetry:a.telemetry},o0=FO(p,J,Q,R,X),u0=P2([p.hooks,p.checkpoint?.enabled===!0?Kj({cwd:p.cwd,sessionId:J,logger:p.logger,createCheckpoint:p.checkpoint?.createCheckpoint,initialRunCount:KO(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:K}):void 0]),l$={...p,providerConfig:o0,workspaceMetadata:z,hooks:u0},T1=f.toolPolicies??p.toolPolicies??j,jf=P0(W,f.capabilities),T2=jf?.requestToolApproval,n4=jf?.toolExecutors,M1=new O4({currentWorkspacePath:L.rootPath,workspaces:{[L.rootPath]:L}});return{effectiveInput:f,config:l$,providerConfig:o0,workspaceMetadata:z,workspaceInfo:L,extensions:E,hooks:u0,toolPolicies:T1,requestToolApproval:T2,pluginSandboxShutdown:v?.shutdown,runtimeBuilderInput:{config:l$,hooks:u0,extensions:E,onTeamEvent:Y,createSpawnTool:V,onTeamRestored:D,userInstructionService:F,configExtensions:P,toolExecutors:n4,workspaceManager:M1,logger:l$.logger,telemetry:l$.telemetry}}}import{resolveDocumentsExtensionPath as DO}from"@cline/shared/storage";R0();function GX($,f,J,Q,Z){if(J)Q6($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else J6($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});RO($.telemetry,{workspacePath:Q})}function RO($,f){let J=DO("Hooks"),Q=e1(f.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[W,j]of Z.entries())K6($,W,j.global,j.workspace)}function PX($,f){for(let J of f.mentions)A6($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)Y6($,"file",J.length);for(let J of f.ignoredMentions)V6($,"file","not_found",J)}import{chmodSync as CX,existsSync as q9,mkdirSync as fz,readFileSync as Jz,writeFileSync as Qz}from"node:fs";import{basename as EX,dirname as w9}from"node:path";import{resolveProviderSettingsPath as Zz}from"@cline/shared/storage";import{existsSync as UO,mkdirSync as LO,readFileSync as OO,writeFileSync as zO}from"node:fs";import{mkdir as _O,readFile as yO,writeFile as NO}from"node:fs/promises";import{dirname as _9,join as TO}from"node:path";import*as z0 from"@cline/llms";import{ModelCapabilitySchema as MO,ProviderCapabilitySchema as qO,ProviderClientSchema as wO,ProviderProtocolSchema as SO}from"@cline/shared";import{z as l}from"zod";var CO=l.object({id:l.string().optional(),name:l.string().optional(),capabilities:l.array(MO).optional(),supportsVision:l.boolean().optional(),supportsAttachments:l.boolean().optional(),supportsReasoning:l.boolean().optional()}).passthrough(),EO=l.object({name:l.string(),baseUrl:l.string(),defaultModelId:l.string().optional(),protocol:SO.optional(),client:wO.optional(),capabilities:l.array(qO).optional(),modelsSourceUrl:l.string().optional()}).passthrough(),FX=l.object({provider:EO.optional(),models:l.record(l.string(),CO).optional()}).passthrough(),DX=l.object({version:l.literal(1),providers:l.record(l.string(),FX)}),hO=l.object({version:l.literal(1),providers:l.record(l.string(),l.unknown())}),z4=new Set;function RX($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function U1($){return TO(_9($.getFilePath()),"models.json")}function _4(){return{version:1,providers:{}}}function UX($){let f=hO.safeParse($);if(!f.success)return _4();let J={};for(let[Q,Z]of Object.entries(f.data.providers)){let W=FX.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function y9($){if(!UO($))return _4();try{let f=OO($,"utf8");return UX(JSON.parse(f))}catch{}return _4()}async function ff($){try{let f=await yO($,"utf8");return UX(JSON.parse(f))}catch{}return _4()}function LX($,f){LO(_9($),{recursive:!0});let J=DX.parse(f);zO($,`${JSON.stringify(J,null,2)}
558
- `,"utf8")}async function y4($,f){await _O(_9($),{recursive:!0});let J=DX.parse(f);await NO($,`${JSON.stringify(J,null,2)}
559
- `,"utf8")}function OX($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function zX($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function _X($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function bO($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function yX($,f){return $??f??"openai-chat"}function NX($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function kO($,f){let J=new Set(f?.capabilities??[]);if(f?.supportsVision)J.add("images");if(f?.supportsAttachments)J.add("files");if(f?.supportsReasoning)J.add("reasoning");return{id:$,name:f?.name??$,capabilities:J.size>0?[...J]:void 0}}function IO($,f){for(let[J,Q]of Object.entries(f??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;z0.registerModel($,Z,kO(Z,Q))}}function xO($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function gO($){return Object.assign({},...z0.resolveProviderModelCatalogKeys($).map((J)=>z0.getGeneratedModelsForProvider(J)))}function mO($){let f=$.provider.trim();if(!f||z0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let Q=z0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=gO(f),W=_X($.capabilities),j=W.length>0?W:void 0,X=$.model?.trim(),H={...Z,...Q?.models??{}};if(X)H[X]=xO(X,H[X],j);let Y=Object.keys(H).filter(Boolean),V=X||Y[0];if(!V)return;let A=yX($.protocol,Q?.provider.protocol),B=NX($.client,A,Q?.provider.client);z0.registerProvider({provider:{id:f,name:Q?.provider.name??RX(f),description:Q?.provider.description,protocol:A,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:V,capabilities:zX($.capabilities)??Q?.provider.capabilities,source:"file"},models:H})}function N4($){for(let f of Object.values($.providers))mO(f.settings)}function F2($,f){let J=f.models??{};if(!bO(f.provider)){IO($,J);return}let Q=_X(f.provider.capabilities),Z=Object.entries(J).map(([Y,V])=>({id:V.id?.trim()||Y.trim(),model:V})).filter(({id:Y})=>Y.length>0),W=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=yX(f.provider.protocol,void 0),X=NX(f.provider.client,j,void 0),H=Object.fromEntries(Z.map(({id:Y,model:V})=>[Y,{id:Y,name:V.name??Y,capabilities:Q.length>0?Q:void 0,status:"active"}]));z0.registerProvider({provider:{id:$,name:f.provider.name.trim()||RX($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:W,capabilities:zX(f.provider.capabilities),source:"file"},models:H})}function TX($){let f=U1($);if(z4.has(f))return;let J=y9(f);for(let[Q,Z]of Object.entries(J.providers))F2(Q,Z);z4.add(f)}async function MX($){let f=U1($);if(z4.has(f))return;let J=await ff(f);for(let[Q,Z]of Object.entries(J.providers))F2(Q,Z);z4.add(f)}import{existsSync as vO,readFileSync as cO}from"node:fs";import{dirname as uO,join as N9}from"node:path";import*as wX from"@cline/llms";import{resolveClineDataDir as dO}from"@cline/shared/storage";var SX="openai";function lO($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function C($){let f=$?.trim();return f?f:void 0}function qX($){if(!vO($))return;try{let f=cO($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function pO($){let f=$.dataDir??dO(),J=$.globalStatePath??N9(f,"globalState.json"),Q=$.secretsPath??N9(f,"secrets.json"),Z=qX(J),W=qX(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function rO($){try{let J=new URL($).hostname.toLowerCase();return J==="api.openai.com"||J.endsWith(".openai.azure.com")||J.endsWith(".services.ai.azure.com")}catch{return!1}}function iO($){let f=C($.openAiBaseUrl);if(!f)return!1;if($.azureApiVersion||$.azureIdentity)return!1;return!rO(f)}function T9($,f){if($==="openai"&&iO(f))return SX;return $}function nO($,f,J,Q){let Z=J==="plan"?"planMode":"actMode",W=f===Q?C(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?C(typeof $[X]==="string"?$[X]:void 0):void 0)??W}function aO($,f,J){let Q=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,W=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??Q,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,H=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&H===void 0)return;return{...X?{effort:X}:{},...H!==void 0?{budgetTokens:H}:{}}}function tO($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),Q=C(J.access_token),Z=C(J.refresh_token),W=C(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function sO($){let f=wX.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function oO($,f,J,Q){let Z=T9($,f),W=C(Q==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=nO(f,$,Q,W)??sO(Z),X=aO(f,Z,Q),H=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},V={};if($==="openai-codex")Object.assign(V,tO(J));if($==="cline")try{let P=C(J["cline:clineAccountId"]);if(P)V.auth={...V.auth??{},...lO(P)}}catch{}if($==="openai"&&f.openAiHeaders)V.headers=f.openAiHeaders;if($==="bedrock")V.aws={accessKey:C(J.awsAccessKey),secretKey:C(J.awsSecretKey),sessionToken:C(J.awsSessionToken),region:C(f.awsRegion),authentication:f.awsAuthentication,profile:f.awsUseProfile?C(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:C(f.awsBedrockEndpoint),customModelBaseId:C(Q==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)};if($==="vertex")V.gcp={projectId:C(f.vertexProjectId),region:C(f.vertexRegion)};if($==="openai"&&(f.azureApiVersion||f.azureIdentity!==void 0))V.azure={apiVersion:C(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")V.sap={clientId:C(J.sapAiCoreClientId),clientSecret:C(J.sapAiCoreClientSecret),tokenUrl:C(f.sapAiCoreTokenUrl),resourceGroup:C(f.sapAiResourceGroup),deploymentId:C(Q==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){V.oca={mode:f.ocaMode};let P=C(J.ocaRefreshToken);if(P)V.auth={...V.auth??{},refreshToken:P}}if($==="qwen")V.apiLine=f.qwenApiLine;if($==="moonshot")V.apiLine=f.moonshotApiLine;if($==="zai")V.apiLine=f.zaiApiLine;if($==="minimax")V.apiLine=f.minimaxApiLine;let A={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=C(Y[$]),K=C(A[$]),G={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...K?{baseUrl:K}:{},...X?{reasoning:X}:{},...H?{timeout:H}:{},...V},R=U4.safeParse(G);if(!R.success)return;return Object.keys(G).filter((P)=>P!=="provider").length>0?R.data:void 0}function eO($,f){if($!==SX)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model}}}}function $z($,f){let J=new Set;for(let Q of[$.actModeApiProvider,$.planModeApiProvider]){let Z=C(Q);if(Z)J.add(Z)}if(C(f.apiKey))J.add("anthropic");if(C(f.openRouterApiKey))J.add("openrouter");if(C(f.openAiApiKey))J.add("openai");if(C(f.openAiNativeApiKey))J.add("openai-native");if(C(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(C(f.geminiApiKey))J.add("gemini");if(C(f.ollamaApiKey))J.add("ollama");if(C(f.awsAccessKey)||C(f.awsBedrockApiKey))J.add("bedrock");if(C($.vertexProjectId)||C($.vertexRegion))J.add("vertex");if(C(f.clineApiKey))J.add("cline");if(C(f.ocaApiKey))J.add("oca");return J}function M9($){let f=$.providerSettingsManager.read(),J=pO($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=$z(Q,Z),X=$f();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let H=new Date().toISOString(),Y=0,V=N9(uO($.providerSettingsManager.getFilePath()),"models.json"),A=y9(V),B=0;for(let R of j){let F=T9(R,Q);if(X.providers[F])continue;let P=oO(R,Q,Z,W);if(!P)continue;X.providers[F]={settings:P,updatedAt:H,tokenSource:"migration"},Y+=1;let D=eO(F,P);if(D&&!A.providers[F])A.providers[F]=D,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let K=C(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),G=K?T9(K,Q):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(G&&X.providers[G]?G:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)LX(V,A);return{migrated:Y>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}function Wz(){return new Date().toISOString()}function jz($){if(EX($)!=="providers.json")return;let f=w9($);if(EX(f)!=="settings")return;return w9(f)}class c${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??Zz(),this.dataDir=$.dataDir??jz(this.filePath),this.dataDir||!$.filePath)M9({providerSettingsManager:this,dataDir:this.dataDir});if(TX(this),N4(this.read()),q9(this.filePath))try{CX(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!q9(this.filePath))return $f();try{let $=Jz(this.filePath,"utf8"),f=JSON.parse($),J=L4.safeParse(f);if(J.success)return N4(J.data),J.data}catch{}return $f()}write($){let f=L4.parse($),J=w9(this.filePath);if(!q9(J))fz(J,{recursive:!0,mode:448});Qz(this.filePath,`${JSON.stringify(f,null,2)}
560
- `,"utf8");try{CX(this.filePath,384)}catch{}N4(f)}saveProviderSettings($,f={}){let J=U4.parse($),Q=this.read(),Z=J.provider,W=f.setLastUsed!==!1,j=Q.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",H={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:Wz(),tokenSource:X}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(H),H}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return f$(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return f$(f,$)}async refreshCatalog(){try{await d2({})}catch{}}}R0();J4();import{execFile as Xz}from"node:child_process";import{promisify as Hz}from"node:util";var Jf=Hz(Xz);function S9($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let X=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...X?{kind:X}:{}}]})}function hX($,f){let J=S9($).filter((Z)=>Z.runCount<=f),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function Yz($,f){return $.reduce((J,Q)=>{if(Q.runCount>f)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function bX($,f){let J=0;for(let Q=0;Q<$.length;Q+=1){let Z=$[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return Q}throw Error(`Could not find user message for checkpoint run ${f}`)}function Vz($,f){let J=bX($,f);return $.slice(0,J+1)}function kX($,f){let J=bX($,f);return $.slice(0,J)}function IX($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=Yz(S9($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...$.restoreMessages!==!1?{messages:Vz($.messages??[],f)}:{}}}async function xX($,f){if((await Jf("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await Jf("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await Jf("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await Jf("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await Jf("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await Jf("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}class v0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function Az($){let f=$.sessionId.trim();if(!f)throw new v0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new v0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new v0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new v0("invalid_restore","checkpointRunCount must be a positive integer");return f}class Qf{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,Q=Az({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(Q);if(!Z)throw new v0("session_not_found",`Session ${Q} not found`);let W=f?await $.readMessages(Q):void 0;if(f&&W?.length===0)throw new v0("session_messages_not_found",`No messages found for session ${Q}`);let j=IX({session:Z,messages:W,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??xX)(j.cwd,j.checkpoint);let X=h$({session:Z,messages:W});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let H=hX(Z,$.checkpointRunCount),Y=$.restore?.omitCheckpointMessageFromSession?kX(W??[],$.checkpointRunCount):j.messages??[],V={sourceSession:Z,sourceMessages:W,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:H,initialMessages:Y,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new v0("invalid_restore","start is required when restore.messages is true");let A=$.buildStartInput?await $.buildStartInput(V,$.start):$.start,B=await $.startSession(A),K=$.getStartedSessionId?.(B);if(K)await($.retainCheckpointRefs??Bj)(j.cwd,K,H?.history??[]);let G=K&&$.readRestoredSession?await $.readRestoredSession(K):void 0;return{sessionId:K,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...G?{restoredSnapshot:h$({session:G,messages:Y})}:{}}}}import{hasRuntimeConfigExtension as Nz}from"@cline/shared";import{nanoid as Tz}from"nanoid";Z$();import{appendFileSync as Bz,existsSync as Zf,mkdirSync as gX,readdirSync as Kz,readFileSync as mX,renameSync as Gz,writeFileSync as Pz}from"node:fs";import{join as C9}from"node:path";import{resolveTeamDataDir as Fz}from"@cline/shared/storage";function vX(){return new Date().toISOString()}function E9($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function cX($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class T4{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??Fz()}init(){this.ensureTeamDir()}listTeamNames(){if(!Zf(this.teamDirPath))return[];return Kz(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>Zf(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?cX(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!Zf(J))return[];return mX(J,"utf8").split(`
561
- `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?cX(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),Bz(this.historyPath($),`${JSON.stringify({ts:vX(),eventType:f.type,payload:f})}
562
- `,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let Q={version:1,updatedAt:vX(),teamState:f,teammates:J},Z=this.statePath($),W=`${Z}.tmp`;Pz(W,`${JSON.stringify(Q,null,2)}
563
- `,"utf8"),Gz(W,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let Q=J.teamState.runs.filter((W)=>W.status==="queued"||W.status==="running").map((W)=>W.id);if(Q.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((W)=>W.status==="queued"||W.status==="running"?{...W,status:"interrupted",error:f,endedAt:Z}:W)},this.persistRuntime($,J.teamState,J.teammates),Q}ensureTeamDir(){if(!Zf(this.teamDirPath))gX(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=C9(this.ensureTeamDir(),E9($));if(!Zf(f))gX(f,{recursive:!0});return f}statePath($){return C9(this.ensureTeamDir(),E9($),"state.json")}historyPath($){return C9(this.ensureTeamDir(),E9($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!Zf(f))return;try{let J=JSON.parse(mX(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as Dz,mkdirSync as Rz}from"node:fs";import{join as Uz}from"node:path";import{safeJsonParse as uX}from"@cline/shared";import{loadSqliteDb as Lz,nowIso as h9}from"@cline/shared/db";import{resolveDbDataDir as Oz}from"@cline/shared/storage";function zz(){return Oz()}function Wf($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function _z($){let f=uX($);if(!Array.isArray(f))return[];let J=[];for(let Q of f){if(!Q||typeof Q!=="object")continue;let Z=Q,W=Z.agentId,j=Z.rolePrompt;if(typeof W!=="string"||!W.trim())continue;if(typeof j!=="string"||!j.trim())continue;let X={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())X.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))X.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(X)}return J}function yz($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class D2{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??zz()}init(){this.getRawDb()}ensureTeamDir(){if(!Dz(this.teamDirPath))Rz(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return Uz(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=Lz(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
552
+ `)}function YX($){let f=$.summarizer,J=(Z)=>{if(Z.providerId==="openai-codex"){let{maxOutputTokens:W,...j}=Z;return{...j,thinking:!1}}return{...Z,maxOutputTokens:Z.maxOutputTokens??ij,thinking:!1}};if(!f)return J($.activeProviderConfig);let Q=f.providerConfig?.providerId===f.providerId?f.providerConfig:void 0;return J({...Q??{},providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey??Q?.apiKey,baseUrl:f.baseUrl??Q?.baseUrl,headers:f.headers??Q?.headers,knownModels:f.knownModels??Q?.knownModels,maxOutputTokens:f.maxOutputTokens??ij})}function VX($){return{role:"user",content:`Context summary:
553
+
554
+ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fileOps,tokensBefore:$.tokensBefore,generatedAt:Date.now()}}}async function JO($){let f=await fO($.providerConfig),J="";for await(let Q of f.createMessage("Summarize the provided coding session into a concise continuation note with detailed next steps.",[{role:"user",content:$.request}])){if(Q.type==="text"){J+=Q.text;continue}if(Q.type==="done"&&!Q.success&&Q.error)throw Error(Q.error)}return $.logger?.debug("Generated compaction summary",{outputChars:J.length,modelId:$.providerConfig.modelId,providerId:$.providerConfig.providerId}),J.trim()}function QO($){try{return JSON.stringify($).length}catch{return String($).length}}async function AX($){let f=$.context.messages;if(f.length<2)return;let J=WX(f,$.preserveRecentTokens,$.estimateMessageTokens);if(J<=0||J>=f.length)return;let Q=f.slice(0,J),Z=ZX(Q),W=Z>=0?N9(Q[Z])?.summary:void 0,j=Z>=0?Q.slice(Z+1):Q;if(j.length===0)return;let X=jX(Q),H=$X(j),Y=HX({previousSummary:W,conversationText:H,fileOps:X});$.logger?.debug("Agentic compaction summarizer diagnostics",{messagesToSummarize:Q.length,newMessagesToFold:j.length,preservedMessages:f.length-J,previousSummaryChars:W?.length??0,conversationTextChars:H.length,summaryRequestChars:Y.length,summaryRequestEstimatedTokens:L9(Y.length),newMessagesJsonChars:QO(j),maxInputTokens:$.context.maxInputTokens,triggerTokens:$.context.triggerTokens});let V=await JO({providerConfig:YX({activeProviderConfig:$.providerConfig,summarizer:$.summarizer}),request:Y,logger:$.logger});if(!V.trim())return;let A=XX(V,X),B=f.reduce((D,F)=>D+$.estimateMessageTokens(F),0),G=[VX({summary:A,fileOps:X,tokensBefore:B}),...f.slice(J)],K=G.reduce((D,F)=>D+$.estimateMessageTokens(F),0);return $.logger?.debug("Performed agentic compaction",{messagesBefore:f.length,messagesAfter:G.length,messagesSummarized:J,messagesPreserved:f.length-J,tokensBefore:B,tokensAfter:K,maxInputTokens:$.context.maxInputTokens}),{messages:G}}function KX($){if(F8($))return;if(typeof $.content==="string"){let J=$.content.trim();return J?{...$,content:J}:void 0}let f=$.content.filter((J)=>J.type!=="text"||J.text.trim());if(f.length===0)return;return{...$,content:f.map((J)=>J.type==="text"?{...J,text:J.text.trim()}:J.type==="tool_result"?{...J,content:_9(J.content)}:J)}}function U8($,f){return $.reduce((J,Q)=>J+f(Q),0)}function BX($,f){let J=Math.max(1,f),Q=Math.max(16,J*4);if(typeof $.content==="string"){let j=g$($.content,Q).trim();return{...$,content:j||"..."}}let Z=Q,W=$.content.map((j)=>{if(j.type!=="text"||Z<=0)return j;let X=g$(j.text,Z).trim();return Z-=X.length,{...j,text:X||"..."}});return{...$,content:W}}function ZO($,f){let J=JX($),Q=U6($),Z=QX($),W=[];for(let j=0;j<$.length;j+=1){let X=KX($[j]);if(!X)continue;W.push({index:j,message:X,estimatedTokens:f(X),isFirstUser:j===J,isLastUser:j===Q,isLastAssistant:j===Z})}return W}function GX($,f,J,Q){let Z=$[f];Z.message=J,Z.estimatedTokens=Q(J)}function WO($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_use")f.add(J.id);return f}function jO($){let f=new Set;if(!Array.isArray($.content))return f;for(let J of $.content)if(J.type==="tool_result")f.add(J.tool_use_id);return f}function FX($){return new Set([...WO($.message),...jO($.message)])}function XO($){let f=new Map;for(let J=0;J<$.length;J+=1)for(let Q of FX($[J])){let Z=f.get(Q);if(Z)Z.add(J);else f.set(Q,new Set([J]))}return f}function HO($,f){let J=XO($),Q=new Set,Z=[f];while(Z.length>0){let W=Z.shift();if(W===void 0||Q.has(W))continue;Q.add(W);for(let j of FX($[W]))for(let X of J.get(j)??[])if(!Q.has(X))Z.push(X)}return Q}function D6($,f,J,Q){let Z=U8($.map((W)=>W.message),Q);for(let W=0;W<$.length&&Z>J;){if(!f($[W])){W+=1;continue}let j=HO($,W);Z-=Array.from(j).reduce((X,H)=>X+$[H].estimatedTokens,0);for(let X of Array.from(j).sort((H,Y)=>Y-H))$.splice(X,1)}}function YO($,f,J){let Q=U8($.map((W)=>W.message),J);if(Q<=f)return;for(let W=$.length-1;W>=0&&Q>f;W-=1){let j=$[W];if(j.isFirstUser)continue;let X=Math.max(oj,j.estimatedTokens-(Q-f));if(X>=j.estimatedTokens)continue;GX($,W,BX(j.message,X),J),Q=U8($.map((H)=>H.message),J)}if(Q<=f)return;let Z=$.findIndex((W)=>W.isFirstUser);if(Z>=0){let W=Math.max(1,$[Z].estimatedTokens-(Q-f));GX($,Z,BX($[Z].message,W),J)}}function VO($,f){return JSON.stringify($)!==JSON.stringify(f)}function AO($){let f=U6($);if(f<0||f===0&&!P8($[0]))return{compactable:$,protectedTail:[]};return{compactable:$.slice(0,f),protectedTail:$.slice(f)}}function PX($){let f=Math.max(1,Math.min($.context.triggerTokens,$.context.maxInputTokens)),{compactable:J,protectedTail:Q}=AO($.context.messages);if(J.length===0)return;let Z=ZO(J,$.estimateMessageTokens);if(Z.length===0)return;D6(Z,(H)=>H.message.role==="assistant"&&!H.isLastAssistant,f,$.estimateMessageTokens),D6(Z,(H)=>H.message.role==="user"&&!H.isFirstUser&&!H.isLastUser,f,$.estimateMessageTokens),D6(Z,(H)=>H.message.role==="assistant"&&H.isLastAssistant,f,$.estimateMessageTokens),D6(Z,(H)=>H.message.role==="user"&&H.isLastUser&&!H.isFirstUser,f,$.estimateMessageTokens),YO(Z,f,$.estimateMessageTokens);let W=[...Z.map((H)=>H.message),...Q];if(!VO($.context.messages,W))return;let j=U8([...J.map((H)=>KX(H)??H),...Q],$.estimateMessageTokens),X=U8(W,$.estimateMessageTokens);return $.logger?.debug("Performed basic compaction",{messagesBefore:$.context.messages.length,messagesAfter:W.length,messagesRemoved:$.context.messages.length-W.length,tokensBefore:j,tokensAfter:X,targetTokens:f,maxInputTokens:$.context.maxInputTokens}),{messages:W}}function UX($){try{return JSON.stringify($).length}catch{return String($).length}}function BO($){let f=0,J=0,Q=0;for(let Z of $){if(!Array.isArray(Z.content))continue;for(let W of Z.content){if(W.type!=="tool_result")continue;let j=UX(W.content);f+=1,J+=j,Q=Math.max(Q,j)}}return{toolResultCount:f,toolResultSerializedChars:J,maxToolResultSerializedChars:Q}}var GO={basic:({context:$,estimateMessageTokens:f,logger:J})=>PX({context:$,estimateMessageTokens:f,logger:J}),agentic:({context:$,providerConfig:f,compaction:J,mode:Q,estimateMessageTokens:Z,logger:W})=>AX({context:$,providerConfig:f,summarizer:J?.summarizer,preserveRecentTokens:Q==="manual"?Math.min(J?.preserveRecentTokens??z9,$.triggerTokens):J?.preserveRecentTokens??z9,estimateMessageTokens:Z,logger:W})};function KO($){if(typeof $.config.reserveTokens==="number"){let Q=Math.max(0,$.config.reserveTokens),Z=Math.max(0,$.maxInputTokens-Q);return{shouldCompact:$.inputTokens>Z,triggerTokens:Z,thresholdRatio:$.maxInputTokens>0?Z/$.maxInputTokens:0}}if(typeof $.config.thresholdRatio!=="number"){let Q=Math.max(0,Math.min($.maxInputTokens-tj,$.maxInputTokens*O9));return{shouldCompact:$.inputTokens>Q,triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}let f=$.config.thresholdRatio??O9,J=$.maxInputTokens*f;return{shouldCompact:$.inputTokens>J,triggerTokens:J,thresholdRatio:f}}function FO($){let f=typeof $.manualTargetRatio==="number"&&Number.isFinite($.manualTargetRatio)?$.manualTargetRatio:0.5,J=Math.min(0.95,Math.max(0.05,f)),Q=Math.max(1,Math.floor(Math.min($.autoTriggerTokens,$.inputTokens*J)));return{triggerTokens:Q,thresholdRatio:$.maxInputTokens>0?Q/$.maxInputTokens:0}}function T9($,f={}){let J=$.compaction;if(J?.enabled!==!0)return;let Q=$.providerConfig??{providerId:$.providerId,modelId:$.modelId},Z=fX(),W=J?.strategy??"basic",j=GO[W],X=f.mode??"auto",H=J?.compact?"custom":W;return async(Y)=>{let V=Y.apiMessages.reduce((L,N)=>L+Z(N),0),A=J?.maxInputTokens??Y.model.info?.maxInputTokens??Y.model.info?.contextWindow??aj;if(typeof A!=="number"||!Number.isFinite(A)||A<=0)return;let B=KO({inputTokens:V,maxInputTokens:A,config:{reserveTokens:J?.reserveTokens,thresholdRatio:J?.thresholdRatio}});if($.logger?.debug("Context compaction diagnostics",{mode:X,strategy:W,iteration:Y.iteration,providerId:$.providerId,modelId:$.modelId,inputTokens:V,maxInputTokens:A,triggerTokens:B.triggerTokens,thresholdRatio:B.thresholdRatio,shouldCompact:B.shouldCompact,messageCount:Y.messages.length,apiMessageCount:Y.apiMessages.length,apiMessagesJsonChars:UX(Y.apiMessages),...BO(Y.apiMessages)}),X==="auto"&&!B.shouldCompact)return;let G=X==="manual"?FO({inputTokens:V,maxInputTokens:A,autoTriggerTokens:B.triggerTokens,manualTargetRatio:f.manualTargetRatio}):B,K={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId,iteration:Y.iteration,messages:Y.messages,model:Y.model,maxInputTokens:A,triggerTokens:G.triggerTokens,thresholdRatio:G.thresholdRatio,utilizationRatio:A>0?V/A:0},D=X==="manual"?"manual_compaction":"auto_compaction";Y.emitStatusNotice?.(X==="manual"?"compacting":"auto-compacting",{kind:D,reason:D,iteration:Y.iteration,triggerTokens:G.triggerTokens,maxInputTokens:A});let F=Y.messages.length,P=Date.now(),U=J?.compact?await J.compact(K):await j({context:K,providerConfig:{...Q,abortSignal:Y.abortSignal},compaction:J,mode:X,estimateMessageTokens:Z,logger:$.logger}),z=Date.now()-P,_=$.sessionId??Y.conversationId,R={agentId:Y.agentId,conversationId:Y.conversationId,parentAgentId:Y.parentAgentId??void 0};if(U?.messages){let L=U.messages.reduce((N,M)=>N+Z(M),0);$.logger?.log("Context compaction completed",{severity:"info",strategy:W,maxInputTokens:A,inputTokens:V,afterTokens:L,tokensSaved:V-L,utilizationBefore:`${(V/A*100).toFixed(1)}%`,utilizationAfter:`${(L/A*100).toFixed(1)}%`,thresholdTrigger:`${(G.thresholdRatio*100).toFixed(1)}%`,messagesBefore:F,messagesAfter:U.messages.length,messagesRemoved:F-U.messages.length}),Tf($.telemetry,{ulid:_,strategy:H,mode:X,messagesBefore:F,messagesAfter:U.messages.length,messagesRemoved:F-U.messages.length,tokensBefore:V,tokensAfter:L,tokensSaved:V-L,triggerTokens:G.triggerTokens,maxInputTokens:A,thresholdRatio:G.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...R})}else Mf($.telemetry,{ulid:_,strategy:H,mode:X,reason:"no_result",tokensBefore:V,triggerTokens:G.triggerTokens,maxInputTokens:A,thresholdRatio:G.thresholdRatio,durationMs:z,provider:$.providerId,modelId:$.modelId,...R});return U}}G0();function B0(){return{inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0,totalCost:0}}function H0($,f){return{inputTokens:$.inputTokens+Math.max(0,f.inputTokens??0),outputTokens:$.outputTokens+Math.max(0,f.outputTokens??0),cacheReadTokens:$.cacheReadTokens+Math.max(0,f.cacheReadTokens??0),cacheWriteTokens:$.cacheWriteTokens+Math.max(0,f.cacheWriteTokens??0),totalCost:$.totalCost+Math.max(0,f.totalCost??0)}}function R6($){let f=B0();for(let J of $)f=H0(f,J);return f}function f2($){return typeof $==="number"&&Number.isFinite($)?$:0}function L6($){let f=B0();for(let J of $){let Q=J.metrics;if(!Q)continue;f=H0(f,{inputTokens:f2(Q.inputTokens),outputTokens:f2(Q.outputTokens),cacheReadTokens:f2(Q.cacheReadTokens),cacheWriteTokens:f2(Q.cacheWriteTokens),totalCost:f2(Q.cost)})}return f}function PO($){for(let f=$.length-1;f>=0;f-=1){let J=$[f];if(J?.role!=="assistant")continue;let Q=f2(J.metrics?.inputTokens);return Q>0?Q:void 0}return}function UO($){if(!$||typeof $!=="object")return;let f=$,J=f.skill??f.skill_name??f.skillName;if(typeof J!=="string")return;let Q=J.trim();return Q.length>0?Q:void 0}function M9($){if(!$||typeof $!=="object")return{};let f=$;return{agentId:typeof f.agentId==="string"?f.agentId:void 0,conversationId:typeof f.conversationId==="string"?f.conversationId:void 0,parentAgentId:typeof f.parentAgentId==="string"?f.parentAgentId:void 0}}function V$($){let f=$.agentId?.trim();if(!f)return;let J=$.parentAgentId?.trim()||void 0,Q=$.teamRole,Z="root";if(Q==="teammate")Z="team_teammate";else if(Q==="lead")Z="team_lead";else if(J)Z="subagent";return{agentId:f,agentKind:Z,conversationId:$.conversationId?.trim()||void 0,parentAgentId:J,createdByAgentId:$.createdByAgentId?.trim()||J||void 0,isSubagent:Boolean(J),teamId:$.teamId?.trim()||void 0,teamName:$.teamName?.trim()||void 0,teamRole:Q,teamAgentId:$.teamAgentId?.trim()||void 0}}function DO($){return{inputTokens:$.inputTokens,outputTokens:$.outputTokens,cacheWriteTokens:$.cacheWriteTokens,cacheReadTokens:$.cacheReadTokens,totalCost:$.cost}}function RO($){let f=$.isPrimaryAgentEvent?[$.overrides?.agentId,$.eventMetadata.agentId,$.overrides?.teamAgentId]:[$.overrides?.teamAgentId,$.overrides?.agentId,$.eventMetadata.agentId,$.eventMetadata.conversationId];for(let J of f){let Q=J?.trim();if(Q)return Q}return $.isPrimaryAgentEvent?"root":"unknown"}function q9($,f,J){let{sessionId:Q,config:Z,liveSession:W,emit:j}=$,X=Z.telemetry,H=W?.runtime.teamRuntime,Y=J?.isPrimaryAgentEvent??!0,V=M9(f),A=V$({agentId:J?.agentId??V.agentId,conversationId:J?.conversationId??V.conversationId,parentAgentId:J?.parentAgentId??V.parentAgentId,createdByAgentId:J?.createdByAgentId,teamId:J?.teamId??H?.getTeamId(),teamName:J?.teamName??H?.getTeamName(),teamRole:J?.teamRole,teamAgentId:J?.teamAgentId});if(f.type==="content_start"&&f.contentType==="tool"&&f.toolName==="skills"){let B=UO(f.input);if(B)Df(X,{ulid:Q,skillName:B,skillSource:"project",skillsAvailableGlobal:0,skillsAvailableProject:0,provider:Z.providerId,modelId:Z.modelId,...A})}if(f.type==="content_end"&&f.contentType==="tool"){let B=f.toolName??"unknown",G=!f.error;if(Uf(X,{ulid:Q,tool:B,autoApproved:void 0,success:G,modelId:Z.modelId,provider:Z.providerId,...A}),!G&&(B==="editor"||B==="apply_patch"))Rf(X,{ulid:Q,modelId:Z.modelId,provider:Z.providerId,errorType:f.error,...A})}if(f.type==="notice"&&f.reason==="api_error")C8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.message,...A});if(f.type==="error")C8(X,{ulid:Q,model:Z.modelId,provider:Z.providerId,errorMessage:f.error?.message??"unknown error",...A});if(f.type==="usage"&&W?.turnUsageBaseline){let B=DO(f);if(Y){W.turnPrimaryUsage=H0(W.turnPrimaryUsage??B0(),B);let K=H0(W.turnUsageBaseline,W.turnPrimaryUsage);$.usageBySession.set(Q,K),A2(X,{ulid:Q,provider:Z.providerId,model:Z.modelId,source:"assistant",mode:Z.mode,...A}),Ff(X,{ulid:Q,tokensIn:f.inputTokens,tokensOut:f.outputTokens,cacheWriteTokens:f.cacheWriteTokens,cacheReadTokens:f.cacheReadTokens,totalCost:f.cost,model:Z.modelId,...A})}else{let K=RO({isPrimaryAgentEvent:Y,overrides:J,eventMetadata:V}),D=W.turnUsageByAgent??new Map;W.turnUsageByAgent=D,D.set(K,H0(D.get(K)??B0(),B))}let G=H0(W.turnPrimaryUsage??B0(),R6(W.turnUsageByAgent?.values()??[]));$.aggregateUsageBySession.set(Q,H0(W.turnAggregateUsageBaseline??W.turnUsageBaseline,G))}if(f.type==="iteration_end"&&Y)$.persistMessages(Q,W?.agent.getMessages()??[],W?.config.systemPrompt);j({type:"agent_event",payload:{sessionId:Q,event:f,teamAgentId:J?.teamAgentId,teamRole:J!==void 0?J.teamRole??(Y?"lead":void 0):void 0}}),j({type:"chunk",payload:{sessionId:Q,stream:"agent",chunk:mW(f),ts:Date.now()}})}function v$($){return $.workspaceRoot??$.cwd}import{hasRuntimeConfigExtension as iO}from"@cline/shared";import{spawn as yO}from"node:child_process";import{appendFileSync as wO,readFileSync as SO}from"node:fs";import{join as hO}from"node:path";import{augmentNodeCommandForDebug as OX,withResolvedClineBuildEnv as E9}from"@cline/shared";import{ensureHookLogDir as RX}from"@cline/shared/storage";function O6($,f){if(!f)return;return{name:$,manifest:{capabilities:["hooks"]},hooks:f}}import{existsSync as LO,readdirSync as OO}from"node:fs";import{basename as zO,extname as _O,join as NO}from"node:path";import{HOOKS_CONFIG_DIRECTORY_NAME as DX,resolveHooksConfigSearchPaths as TO}from"@cline/shared/storage";function y9($){return TO($)}var z6;((V)=>{V.TaskStart="TaskStart";V.TaskResume="TaskResume";V.TaskCancel="TaskCancel";V.TaskComplete="TaskComplete";V.TaskError="TaskError";V.PreToolUse="PreToolUse";V.PostToolUse="PostToolUse";V.UserPromptSubmit="UserPromptSubmit";V.PreCompact="PreCompact";V.SessionShutdown="SessionShutdown"})(z6||={});var w9={["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"},MO=new Map(Object.values(z6).map(($)=>[$.toLowerCase(),$])),qO=new Set(["",".sh",".bash",".zsh",".js",".mjs",".cjs",".ts",".mts",".cts",".py",".ps1"]);function S9($){let f=_O($).toLowerCase();if(!qO.has(f))return;let J=zO($,f).trim().toLowerCase();return MO.get(J)}function J2($){let f=[],J=new Set,Q=y9($).filter((Z)=>LO(Z));for(let Z of Q)try{for(let W of OO(Z,{withFileTypes:!0})){if(!W.isFile())continue;let j=S9(W.name);if(!j)continue;let X=NO(Z,W.name);if(J.has(X))continue;J.add(X),f.push({fileName:j,hookEventName:w9[j],path:X})}}catch{}return f.sort((Z,W)=>Z.path.localeCompare(W.path))}function N6($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))f[J]=typeof Q==="string"?Q:JSON.stringify(Q);return f}function _6($,f,J){let Q=J instanceof Error?`: ${J.message}`:"",Z=`${f}${Q}`;if($){try{$.log(Z,{severity:"warn",...J!==void 0?{error:J}:{}})}catch{}return}console.warn(Z)}function CO($,f){if(!f)return $;if(!$)return{...f};let J=[$.context,f.context].filter((Z)=>typeof Z==="string"&&Z.length>0).join(`
555
+ `),Q=[...$.appendMessages??[],...f.appendMessages??[]];return{cancel:$.cancel===!0||f.cancel===!0?!0:void 0,review:$.review===!0||f.review===!0?!0:void 0,context:J||void 0,overrideInput:f.overrideInput!==void 0?f.overrideInput:$.overrideInput,systemPrompt:f.systemPrompt!==void 0?f.systemPrompt:$.systemPrompt,appendMessages:Q.length>0?Q:void 0}}function EO($){if(!$||typeof $!=="object")return;let f=$,J=typeof f.context==="string"?f.context:typeof f.contextModification==="string"?f.contextModification:typeof f.errorMessage==="string"?f.errorMessage:void 0;return{cancel:typeof f.cancel==="boolean"?f.cancel:void 0,review:typeof f.review==="boolean"?f.review:void 0,context:J,overrideInput:Object.hasOwn(f,"overrideInput")?f.overrideInput:void 0}}function h9($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function Y0($,f){let J=process.env.CLINE_USER_ID?.trim()||process.env.USER?.trim()||"unknown",Q={rootSessionId:f.rootSessionId||$.conversationId};return{clineVersion:process.env.CLINE_VERSION?.trim()||"",timestamp:new Date().toISOString(),taskId:$.conversationId,sessionContext:Q,workspaceRoots:f.workspacePath?[f.workspacePath]:[],workspaceInfo:f.workspaceInfo,userId:J,agent_id:$.agentId,parent_agent_id:$.parentAgentId}}function bO($){let f=$.trim();if(!f)return{};let Q=f.split(`
556
+ `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse hook stdout JSON"}}}async function kO($,f){let J=$.stdin;if(!J)throw Error("hook command failed to create stdin");await new Promise((Q,Z)=>{let W=!1,j=()=>{J.off("error",H),J.off("finish",Y),$.off("close",V)},X=(A)=>{if(W)return;if(W=!0,j(),A){let B=A.code;if(B==="EPIPE"||B==="ERR_STREAM_DESTROYED"){Q();return}Z(A);return}Q()},H=(A)=>X(A),Y=()=>X(),V=()=>X();J.on("error",H),J.once("finish",Y),$.once("close",V);try{J.end(f)}catch(A){X(A)}})}async function zX($,f){if(f.command.length===0)throw Error("runHookCommand requires non-empty command");try{return await LX($,f)}catch(J){let Q=mO(f.command,process.platform,J);if(!Q)throw J;return await LX($,{...f,command:Q})}}async function LX($,f){let J=OX(f.command,{env:f.env,debugRole:"hook"}),Q=yO(J[0],J.slice(1),{cwd:f.cwd,env:E9(f.env),stdio:f.detached?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:f.detached}),Z=new Promise((B)=>{Q.once("spawn",()=>B())}),W=new Promise((B,G)=>{Q.once("error",(K)=>G(K))}),j=JSON.stringify($);if(await Promise.race([Z,W]),await kO(Q,j),f.detached){Q.unref();return}if(!Q.stdout||!Q.stderr)throw Error("hook command failed to create stdout/stderr");let X="",H="",Y=!1,V;Q.stdout.on("data",(B)=>{X+=B.toString()}),Q.stderr.on("data",(B)=>{H+=B.toString()});let A=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{Y=!0,Q.kill("SIGKILL")},f.timeoutMs);Q.once("close",(G)=>{if(V)clearTimeout(V);let{parsedJson:K,parseError:D}=bO(X);B({exitCode:G,stdout:X,stderr:H,parsedJson:K,parseError:D,timedOut:Y})})});return await Promise.race([A,W])}function IO($){try{let J=SO($,"utf8").split(/\r?\n/,1)[0]?.trim();if(!J?.startsWith("#!"))return;let Q=J.slice(2).trim();if(!Q)return;let Z=Q.split(/\s+/).filter(Boolean);return Z.length>0?Z:void 0}catch{return}}function xO($){return!!($&&typeof $==="object"&&("code"in $)&&$.code==="ENOENT")}function mO($,f=process.platform,J){if(f!=="win32"||!xO(J))return;if($[0]!=="py"||$[1]!=="-3")return;return["python",...$.slice(2)]}function _X($){if($.length===0)return;let[f,...J]=$,Q=f.replace(/\\/g,"/").toLowerCase(),Z=Q.split("/").at(-1)??Q;if(Z==="env")return _X(J);if(Z==="bash"||Z==="sh"||Z==="zsh")return[Z,...J];if(Z==="python3"||Z==="python")return process.platform==="win32"?["py","-3",...J]:[Z,...J];return $}function gO($){let f=IO($);if(f&&f.length>0)return[..._X(f)??f,$];let J=$.toLowerCase();if(J.endsWith(".sh")||J.endsWith(".bash")||J.endsWith(".zsh"))return["bash",$];if(J.endsWith(".js")||J.endsWith(".mjs")||J.endsWith(".cjs"))return OX(["node",$],{debugRole:"hook"});if(J.endsWith(".ts")||J.endsWith(".mts")||J.endsWith(".cts"))return["bun","run",$];if(J.endsWith(".py"))return process.platform==="win32"?["py","-3",$]:["python3",$];if(J.endsWith(".ps1"))return[process.platform==="win32"?"powershell":"pwsh","-File",$];return["bash",$]}function vO($){let f={};for(let J of J2($)){if(!J.hookEventName)continue;let Q=J.hookEventName,Z=f[Q]??[];Z.push(gO(J.path)),f[Q]=Z}return f}async function uO($){let f;for(let J of $.commands){let Q=J.join(" ");try{let Z=await zX($.payload,{command:J,cwd:$.cwd,env:E9(process.env),detached:!1,timeoutMs:$.timeoutMs});if(Z?.timedOut){_6($.logger,`hook command timed out: ${Q}`);continue}if(Z?.parseError){_6($.logger,`hook command returned invalid JSON control output: ${Q} (${Z.parseError})`);continue}f=CO(f,EO(Z?.parsedJson))}catch(Z){_6($.logger,`hook command failed: ${Q}`,Z)}}return f}function R1($){for(let f of $.commands){let J=f.join(" ");zX($.payload,{command:f,cwd:$.cwd,env:E9(process.env),detached:!0}).catch((Q)=>{_6($.logger,`hook command failed: ${J}`,Q)})}}function u$($){return{agentId:$.agentId,conversationId:$.conversationId??$.runId??$.agentId,parentAgentId:$.parentAgentId??null}}function C9($,f){return{...u$($.snapshot),userMessage:f}}function NX($){return{...u$($.snapshot),iteration:$.snapshot.iteration,call:{id:$.toolCall.toolCallId,name:$.toolCall.toolName,input:$.input}}}function TX($){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 MX($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function cO($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}function T6($){let f={cwd:$.workspacePath,workspacePath:$.workspacePath,rootSessionId:$.rootSessionId,workspaceInfo:$.workspaceInfo},J=(Q)=>{let Z=`${JSON.stringify({ts:new Date().toISOString(),...Q})}
557
+ `,j=(process.env.CLINE_HOOKS_LOG_PATH?.trim()||void 0)??hO(RX(),"hooks.jsonl");RX(j),wO(j,Z,"utf8")};return{beforeRun:async(Q)=>{let Z=C9(Q,"");J({...Y0(Z,f),hookName:"agent_start",taskStart:{taskMetadata:{}}});return},beforeTool:async(Q)=>{let Z=NX(Q);J({...Y0(Z,f),hookName:"tool_call",iteration:Z.iteration,tool_call:{id:Z.call.id,name:Z.call.name,input:Z.call.input},preToolUse:{toolName:Z.call.name,parameters:N6(Z.call.input)}});return},afterTool:async(Q)=>{let Z=TX(Q);J({...Y0(Z,f),hookName:"tool_result",iteration:Z.iteration,tool_result:Z.record,postToolUse:{toolName:Z.record.name,parameters:N6(Z.record.input),result:typeof Z.record.output==="string"?Z.record.output:JSON.stringify(Z.record.output),success:!Z.record.error,executionTimeMs:Z.record.durationMs}});return},afterRun:async({snapshot:Q,result:Z})=>{let W=u$(Q);if(Z.status==="completed"){J({...Y0(W,f),hookName:"agent_end",iteration:Z.iterations,turn:{outputText:Z.outputText,status:Z.status},taskComplete:{taskMetadata:{}}});return}if(Z.status==="aborted"||h9(Z.error?.message)){J({...Y0(W,f),hookName:"agent_abort",reason:Z.error?.message,taskCancel:{taskMetadata:{}}});return}if(Z.error)J({...Y0(W,f),hookName:"agent_error",iteration:Z.iterations,error:{name:Z.error.name,message:Z.error.message,stack:Z.error.stack}})},onEvent:async(Q)=>{if(Q.type!=="message-added"||Q.message.role!=="user")return;let Z=C9({snapshot:Q.snapshot},MX(Q.message.content));J({...Y0(Z,f),hookName:"prompt_submit",userPromptSubmit:{prompt:Z.userMessage,attachments:[]}})}}}function b9($){let f=vO($.workspacePath);if(!Object.values(f).some((A)=>A.length>0))return;let Q=async(A,B)=>{let G=f[B]??[];if(G.length===0)return;R1({commands:G,cwd:$.cwd,logger:$.logger,payload:B==="agent_resume"?{...Y0(A,$),hookName:B,taskResume:{taskMetadata:{},previousState:{}}}:{...Y0(A,$),hookName:B,taskStart:{taskMetadata:{}}}})},Z=async(A)=>{let B=f.prompt_submit??[];if(B.length>0)R1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"prompt_submit",userPromptSubmit:{prompt:A.userMessage,attachments:[]}}})},W=async(A)=>{let B=f.tool_call??[];if(B.length===0)return;return uO({commands:B,cwd:$.cwd,logger:$.logger,timeoutMs:$.toolCallTimeoutMs??120000,payload:{...Y0(A,$),hookName:"tool_call",iteration:A.iteration,tool_call:{id:A.call.id,name:A.call.name,input:A.call.input},preToolUse:{toolName:A.call.name,parameters:N6(A.call.input)}}})},j=async(A)=>{let B=f.tool_result??[];if(B.length===0)return;R1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"tool_result",iteration:A.iteration,tool_result:A.record,postToolUse:{toolName:A.record.name,parameters:N6(A.record.input),result:typeof A.record.output==="string"?A.record.output:JSON.stringify(A.record.output),success:!A.record.error,executionTimeMs:A.record.durationMs}}})},X=async(A)=>{let B=f.agent_end??[];if(B.length===0)return;R1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_end",iteration:A.iteration,turn:A.turn,taskComplete:{taskMetadata:{}}}})},H=async(A)=>{let B=f.agent_error??[];if(B.length===0)return;R1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_error",iteration:A.iteration,error:{name:A.error.name,message:A.error.message,stack:A.error.stack}}})},Y=async(A)=>{if(h9(A.reason)){let G=f.agent_abort??[];if(G.length>0)R1({commands:G,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"agent_abort",reason:A.reason,taskCancel:{taskMetadata:{}}}})}let B=f.session_shutdown??[];if(B.length===0)return;R1({commands:B,cwd:$.cwd,logger:$.logger,payload:{...Y0(A,$),hookName:"session_shutdown",reason:A.reason}})},V={};if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0||(f.prompt_submit?.length??0)>0){if((f.agent_start?.length??0)>0||(f.agent_resume?.length??0)>0)V.beforeRun=async(A)=>{let B=process.env.CLINE_HOOK_AGENT_RESUME==="1"?"agent_resume":"agent_start";await Q(u$(A.snapshot),B);return};if((f.prompt_submit?.length??0)>0)V.onEvent=async(A)=>{if(A.type!=="message-added"||A.message.role!=="user")return;await Z(C9({snapshot:A.snapshot},MX(A.message.content)))}}if((f.tool_call?.length??0)>0)V.beforeTool=async(A)=>{let B=await W(NX(A));return cO(B)};if((f.tool_result?.length??0)>0)V.afterTool=async(A)=>{await j(TX(A));return};if((f.agent_end?.length??0)>0)V.afterRun=async({snapshot:A,result:B})=>{if(B.status!=="completed")return;await X({...u$(A),iteration:B.iterations,turn:{outputText:B.outputText,status:B.status}})};if((f.agent_error?.length??0)>0||(f.agent_abort?.length??0)>0||(f.session_shutdown?.length??0)>0){let A=V.afterRun;V.afterRun=async(B)=>{await A?.(B);let{snapshot:G,result:K}=B;if(K.status==="aborted"||h9(K.error?.message)){await Y({...u$(G),reason:K.error?.message});return}if(K.error)await H({...u$(G),iteration:K.iterations,error:K.error})}}return V}function M6($){return O6("core.hook_config_files",b9($))}function L1($,f){let J=$.map((Q)=>Q[f]).filter((Q)=>typeof Q==="function");if(J.length===0)return;return async(Q)=>{let Z;for(let W of J){let j=await W(Q);if(!j||typeof j!=="object")continue;let X=j;Z={...Z??{},...X,stop:Z?.stop===!0||X.stop===!0?!0:X.stop,options:Z?.options||X.options?{...Z?.options??{},...X.options??{}}:void 0}}return Z}}function D8($){let f=$.filter((J)=>J!==void 0);if(f.length===0)return;return{beforeRun:L1(f,"beforeRun"),afterRun:L1(f,"afterRun"),beforeModel:L1(f,"beforeModel"),afterModel:L1(f,"afterModel"),beforeTool:L1(f,"beforeTool"),afterTool:L1(f,"afterTool"),onEvent:L1(f,"onEvent")}}import{z as c$}from"zod";var q6=b1;var qX=c$.object({settings:b1,updatedAt:c$.string().datetime(),tokenSource:c$.enum(["manual","oauth","migration"]).default("manual")}),y6=c$.object({version:c$.literal(1),lastUsedProvider:c$.string().min(1).optional(),providers:c$.record(c$.string(),qX)});function Q2(){return{version:1,providers:{}}}Z$();import{upsertWorkspaceInfo as dO,WorkspaceManifestSchema as k9}from"@cline/shared";class w6{manifest;listeners=new Set;constructor($){this.manifest=k9.parse($??{workspaces:{}})}async addWorkspacePath($){let f=await s4($);return this.manifest=dO(this.manifest,f),this.emit({type:"workspace_added",workspace:f}),f}async switchWorkspace($){let f=Y1($),J=this.manifest.workspaces[f];if(J)return this.manifest=k9.parse({...this.manifest,currentWorkspacePath:f}),this.emit({type:"workspace_switched",workspace:J}),J;let Q=await this.addWorkspacePath(f);return this.manifest=k9.parse({...this.manifest,currentWorkspacePath:Q.rootPath}),this.emit({type:"workspace_switched",workspace:Q}),Q}subscribe($){return this.listeners.add($),()=>{this.listeners.delete($)}}getCurrentWorkspace(){let $=this.manifest.currentWorkspacePath;if(!$)return;return this.manifest.workspaces[$]}getWorkspace($){let f=Y1($);return this.manifest.workspaces[f]}listWorkspaces(){return Object.values(this.manifest.workspaces)}getManifest(){return this.manifest}emit($){for(let f of this.listeners)f($)}}G0();import{createHash as lO}from"node:crypto";var yX=new Set,wX=new Set;function pO($){return lO("sha256").update($).digest("hex")}function rO($){if($.vcsTypes&&$.vcsTypes.length>0)return $.vcsTypes;return[$.vcsType==="git"?"git":"none"]}function SX($){if(!$.telemetry)return;let f=pO($.rootPath),J=$.rootCount??1;if(!yX.has(f))yX.add(f),Af($.telemetry,{root_count:J,vcs_types:rO($),init_duration_ms:$.durationMs,feature_flag_enabled:$.featureFlagEnabled??!0,is_remote_workspace:$.isRemoteWorkspace});if($.initError&&!wX.has(f)){wX.add(f);let Q=Error($.initError.message);Q.name=$.initError.errorType||"Error",Bf($.telemetry,Q,{fallback_to_single_root:!0,workspace_count:J})}}function nO($){return`${$.pluginName??$.pluginPath}: ${$.message}`}function aO($,f,J){if(f.length>0)for(let W of f)J?.log(W.message,{severity:"warn"});if($.length===0)return;let Q=$.slice(0,3).map(nO).join("; "),Z=$.length>3?`; and ${$.length-3} more`:"";J?.log(`Some plugins failed to initialize. ${Q}${Z}. Use --verbose for more details.`,{severity:"warn"});for(let W of $)J?.log(`Plugin initialization failed (${W.phase}) for ${W.pluginPath}`,{severity:"warn",stack:W.stack,pluginPath:W.pluginPath,pluginName:W.pluginName})}function tO($,f){let J=typeof $.thinking==="boolean",Q=typeof $.reasoningEffort==="string";if(!J&&!Q)return f;return{...f??{},...J?{enabled:$.thinking}:{},...Q?{effort:$.reasoningEffort}:{}}}function sO($,f){return iO($,f)}function oO($){let f=0;for(let J of $??[]){if(J.role!=="user")continue;if(("metadata"in J&&J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0)?.kind==="recovery_notice")continue;f+=1}return f}function eO($){let f={...$.storedHeaders??{},...$.configHeaders??{}},J=$.accountId?.trim()||$z($.accessToken);if(f.originator="cline",f.session_id=$.sessionId,f["User-Agent"]=`Cline/${process.env.npm_package_version||"1.0.0"}`,J)f["ChatGPT-Account-Id"]=J;return f}function $z($){let f=$?.trim();if(!f)return;let J=K0(f),Q=J?.["https://api.openai.com/auth"]?.chatgpt_account_id;if(typeof Q==="string"&&Q.length>0)return Q;let Z=J?.organizations?.[0]?.id;if(typeof Z==="string"&&Z.length>0)return Z;let W=J?.chatgpt_account_id;if(typeof W==="string"&&W.length>0)return W;return}function fz($,f,J,Q,Z){let W=J.getProviderSettings($.providerId),j=Q||W?.modelCatalog?{...Q??{},...W?.modelCatalog??{}}:void 0,X={...W??{},provider:$.providerId,model:$.modelId,apiKey:$.apiKey??W?.apiKey,baseUrl:$.baseUrl??W?.baseUrl,headers:$.providerId==="openai-codex"?eO({sessionId:f,configHeaders:$.headers,storedHeaders:W?.headers,accountId:W?.auth?.accountId,accessToken:$.apiKey??W?.auth?.accessToken??W?.apiKey}):$.headers??W?.headers,reasoning:tO($,W?.reasoning),modelCatalog:j},H=$$(X);if($.knownModels)H.knownModels=$.knownModels;if($.extensionContext)H.extensionContext=$.extensionContext;let V=$.fetch??H.fetch??Z;if(V)H.fetch=V;return H}async function hX($){let{input:f,sessionId:J,providerSettingsManager:Q,defaultTelemetry:Z,defaultCapabilities:W,defaultToolPolicies:j,defaultFetch:X,onPluginEvent:H,onTeamEvent:Y,createSpawnTool:V,localRuntime:A,readSessionMetadata:B,writeSessionMetadata:G}=$,K=v$(f.config),{modelCatalogDefaults:D,userInstructionService:F,configExtensions:P,onTeamRestored:U,...z}=A??{},_=Object.keys(z).length>0?z:void 0,{workspaceInfo:R,workspaceMetadata:L,durationMs:N,vcsType:M,initError:o}=await LW(K),e=_?.extensionContext,a={...e??{},workspace:{...R,...e?.workspace??{}},session:{...e?.session??{},sessionId:J},logger:e?.logger??_?.logger,telemetry:e?.telemetry??_?.telemetry??Z};SX({telemetry:a.telemetry,rootPath:R.rootPath,workspaceInfo:R,rootCount:1,vcsType:M,durationMs:N,initError:o,featureFlagEnabled:!0});let v=M6({cwd:f.config.cwd,workspacePath:K,rootSessionId:J,logger:_?.logger,workspaceInfo:R}),V0=xW(_?.hooks)?void 0:T6({rootSessionId:J,workspacePath:K,workspaceInfo:R}),B$=D8([_?.hooks,V0]),u;if(sO(P,"plugins"))try{u=await r4({pluginPaths:_?.pluginPaths,workspacePath:K,cwd:f.config.cwd,onEvent:H,providerId:f.config.providerId,modelId:f.config.modelId,workspaceInfo:R,session:a.session,client:a.client,user:a.user,logger:a.logger,telemetry:a.telemetry,automation:a.automation}),aO(u.failures,u.warnings,_?.logger)}catch(V2){let p=V2 instanceof Error?V2.message:String(V2);_?.logger?.log?.(`plugin loading failed; continuing without plugins (${p})`)}let h=E5(v?[v]:void 0,E5(_?.extensions,iJ(u?.extensions))),l={...f.config,..._??{},sessionId:J,hooks:B$,extensions:h,extensionContext:a,telemetry:a.telemetry},M0=fz(l,J,Q,D,X),L0=D8([l.hooks,l.checkpoint?.enabled===!0?hj({cwd:l.cwd,sessionId:J,logger:l.logger,createCheckpoint:l.checkpoint?.createCheckpoint,initialRunCount:oO(f.initialMessages),readSessionMetadata:B,writeSessionMetadata:G}):void 0]),r$={...l,providerConfig:M0,workspaceMetadata:L,hooks:L0},y1=f.toolPolicies??l.toolPolicies??j,Y2=P0(W,f.capabilities),w8=Y2?.requestToolApproval,Wf=Y2?.toolExecutors,w1=new w6({currentWorkspacePath:R.rootPath,workspaces:{[R.rootPath]:R}});return{effectiveInput:f,config:r$,providerConfig:M0,workspaceMetadata:L,workspaceInfo:R,extensions:h,hooks:L0,toolPolicies:y1,requestToolApproval:w8,pluginSandboxShutdown:u?.shutdown,runtimeBuilderInput:{config:r$,hooks:L0,extensions:h,onTeamEvent:Y,createSpawnTool:V,onTeamRestored:U,userInstructionService:F,configExtensions:P,toolExecutors:Wf,workspaceManager:w1,logger:r$.logger,telemetry:r$.telemetry}}}import{resolveDocumentsExtensionPath as Jz}from"@cline/shared/storage";G0();function CX($,f,J,Q,Z){if(J)Kf($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});else Gf($.telemetry,{ulid:f,apiProvider:$.providerId,...Z});Qz($.telemetry,{workspacePath:Q})}function Qz($,f){let J=Jz("Hooks"),Q=J2(f.workspacePath),Z=new Map;for(let W of Q){let j=W.hookEventName??"unknown",X=Z.get(j)??{global:0,workspace:0};if(W.path===J||W.path.startsWith(`${J}/`))X.global+=1;else X.workspace+=1;Z.set(j,X)}for(let[W,j]of Z.entries())Nf($,W,j.global,j.workspace)}function EX($,f){for(let J of f.mentions)zf($,J,f.matchedFiles.includes(J)?1:0,"file",!f.matchedFiles.includes(J));for(let J of f.matchedFiles)Lf($,"file",J.length);for(let J of f.ignoredMentions)Of($,"file","not_found",J)}import{chmodSync as tX,existsSync as u9,mkdirSync as xz,readFileSync as mz,writeFileSync as gz}from"node:fs";import{basename as sX,dirname as c9}from"node:path";import{resolveProviderSettingsPath as vz}from"@cline/shared/storage";import{existsSync as Zz,mkdirSync as Wz,readFileSync as jz,writeFileSync as Xz}from"node:fs";import{mkdir as Hz,readFile as Yz,writeFile as Vz}from"node:fs/promises";import{dirname as I9,join as Az}from"node:path";import*as N0 from"@cline/llms";import{ModelCapabilitySchema as Bz,ProviderCapabilitySchema as Gz,ProviderClientSchema as Kz,ProviderProtocolSchema as Fz}from"@cline/shared";import{z as d}from"zod";var Pz=d.object({id:d.string().optional(),name:d.string().optional(),maxTokens:d.number().optional(),contextWindow:d.number().optional(),maxInputTokens:d.number().optional(),capabilities:d.array(Bz).optional(),supportsVision:d.boolean().optional(),supportsAttachments:d.boolean().optional(),supportsReasoning:d.boolean().optional()}).passthrough(),Uz=d.object({name:d.string(),baseUrl:d.string(),defaultModelId:d.string().optional(),protocol:Fz.optional(),client:Kz.optional(),capabilities:d.array(Gz).optional(),modelsSourceUrl:d.string().optional()}).passthrough(),bX=d.object({provider:Uz.optional(),models:d.record(d.string(),Pz).optional()}).passthrough(),kX=d.object({version:d.literal(1),providers:d.record(d.string(),bX)}),Dz=d.object({version:d.literal(1),providers:d.record(d.string(),d.unknown())}),S6=new Set;function IX($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function O1($){return Az(I9($.getFilePath()),"models.json")}function h6(){return{version:1,providers:{}}}function xX($){let f=Dz.safeParse($);if(!f.success)return h6();let J={};for(let[Q,Z]of Object.entries(f.data.providers)){let W=bX.safeParse(Z);if(W.success)J[Q]=W.data}return{version:1,providers:J}}function x9($){if(!Zz($))return h6();try{let f=jz($,"utf8");return xX(JSON.parse(f))}catch{}return h6()}async function Z2($){try{let f=await Yz($,"utf8");return xX(JSON.parse(f))}catch{}return h6()}function mX($,f){Wz(I9($),{recursive:!0});let J=kX.parse(f);Xz($,`${JSON.stringify(J,null,2)}
558
+ `,"utf8")}async function C6($,f){await Hz(I9($),{recursive:!0});let J=kX.parse(f);await Vz($,`${JSON.stringify(J,null,2)}
559
+ `,"utf8")}function gX($,f){return{id:$,name:f.name??$,supportsAttachments:f.capabilities?.includes("files"),supportsVision:f.capabilities?.includes("images"),supportsReasoning:f.capabilities?.includes("reasoning")||f.thinkingConfig!=null}}function vX($){if(!$||$.length===0)return;let f=new Set;if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("tools"))f.add("tools");return f.size>0?[...f]:void 0}function uX($){let f=new Set;if(!$||$.length===0)return[...f];if($.includes("streaming"))f.add("streaming");if($.includes("tools"))f.add("tools");if($.includes("reasoning"))f.add("reasoning");if($.includes("prompt-cache"))f.add("prompt-cache");if($.includes("vision"))f.add("images"),f.add("files");return[...f]}function Rz($){return $!=null&&typeof $.name==="string"&&typeof $.baseUrl==="string"}function cX($,f){return $??f??"openai-chat"}function dX($,f,J){return $??J??(f==="openai-responses"?"openai":"openai-compatible")}function lX($,f,J){let Q=new Set(f?.capabilities??J??[]);if(f?.supportsVision)Q.add("images");if(f?.supportsAttachments)Q.add("files");if(f?.supportsReasoning)Q.add("reasoning");return{id:$,name:f?.name??$,maxTokens:f?.maxTokens,contextWindow:f?.contextWindow,maxInputTokens:f?.maxInputTokens,capabilities:Q.size>0?[...Q]:void 0}}function Lz($,f){for(let[J,Q]of Object.entries(f??{})){let Z=Q.id?.trim()||J.trim();if(!Z)continue;N0.registerModel($,Z,lX(Z,Q))}}function Oz($,f,J){return{...f??{},id:$,name:f?.name??$,capabilities:f?.capabilities??J}}function zz($){return Object.assign({},...N0.resolveProviderModelCatalogKeys($).map((J)=>N0.getGeneratedModelsForProvider(J)))}function _z($){let f=$.provider.trim();if(!f||N0.isBuiltInProviderId(f))return;let J=$.baseUrl?.trim();if(!J)return;let Q=N0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f],Z=zz(f),W=uX($.capabilities),j=W.length>0?W:void 0,X=$.model?.trim(),H={...Z,...Q?.models??{}};if(X)H[X]=Oz(X,H[X],j);let Y=Object.keys(H).filter(Boolean),V=X||Y[0];if(!V)return;let A=cX($.protocol,Q?.provider.protocol),B=dX($.client,A,Q?.provider.client);N0.registerProvider({provider:{id:f,name:Q?.provider.name??IX(f),description:Q?.provider.description,protocol:A,client:B,baseUrl:J,modelsSourceUrl:Q?.provider.modelsSourceUrl,defaultModelId:V,capabilities:vX($.capabilities)??Q?.provider.capabilities,source:"file"},models:H})}function E6($){for(let f of Object.values($.providers))_z(f.settings)}function R8($,f){let J=f.models??{};if(!Rz(f.provider)){Lz($,J);return}let Q=uX(f.provider.capabilities),Z=Object.entries(J).map(([Y,V])=>({id:V.id?.trim()||Y.trim(),model:V})).filter(({id:Y})=>Y.length>0),W=f.provider.defaultModelId?.trim()||Z[0]?.id||"default",j=cX(f.provider.protocol,void 0),X=dX(f.provider.client,j,void 0),H=Object.fromEntries(Z.map(({id:Y,model:V})=>[Y,{...lX(Y,V,Q.length>0?Q:void 0),status:"active"}]));N0.registerProvider({provider:{id:$,name:f.provider.name.trim()||IX($),protocol:j,client:X,baseUrl:f.provider.baseUrl,modelsSourceUrl:f.provider.modelsSourceUrl,defaultModelId:W,capabilities:vX(f.provider.capabilities),source:"file"},models:H})}function pX($){let f=O1($);if(S6.has(f))return;let J=x9(f);for(let[Q,Z]of Object.entries(J.providers))R8(Q,Z);S6.add(f)}async function rX($){let f=O1($);if(S6.has(f))return;let J=await Z2(f);for(let[Q,Z]of Object.entries(J.providers))R8(Q,Z);S6.add(f)}import{existsSync as Nz,readFileSync as Tz}from"node:fs";import{dirname as Mz,join as m9}from"node:path";import*as k6 from"@cline/llms";import{resolveClineDataDir as qz}from"@cline/shared/storage";var b6="openai",aX=k6.BUILT_IN_PROVIDER.OPENAI_COMPATIBLE,iX=128000;function yz($){let f=$?.trim();if(!f)return;try{let J=JSON.parse(f);if(!J)return;return{accessToken:J.idToken,refreshToken:J.refreshToken,expiresAt:J.expiresAt,accountId:J.userInfo?.id}}catch{return}}function C($){let f=$?.trim();return f?f:void 0}function nX($){if(!Nz($))return;try{let f=Tz($,"utf8"),J=JSON.parse(f);if(J&&typeof J==="object"&&!Array.isArray(J))return J}catch{}return}function wz($){let f=$.dataDir??qz(),J=$.globalStatePath??m9(f,"globalState.json"),Q=$.secretsPath??m9(f,"secrets.json"),Z=nX(J),W=nX(Q);if(!Z&&!W)return;return{globalState:Z??{},secrets:W??{}}}function g9($){if($===b6)return aX;return $}function Sz($,f,J,Q){let Z=J==="plan"?"planMode":"actMode",W=f===Q?C(J==="plan"?$.planModeApiModelId:$.actModeApiModelId):void 0,X={openrouter:`${Z}OpenRouterModelId`,cline:`${Z}ClineModelId`,openai:`${Z}OpenAiModelId`,ollama:`${Z}OllamaModelId`,lmstudio:`${Z}LmStudioModelId`,litellm:`${Z}LiteLlmModelId`,requesty:`${Z}RequestyModelId`,together:`${Z}TogetherModelId`,fireworks:`${Z}FireworksModelId`,sapaicore:`${Z}SapAiCoreModelId`,groq:`${Z}GroqModelId`,baseten:`${Z}BasetenModelId`,huggingface:`${Z}HuggingFaceModelId`,"huawei-cloud-maas":`${Z}HuaweiCloudMaasModelId`,oca:`${Z}OcaModelId`,aihubmix:`${Z}AihubmixModelId`,hicap:`${Z}HicapModelId`,nousResearch:`${Z}NousResearchModelId`,"vercel-ai-gateway":`${Z}VercelAiGatewayModelId`}[f];return(X?C(typeof $[X]==="string"?$[X]:void 0):void 0)??W}function hz($,f,J){let Q=J==="plan"?$.planModeReasoningEffort:$.actModeReasoningEffort,Z=J==="plan"?$.geminiPlanModeThinkingLevel:$.geminiActModeThinkingLevel,W=J==="plan"?$.planModeThinkingBudgetTokens:$.actModeThinkingBudgetTokens,j=(f==="gemini"?Z:void 0)??Q,X=j==="none"||j==="low"||j==="medium"||j==="high"?j:void 0,H=typeof W==="number"&&Number.isInteger(W)&&W>0?W:void 0;if(!X&&H===void 0)return;return{...X?{effort:X}:{},...H!==void 0?{budgetTokens:H}:{}}}function Cz($){let f=$["openai-codex-oauth-credentials"];if(!f)return;try{let J=JSON.parse(f),Q=C(J.access_token),Z=C(J.refresh_token),W=C(J.accountId);if(!Q&&!Z&&!W)return;return{...Q?{apiKey:Q}:{},auth:{...Q?{accessToken:Q}:{},...Z?{refreshToken:Z}:{},...W?{accountId:W}:{}}}}catch{return}}function Ez($){let f=k6.getGeneratedModelsForProvider($);return Object.keys(f)[0]??void 0}function bz($,f,J,Q){let Z=g9($),W=C(Q==="plan"?f.planModeApiProvider:f.actModeApiProvider),j=Sz(f,$,Q,W)??Ez(Z),X=hz(f,Z,Q),H=typeof f.requestTimeoutMs==="number"&&Number.isInteger(f.requestTimeoutMs)&&f.requestTimeoutMs>0?f.requestTimeoutMs:void 0,Y={anthropic:J.apiKey,cline:J.clineApiKey,openai:J.openAiApiKey,"openai-native":J.openAiNativeApiKey,openrouter:J.openRouterApiKey,bedrock:J.awsBedrockApiKey,gemini:J.geminiApiKey,ollama:J.ollamaApiKey,deepseek:J.deepSeekApiKey,requesty:J.requestyApiKey,together:J.togetherApiKey,fireworks:J.fireworksApiKey,qwen:J.qwenApiKey,doubao:J.doubaoApiKey,mistral:J.mistralApiKey,litellm:J.liteLlmApiKey,asksage:J.asksageApiKey,xai:J.xaiApiKey,moonshot:J.moonshotApiKey,zai:J.zaiApiKey,huggingface:J.huggingFaceApiKey,nebius:J.nebiusApiKey,sambanova:J.sambanovaApiKey,cerebras:J.cerebrasApiKey,groq:J.groqApiKey,"huawei-cloud-maas":J.huaweiCloudMaasApiKey,baseten:J.basetenApiKey,"vercel-ai-gateway":J.vercelAiGatewayApiKey,dify:J.difyApiKey,minimax:J.minimaxApiKey,hicap:J.hicapApiKey,aihubmix:J.aihubmixApiKey,nousResearch:J.nousResearchApiKey,oca:J.ocaApiKey,sapaicore:J.sapAiCoreClientId},V={};if($==="openai-codex")Object.assign(V,Cz(J));if($==="cline")try{let P=C(J["cline:clineAccountId"]);if(P)V.auth={...V.auth??{},...yz(P)}}catch{}if($===b6&&f.openAiHeaders)V.headers=f.openAiHeaders;if($==="bedrock"){let P=f.awsAuthentication==="profile"||f.awsUseProfile===!0;V.aws={accessKey:C(J.awsAccessKey),secretKey:C(J.awsSecretKey),sessionToken:C(J.awsSessionToken),region:C(f.awsRegion),authentication:f.awsAuthentication,profile:P?C(f.awsProfile):void 0,usePromptCache:f.awsBedrockUsePromptCache,useCrossRegionInference:f.awsUseCrossRegionInference,useGlobalInference:f.awsUseGlobalInference,endpoint:C(f.awsBedrockEndpoint),customModelBaseId:C(Q==="plan"?f.planModeAwsBedrockCustomModelBaseId:f.actModeAwsBedrockCustomModelBaseId)}}if($==="vertex")V.gcp={projectId:C(f.vertexProjectId),region:C(f.vertexRegion)};if($===b6&&(f.azureApiVersion||f.azureIdentity!==void 0))V.azure={apiVersion:C(f.azureApiVersion),useIdentity:f.azureIdentity};if($==="sapaicore")V.sap={clientId:C(J.sapAiCoreClientId),clientSecret:C(J.sapAiCoreClientSecret),tokenUrl:C(f.sapAiCoreTokenUrl),resourceGroup:C(f.sapAiResourceGroup),deploymentId:C(Q==="plan"?f.planModeSapAiCoreDeploymentId:f.actModeSapAiCoreDeploymentId),useOrchestrationMode:f.sapAiCoreUseOrchestrationMode};if($==="oca"){V.oca={mode:f.ocaMode};let P=C(J.ocaRefreshToken);if(P)V.auth={...V.auth??{},refreshToken:P}}if($==="qwen")V.apiLine=f.qwenApiLine;if($==="moonshot")V.apiLine=f.moonshotApiLine;if($==="zai")V.apiLine=f.zaiApiLine;if($==="minimax")V.apiLine=f.minimaxApiLine;let A={anthropic:f.anthropicBaseUrl,openai:f.openAiBaseUrl,ollama:f.ollamaBaseUrl,lmstudio:f.lmStudioBaseUrl,litellm:f.liteLlmBaseUrl,gemini:f.geminiBaseUrl,requesty:f.requestyBaseUrl,asksage:f.asksageApiUrl,dify:f.difyBaseUrl,oca:f.ocaBaseUrl,aihubmix:f.aihubmixBaseUrl,sapaicore:f.sapAiCoreBaseUrl},B=C(Y[$]),G=C(A[$]),K={provider:Z,...B?{apiKey:B}:{},...j?{model:j}:{},...G?{baseUrl:G}:{},...X?{reasoning:X}:{},...H?{timeout:H}:{},...V},D=q6.safeParse(K);if(!D.success)return;return Object.keys(K).filter((P)=>P!=="provider").length>0?D.data:void 0}function kz($,f){if($!==aX)return;if(!f.baseUrl||!f.model)return;return{provider:{name:"OpenAI Compatible",baseUrl:f.baseUrl,defaultModelId:f.model},models:{[f.model]:{id:f.model,name:f.model,contextWindow:iX,maxInputTokens:iX,capabilities:["streaming","tools","images"]}}}}function Iz($,f){let J=new Set;for(let Q of[$.actModeApiProvider,$.planModeApiProvider]){let Z=C(Q);if(Z)J.add(Z)}if(C(f.apiKey))J.add("anthropic");if(C(f.openRouterApiKey))J.add("openrouter");if(C(f.openAiApiKey))J.add(b6);if(C(f.openAiNativeApiKey))J.add("openai-native");if(C(f["openai-codex-oauth-credentials"]))J.add("openai-codex");if(C(f.geminiApiKey))J.add("gemini");if(C(f.ollamaApiKey))J.add("ollama");if(C(f.awsAccessKey)||C(f.awsBedrockApiKey)||$.awsAuthentication!==void 0||$.awsUseProfile===!0||C($.awsProfile))J.add("bedrock");if(C($.vertexProjectId)||C($.vertexRegion))J.add("vertex");if(C(f.clineApiKey))J.add("cline");if(C(f.ocaApiKey))J.add("oca");return J}function v9($){let f=$.providerSettingsManager.read(),J=wz($);if(!J)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let{globalState:Q,secrets:Z}=J,W=Q.mode==="plan"?"plan":"act",j=Iz(Q,Z),X=Q2();X.providers={...f.providers},X.lastUsedProvider=f.lastUsedProvider;let H=new Date().toISOString(),Y=0,V=m9(Mz($.providerSettingsManager.getFilePath()),"models.json"),A=x9(V),B=0;for(let D of j){let F=g9(D);if(X.providers[F])continue;let P=bz(D,Q,Z,W);if(!P)continue;X.providers[F]={settings:P,updatedAt:H,tokenSource:"migration"},Y+=1;let U=kz(F,P);if(U&&!A.providers[F])A.providers[F]=U,B+=1}if(Y===0&&B===0)return{migrated:!1,providerCount:Object.keys(f.providers).length,lastUsedProvider:f.lastUsedProvider};let G=C(W==="plan"?Q.planModeApiProvider:Q.actModeApiProvider),K=G?g9(G):void 0;if(X.lastUsedProvider=f.lastUsedProvider??(K&&X.providers[K]?K:Object.keys(X.providers)[0]),$.providerSettingsManager.write(X),B>0)mX(V,A);return{migrated:Y>0||B>0,providerCount:Object.keys(X.providers).length,lastUsedProvider:X.lastUsedProvider}}function uz(){return new Date().toISOString()}function cz($){if(sX($)!=="providers.json")return;let f=c9($);if(sX(f)!=="settings")return;return c9(f)}class d${filePath;dataDir;constructor($={}){if(this.filePath=$.filePath??vz(),this.dataDir=$.dataDir??cz(this.filePath),this.dataDir||!$.filePath)v9({providerSettingsManager:this,dataDir:this.dataDir});if(pX(this),E6(this.read()),u9(this.filePath))try{tX(this.filePath,384)}catch{}}getFilePath(){return this.filePath}read(){if(!u9(this.filePath))return Q2();try{let $=mz(this.filePath,"utf8"),f=JSON.parse($),J=y6.safeParse(f);if(J.success)return E6(J.data),J.data}catch{}return Q2()}write($){let f=y6.parse($),J=c9(this.filePath);if(!u9(J))xz(J,{recursive:!0,mode:448});gz(this.filePath,`${JSON.stringify(f,null,2)}
560
+ `,"utf8");try{tX(this.filePath,384)}catch{}E6(f)}saveProviderSettings($,f={}){let J=q6.parse($),Q=this.read(),Z=J.provider,W=f.setLastUsed!==!1,j=Q.providers[Z],X=f.tokenSource??j?.tokenSource??"manual",H={...Q,providers:{...Q.providers,[Z]:{settings:J,updatedAt:uz(),tokenSource:X}},lastUsedProvider:W?Z:Q.lastUsedProvider};return this.write(H),H}getProviderSettings($){return this.read().providers[$]?.settings}getLastUsedProviderSettings(){let $=this.read(),f=$.lastUsedProvider;if(!f)return;return $.providers[f]?.settings}getProviderConfig($,f){let J=this.getProviderSettings($);if(!J)return;return $$(J,f)}getLastUsedProviderConfig($){let f=this.getLastUsedProviderSettings();if(!f)return;return $$(f,$)}async refreshCatalog(){try{await a8({})}catch{}}}G0();V6();import{execFile as dz}from"node:child_process";import{promisify as lz}from"node:util";var W2=lz(dz);function d9($){let f=$?.metadata?.checkpoint&&typeof $.metadata.checkpoint==="object"&&!Array.isArray($.metadata.checkpoint)?$.metadata.checkpoint:void 0;return(Array.isArray(f?.history)?f.history:[]).filter((Q)=>!!Q&&typeof Q==="object"&&!Array.isArray(Q)).flatMap((Q)=>{let Z=String(Q.ref??"").trim(),W=Number(Q.createdAt??0),j=Number(Q.runCount??0);if(Z.length===0||!Number.isFinite(W)||!Number.isInteger(j)||j<1)return[];let X=Q.kind==="stash"||Q.kind==="commit"?Q.kind:void 0;return[{ref:Z,createdAt:W,runCount:j,...X?{kind:X}:{}}]})}function oX($,f){let J=d9($).filter((Z)=>Z.runCount<=f),Q=J.at(-1);return Q?{latest:Q,history:J}:void 0}function pz($,f){return $.reduce((J,Q)=>{if(Q.runCount>f)return J;if(!J||Q.runCount>J.runCount)return Q;return J},void 0)}function eX($,f){let J=0;for(let Q=0;Q<$.length;Q+=1){let Z=$[Q];if(Z?.role!=="user")continue;if(("metadata"in Z&&Z.metadata&&typeof Z.metadata==="object"?Z.metadata:void 0)?.kind==="recovery_notice")continue;if(J+=1,J===f)return Q}throw Error(`Could not find user message for checkpoint run ${f}`)}function rz($,f){let J=eX($,f);return $.slice(0,J+1)}function $H($,f){let J=eX($,f);return $.slice(0,J)}function fH($){let f=$.checkpointRunCount;if(!Number.isInteger(f)||f<1)throw Error("checkpointRunCount must be a positive integer");let J=pz(d9($.session),f);if(!J)throw Error(`No checkpoint found at or before run ${f} in session ${$.session.sessionId}`);let Q=($.cwd?.trim()||$.session.cwd||$.session.workspaceRoot).trim();if(!Q)throw Error("cwd or workspaceRoot is required to restore a checkpoint");return{checkpoint:J,cwd:Q,...$.restoreMessages!==!1?{messages:rz($.messages??[],f)}:{}}}async function JH($,f){if((await W2("git",["-C",$,"rev-parse","--is-inside-work-tree"],{windowsHide:!0})).stdout.trim()!=="true")throw Error(`${$} is not a git repository`);if(await W2("git",["-C",$,"cat-file","-e",`${f.ref}^{commit}`],{windowsHide:!0}),await W2("git",["-C",$,"reset","--hard"],{windowsHide:!0}),await W2("git",["-C",$,"clean","-fd"],{windowsHide:!0}),f.kind==="commit"){await W2("git",["-C",$,"reset","--hard",f.ref],{windowsHide:!0});return}await W2("git",["-C",$,"stash","apply",f.ref],{windowsHide:!0})}class d0 extends Error{code;constructor($,f){super(f);this.code=$;this.name="SessionVersioningError"}}function iz($){let f=$.sessionId.trim();if(!f)throw new d0("invalid_restore","sessionId is required");if(!$.restoreMessages&&!$.restoreWorkspace)throw new d0("invalid_restore","restore.messages or restore.workspace must be true");if($.restoreMessages&&$.requiresStart)throw new d0("invalid_restore","start is required when restore.messages is true");if(!Number.isInteger($.checkpointRunCount)||$.checkpointRunCount<1)throw new d0("invalid_restore","checkpointRunCount must be a positive integer");return f}class j2{async restoreCheckpoint($){let f=$.restore?.messages!==!1,J=$.restore?.workspace!==!1,Q=iz({sessionId:$.sessionId,restoreMessages:f,restoreWorkspace:J,requiresStart:$.start===void 0,checkpointRunCount:$.checkpointRunCount}),Z=await $.getSession(Q);if(!Z)throw new d0("session_not_found",`Session ${Q} not found`);let W=f?await $.readMessages(Q):void 0;if(f&&W?.length===0)throw new d0("session_messages_not_found",`No messages found for session ${Q}`);let j=fH({session:Z,messages:W,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restoreMessages:f});if(J)await($.applyWorkspaceCheckpoint??JH)(j.cwd,j.checkpoint);let X=b$({session:Z,messages:W});if(!f)return{checkpoint:j.checkpoint,sourceSnapshot:X};let H=oX(Z,$.checkpointRunCount),Y=$.restore?.omitCheckpointMessageFromSession?$H(W??[],$.checkpointRunCount):j.messages??[],V={sourceSession:Z,sourceMessages:W,sourceSnapshot:X,plan:j,restoredCheckpointMetadata:H,initialMessages:Y,restoreMessages:f,restoreWorkspace:J,checkpointRunCount:$.checkpointRunCount};if(!$.start||!$.startSession)throw new d0("invalid_restore","start is required when restore.messages is true");let A=$.buildStartInput?await $.buildStartInput(V,$.start):$.start,B=await $.startSession(A),G=$.getStartedSessionId?.(B);if(G)await($.retainCheckpointRefs??Sj)(j.cwd,G,H?.history??[]);let K=G&&$.readRestoredSession?await $.readRestoredSession(G):void 0;return{sessionId:G,startResult:B,messages:j.messages,checkpoint:j.checkpoint,sourceSnapshot:X,...K?{restoredSnapshot:b$({session:K,messages:Y})}:{}}}}import{hasRuntimeConfigExtension as X_}from"@cline/shared";import{nanoid as H_}from"nanoid";Z$();import{appendFileSync as nz,existsSync as X2,mkdirSync as QH,readdirSync as az,readFileSync as ZH,renameSync as tz,writeFileSync as sz}from"node:fs";import{join as l9}from"node:path";import{resolveTeamDataDir as oz}from"@cline/shared/storage";function WH(){return new Date().toISOString()}function p9($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function jH($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class I6{teamDirPath;constructor($={}){this.teamDirPath=$.teamDir??oz()}init(){this.ensureTeamDir()}listTeamNames(){if(!X2(this.teamDirPath))return[];return az(this.teamDirPath,{withFileTypes:!0}).filter(($)=>$.isDirectory()).filter(($)=>X2(this.statePath($.name))).map(($)=>$.name).sort()}readState($){let f=this.readEnvelope($);return f?.teamState?jH(f.teamState):void 0}readHistory($,f=200){let J=this.historyPath($);if(!X2(J))return[];return ZH(J,"utf8").split(`
561
+ `).map((Q)=>Q.trim()).filter(Boolean).map((Q)=>{try{return JSON.parse(Q)}catch{return}}).filter((Q)=>Q!==void 0).reverse().slice(0,f)}loadRuntime($){let f=this.readEnvelope($);return{state:f?.teamState?jH(f.teamState):void 0,teammates:f?.teammates??[],interruptedRunIds:[]}}handleTeamEvent($,f){this.ensureTeamSubdir($),nz(this.historyPath($),`${JSON.stringify({ts:WH(),eventType:f.type,payload:f})}
562
+ `,"utf8")}persistRuntime($,f,J){this.ensureTeamSubdir($);let Q={version:1,updatedAt:WH(),teamState:f,teammates:J},Z=this.statePath($),W=`${Z}.tmp`;sz(W,`${JSON.stringify(Q,null,2)}
563
+ `,"utf8"),tz(W,Z)}markInProgressRunsInterrupted($,f){let J=this.readEnvelope($);if(!J?.teamState?.runs?.length)return[];let Q=J.teamState.runs.filter((W)=>W.status==="queued"||W.status==="running").map((W)=>W.id);if(Q.length===0)return[];let Z=new Date;return J.teamState={...J.teamState,runs:J.teamState.runs.map((W)=>W.status==="queued"||W.status==="running"?{...W,status:"interrupted",error:f,endedAt:Z}:W)},this.persistRuntime($,J.teamState,J.teammates),Q}ensureTeamDir(){if(!X2(this.teamDirPath))QH(this.teamDirPath,{recursive:!0});return this.teamDirPath}ensureTeamSubdir($){let f=l9(this.ensureTeamDir(),p9($));if(!X2(f))QH(f,{recursive:!0});return f}statePath($){return l9(this.ensureTeamDir(),p9($),"state.json")}historyPath($){return l9(this.ensureTeamDir(),p9($),"task-history.jsonl")}readEnvelope($){let f=this.statePath($);if(!X2(f))return;try{let J=JSON.parse(ZH(f,"utf8"));if(J?.version===1&&J.teamState)return J}catch{}return}}import{existsSync as ez,mkdirSync as $_}from"node:fs";import{join as f_}from"node:path";import{safeJsonParse as XH}from"@cline/shared";import{loadSqliteDb as J_,nowIso as r9}from"@cline/shared/db";import{resolveDbDataDir as Q_}from"@cline/shared/storage";function Z_(){return Q_()}function H2($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}function W_($){let f=XH($);if(!Array.isArray(f))return[];let J=[];for(let Q of f){if(!Q||typeof Q!=="object")continue;let Z=Q,W=Z.agentId,j=Z.rolePrompt;if(typeof W!=="string"||!W.trim())continue;if(typeof j!=="string"||!j.trim())continue;let X={agentId:W.trim(),rolePrompt:j};if(typeof Z.modelId==="string"&&Z.modelId.trim())X.modelId=Z.modelId.trim();if(typeof Z.maxIterations==="number"&&Number.isFinite(Z.maxIterations))X.maxIterations=Math.max(1,Math.floor(Z.maxIterations));J.push(X)}return J}function j_($){return{...$,tasks:$.tasks.map((f)=>({...f,createdAt:new Date(f.createdAt),updatedAt:new Date(f.updatedAt)})),mailbox:$.mailbox.map((f)=>({...f,sentAt:new Date(f.sentAt),readAt:f.readAt?new Date(f.readAt):void 0})),missionLog:$.missionLog.map((f)=>({...f,ts:new Date(f.ts)})),runs:($.runs??[]).map((f)=>({...f,startedAt:new Date(f.startedAt),endedAt:f.endedAt?new Date(f.endedAt):void 0,nextAttemptAt:f.nextAttemptAt?new Date(f.nextAttemptAt):void 0,heartbeatAt:f.heartbeatAt?new Date(f.heartbeatAt):void 0})),outcomes:($.outcomes??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),finalizedAt:f.finalizedAt?new Date(f.finalizedAt):void 0})),outcomeFragments:($.outcomeFragments??[]).map((f)=>({...f,createdAt:new Date(f.createdAt),reviewedAt:f.reviewedAt?new Date(f.reviewedAt):void 0}))}}class L8{teamDirPath;db;constructor($={}){this.teamDirPath=$.teamDir??Z_()}init(){this.getRawDb()}ensureTeamDir(){if(!ez(this.teamDirPath))$_(this.teamDirPath,{recursive:!0});return this.teamDirPath}dbPath(){return f_(this.ensureTeamDir(),"teams.db")}getRawDb(){if(this.db)return this.db;let $=J_(this.dbPath());return this.ensureSchema($),this.db=$,$}ensureSchema($){if($.exec("PRAGMA journal_mode = WAL;"),$.exec("PRAGMA busy_timeout = 5000;"),$.exec(`
564
564
  CREATE TABLE IF NOT EXISTS team_store_schema_version (
565
565
  lock INTEGER PRIMARY KEY CHECK (lock = 1),
566
566
  version INTEGER NOT NULL
@@ -644,8 +644,8 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
644
644
  version INTEGER NOT NULL DEFAULT 1,
645
645
  PRIMARY KEY(team_name, fragment_id)
646
646
  );
647
- `)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[Wf($)]);if(!f)return;let J=uX(f.state_json);if(!J)return;try{return yz(J)}catch{return}}readHistory($,f=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[Wf($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=Wf($),J=this.readState(f),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=Q?_z(Q.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
648
- VALUES (?, ?, ?, ?, NULL, ?)`,[Wf($),h9(),f,JSON.stringify(J),Q??null])}persistRuntime($,f,J){let Q=Wf($),Z=h9();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
647
+ `)}run($,f=[]){return this.getRawDb().prepare($).run(...f)}queryOne($,f=[]){return this.getRawDb().prepare($).get(...f)??void 0}queryAll($,f=[]){return this.getRawDb().prepare($).all(...f)}withTransaction($){let f=this.getRawDb();f.exec("BEGIN IMMEDIATE;");try{$(),f.exec("COMMIT;")}catch(J){try{f.exec("ROLLBACK;")}catch{}throw J}}listTeamNames(){return this.queryAll("SELECT team_name FROM team_runtime_snapshot ORDER BY team_name ASC").map(($)=>$.team_name)}readState($){let f=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[H2($)]);if(!f)return;let J=XH(f.state_json);if(!J)return;try{return j_(J)}catch{return}}readHistory($,f=200){return this.queryAll("SELECT event_type, payload_json, ts FROM team_events WHERE team_name = ? ORDER BY id DESC LIMIT ?",[H2($),f]).flatMap((J)=>{try{return[{eventType:J.event_type,payload:JSON.parse(J.payload_json),ts:J.ts}]}catch{return[]}})}loadRuntime($){let f=H2($),J=this.readState(f),Q=this.queryOne("SELECT team_name, state_json, teammates_json, updated_at FROM team_runtime_snapshot WHERE team_name = ?",[f]),Z=Q?W_(Q.teammates_json):[];return{state:J,teammates:Z,interruptedRunIds:[]}}appendTeamEvent($,f,J,Q){this.run(`INSERT INTO team_events (team_name, ts, event_type, payload_json, causation_id, correlation_id)
648
+ VALUES (?, ?, ?, ?, NULL, ?)`,[H2($),r9(),f,JSON.stringify(J),Q??null])}persistRuntime($,f,J){let Q=H2($),Z=r9();this.withTransaction(()=>{this.run(`INSERT INTO team_runtime_snapshot (team_name, state_json, teammates_json, updated_at)
649
649
  VALUES (?, ?, ?, ?)
650
650
  ON CONFLICT(team_name) DO UPDATE SET
651
651
  state_json = excluded.state_json,
@@ -690,28 +690,28 @@ ${$.summary}`,metadata:{kind:"compaction_summary",summary:$.summary,details:$.fi
690
690
  status = excluded.status,
691
691
  reviewed_by = excluded.reviewed_by,
692
692
  reviewed_at = excluded.reviewed_at,
693
- version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=Wf($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(Q.length===0)return[];let Z=h9();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
- WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function dX($={}){try{let f=new D2($);return f.init(),f}catch{let f=new T4({teamDir:$.teamDir});return f.init(),f}}function b9($,f){return Nz($,f)}function Mz($,f){let J=f?.["*"]??{},Q=f?.[$]??{};return{...J,...Q}.enabled!==!1}function qz($,f){return $.filter((J)=>Mz(J.name,f))}function lX($,f){return d1(qz($,f))}function pX(){return`team-${Tz(5)}`}function k9($,f,J,Q,Z,W,j,X){let H=p0[y$({mode:J})],Y=Rf(f,Q,J,Z??Df);return lX(yf({cwd:$,...H,enableSkills:!!j,...Y,executors:{...j?{skills:j}:{},...X??{}}}),W)}function wz($){return k9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,Sz,$.toolExecutors).some((f)=>f.name==="skills")}var Sz=async()=>"";async function Cz($){let f=w0();if(!Z1({filePath:f}))return{tools:[]};let J=new Ef({clientFactory:q8({settingsPath:f})}),Q;try{Q=await Cf(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let H=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${H}`),{tools:[]}}let Z=Q.filter((X)=>X.disabled!==!0),W=await Promise.allSettled(Z.map((X)=>S8({serverName:X.name,provider:J}))),j=[];for(let[X,H]of W.entries())if(H.status==="fulfilled")j.push(...H.value);else{let Y=H.reason instanceof Error?H.reason.message:String(H.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${Y}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function Ez($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function hz($){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 bz($){let f=p0[y$({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class M4{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:X,userInstructionService:H,configExtensions:Y,toolExecutors:V}=$,A=$.onTeamEvent??(()=>{}),B=bz(f),K=r0(),G=[],R=f.teamName?.trim()||pX(),F=f.sessionId?.trim()||R,P=b9(Y,"rules"),D=b9(Y,"skills"),O=b9(Y,"workflows"),_=P||D||O,L=!1,z=Boolean(H),y=H,T;if(!y&&_)y=v1({skills:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(y)await y.start().catch(()=>{});let e=B.enableTools&&D&&Boolean(y)&&(z||y?.hasConfiguredSkills(f.skills)===!0)&&wz({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:V}),$0=y&&_?y.createExtension({includeRules:P,includeSkills:D,includeWorkflows:O,registerSkillsTool:e,allowedSkillNames:f.skills}):void 0,a=$0?[...Q??f.extensions??[],$0]:Q??f.extensions;if(B.enableTools){if(G.push(...k9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,V)),!B.disableMcpSettingsTools){let u=await Cz(f.logger);G.push(...u.tools),T=u.shutdown}}let m,V0=B.enableAgentTeams?dX():void 0,B$=V0?.loadRuntime(F),v=B$?.state,s0=B$?.teammates??[],E=new Map(s0.map((u)=>[u.agentId,u])),p=f.sessionId||R,o0,u0=[],l$=!1,T1=R8({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:a,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(p))this.teamRuntimeEntries.set(p,{delegatedAgentConfigProvider:T1});let jf=()=>{if(!B.enableAgentTeams)return;let u=this.teamRuntimeEntries.get(p)??{delegatedAgentConfigProvider:T1};if(this.teamRuntimeEntries.set(p,u),m=u.runtime,!m){if(m=new X2({teamName:R,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(o)=>{if(A(o),m&&V0){if(o.type==="teammate_spawned"&&o.teammate?.rolePrompt){let e0={agentId:o.agentId,rolePrompt:o.teammate.rolePrompt,modelId:o.teammate.modelId,maxIterations:o.teammate.maxIterations};E.set(e0.agentId,e0)}if(o.type==="teammate_shutdown"&&!hz(o.reason))E.delete(o.agentId);V0.handleTeamEvent(F,o),V0.persistRuntime(F,m.exportState(),Array.from(E.values()))}}}),v)m.hydrateState(v),l$=!0;u.runtime=m}if(!L){if(!m)return;L=!0;let o=z8({runtime:m,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(v),restoredTeammates:s0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(e0)=>{u0=e0,o0?.addTools(e0)},createBaseTools:B.enableTools?()=>k9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,V):void 0,teammateConfigProvider:T1});if(l$)m.recoverActiveRuns("runtime_recovered");if(o.restoredFromPersistence)X?.();G.push(...o.tools)}return m};if(B.enableSpawnAgent&&j){let u=j();G.push({...u,execute:async(o,e0)=>{return jf(),u.execute(o,e0)}})}if(B.enableAgentTeams)jf();let T2=lX(G,f.toolPolicies),n4=T2.some((u)=>u.name===Z0.SUBMIT_AND_EXIT&&u.lifecycle?.completesRun===!0),M1=B.enableAgentTeams?()=>{let u=this.teamRuntimeEntries.get(p)?.runtime;if(!u)return;let o=u.listTasks(),e0=o.some((K$)=>K$.status==="in_progress"||K$.status==="pending"),U7=u.listRuns({}),TY=U7.some((K$)=>K$.status==="running"||K$.status==="queued");if(e0||TY){let K$=o.filter((y0)=>y0.status==="in_progress"||y0.status==="pending").map((y0)=>`${y0.id} (${y0.status}): ${y0.title}`).join(", "),L7=U7.filter((y0)=>y0.status==="running"||y0.status==="queued").map((y0)=>`${y0.id} (${y0.status})`).join(", "),a4=[];if(K$)a4.push(`Unfinished tasks: ${K$}`);if(L7)a4.push(`Active runs: ${L7}`);return`[SYSTEM] You still have team obligations. ${a4.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,Xf=n4?{requireCompletionTool:!0,...M1?{completionGuard:M1}:{}}:M1?{completionGuard:M1}:void 0;return{tools:T2,logger:Z??f.logger,telemetry:W??f.telemetry,teamRuntime:m,teamRestoredFromPersistence:Boolean(v),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(p)?.delegatedAgentConfigProvider??T1,extensions:a,completionPolicy:Xf,registerLeadAgent:(u)=>{if(o0=u,u0.length>0)u.addTools(d1(u0,[...K]))},shutdown:async(u)=>{if(Ez(m,u),this.teamRuntimeEntries.delete(p),await T?.(),!z)y?.stop()}}}}import{getClineEnvironmentConfig as kz,isOAuthProviderId as Iz}from"@cline/shared";var I9="workos:";function xz($,f){if($==="cline")return`${I9}${f}`;return f}function gz($,f){if($==="cline"&&f.toLowerCase().startsWith(I9))return f.slice(I9.length);return f}function mz($){let J=j0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function vz($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=mz(f);if(Q)return Q;return Date.now()-1}function cz($,f){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=gz($,J);if(!Z)return null;return{access:Z,refresh:Q,expires:vz(f,Z),accountId:f.auth?.accountId}}function uz($,f){let J=$?.expiresAt,Q=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===Q}class q4 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 x9{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new c$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!Iz($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let Q=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,Q),Q}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let Q=cz($,J);if(!Q)return null;let Z=await this.resolveCredentials($,J,Q,f);if(!Z)throw new q4($);let W=xz($,Z.access),j={...J.auth??{},accessToken:W,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let X={...J,auth:j},H=!uz(J.auth,X.auth);if(H)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:W,accountId:Z.accountId,refreshed:H}}async resolveCredentials($,f,J,Q){if($==="cline")return L6(J,{apiBaseUrl:f.baseUrl?.trim()||kz().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:Q});if($==="oca")return q6(J,{forceRefresh:Q,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return z6(J,{forceRefresh:Q,telemetry:this.telemetry})}}import{normalizeUserInput as dz}from"@cline/shared";import{nanoid as lz}from"nanoid";class rX{list($){return $?b0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((H)=>H.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:b0($),updated:!1};let Z=$.pendingPrompts[Q];if(!Z)return{sessionId:f.sessionId,prompts:b0($),updated:!1};let W=f.prompt===void 0?Z.prompt:dz(f.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:W,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(Q,1),pz($,X,Q,Z.delivery),{sessionId:f.sessionId,prompts:b0($),prompt:w4(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:b0($),removed:!1};let[Z]=$.pendingPrompts.splice(Q,1);return{sessionId:f.sessionId,prompts:b0($),prompt:Z?w4(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=f,X=$.pendingPrompts.findIndex((H)=>H.prompt===J);if(X>=0){let[H]=$.pendingPrompts.splice(X,1),Y={...H,prompt:J,mode:Q??H.mode,userImages:W??H.userImages,userFiles:j??H.userFiles};if(Z==="steer"||H.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let H={id:`pending_${Date.now()}_${lz(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(H);else $.pendingPrompts.push(H)}return b0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(f<0)return{prompts:b0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:b0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:b0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),b0($)}clear($){return $.pendingPrompts.length=0,[]}}class g9{deps;service=new rX;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:b0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,Q&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=w4(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function w4($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function b0($){return $.pendingPrompts.map(w4)}function pz($,f,J,Q){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(Q==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}R0();class v9{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let Q=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=K9(J),j=!!Q&&(!W.agentId||W.agentId===m9(Q.agent));G9(Z,J,j?{isPrimaryAgentEvent:!0,agentId:m9(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(n5(J,f),f.type==="agent_event"){let Q={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};G9(Q,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let Q=V$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:m9(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(Q)i$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await a5($,f,this.deps.invokeBackendOptional),J)t5(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let H=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!H)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await H.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let Q=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog($,f,J){let Q=this.deps.getSession($),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!f||typeof f!=="object")return;let W=f,j=typeof W.message==="string"?W.message:"";if(!j)return;let X=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(X.sessionId??=$,typeof W.pluginName==="string"&&W.pluginName)X.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,X);return}if(W.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function m9($){return $.getAgentId()}function c9($){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 u9($,f){let J=$[f];return typeof J==="function"?J:null}async function iX($,f,...J){let Q=u9($,f);if(!Q)throw Error(`session service method not available: ${f}`);return Promise.resolve(Q.apply($,J))}async function nX($,f,...J){let Q=u9($,f);if(!Q)return;await Promise.resolve(Q.apply($,J))}async function aX($,f,...J){let Q=u9($,f);if(!Q)return;return await Promise.resolve(Q.apply($,J))}Z$();R0();function d9($,f,J,Q){return m1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let W=f.enableTools?yf({cwd:f.cwd,...p0[y$({mode:f.mode})],executors:Q}):[];if(f.enableSpawnAgent)W.push(d9($,f,J,Q));return d1(W)},onSubAgentEvent:(W)=>$.onAgentEvent(J,f,W),onSubAgentStart:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(W.subAgentId,{startedAt:Date.now(),rootSessionId:J});let X=V$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId});if(X)i$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...X});S2(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:W.parentAgentId,agentId:W.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",J,W)},onSubAgentEnd:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime,X=$.subAgentStarts.get(W.subAgentId),H=X?Date.now()-X.startedAt:0,Y=W.result?.text?W.result.text.split(`
695
- `).length:0;S2(f.telemetry,{event:"ended",ulid:J,durationMs:H,outputLines:Y,errorMessage:W.error?String(W.error):void 0,agentId:W.subAgentId,parentId:W.parentAgentId,...V$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId})}),$.subAgentStarts.delete(W.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,W)}})}import{readFile as rz,stat as iz}from"node:fs/promises";var nz=20480000;async function tX($){let f=await iz($);if(!f.isFile())throw Error("Path is not a file");if(f.size>nz)throw Error("File is too large to read into context.");let J=await rz($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var sX=5000;function R2($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function J_($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=R2(f.inputTokens),Q=R2(f.outputTokens),Z=R2(f.cacheReadTokens),W=R2(f.cacheWriteTokens),j=R2(f.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function Q_($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class u${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new of;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new Qf;constructor($){let f=tz();if(f)f_(f);let J=P1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new M4,this.createAgentInstance=$.createAgent??((Q)=>new N$(Q)),this.defaultCapabilities=P0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new c$,this.oauthTokenManager=$.oauthTokenManager??new x9({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new g9({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new v9({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession($){let f=$.source??G0.CLI,J=n(),Q=$.config.sessionId?.trim()??"",Z=Q||oz(),W=$,j=W.initialMessages??[],X=j.length>0?B4(j):K0(),H=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!H)throw Error("session service method not available: ensureSessionsDir");let Y=l9(H,Z),V=l9(Y,`${Z}.messages.json`),A=l9(Y,`${Z}.json`),B=g$($.config),K=O0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:V}),G;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let E=await this.invokeOptionalValue("readSessionManifest",Z);if(E)K=E,G={manifestPath:A,messagesPath:E.messages_path||V,manifest:E}}let F=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:Y,rootMessagesPath:G?.messagesPath??V,manifest:K});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,F);let P=P0(this.defaultCapabilities,$.capabilities),D=P?.toolExecutors??this.toolExecutors,O=$.localRuntime,_=O?.extensionContext?.logger??O?.logger,L=O?.extensionContext?.automation,z;z=await KX({input:W,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:P,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(E)=>{if(E.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,E.payload,_);return}this.eventBridge.handlePluginEvent(Z,E,L)},onTeamEvent:(E)=>{this.eventBridge.handleTeamEvent(Z,E),z.config.onTeamEvent?.(E)},createSpawnTool:()=>d9({getSession:(E)=>this.sessions.get(E),subAgentStarts:this.subAgentStarts,onAgentEvent:(E,p,o0)=>this.eventBridge.dispatchAgentEvent(E,p,o0),invokeBackendOptional:(E,...p)=>this.invokeOptional(E,...p)},z.config,Z,D),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(E)=>{await this.persistSessionMetadata(Z,()=>E)}});let y=await this.runtimeBuilder.build(z.runtimeBuilderInput),T=z.config,e=z.providerConfig;if(y.teamRuntime&&!T.teamName?.trim())T.teamName=y.teamRuntime.getTeamName();let $0=[...y.tools,...T.extraTools??[]],a=y.extensions??z.extensions,m={sessionId:Z,providerId:e.providerId,modelId:e.modelId,apiKey:e.apiKey,baseUrl:e.baseUrl,headers:e.headers,knownModels:e.knownModels,providerConfig:e,thinking:T.thinking,reasoningEffort:T.reasoningEffort??e.reasoningEffort,systemPrompt:T.systemPrompt,maxIterations:T.maxIterations,execution:T.execution,prepareTurn:B9(T),tools:$0,hooks:z.hooks,extensions:a,hookErrorMode:T.hookErrorMode,initialMessages:z.effectiveInput.initialMessages,userFileContentLoader:tX,toolPolicies:z.toolPolicies,requestToolApproval:z.requestToolApproval,telemetry:T.telemetry,onConsecutiveMistakeLimitReached:T.onConsecutiveMistakeLimitReached,completionPolicy:y.completionPolicy,consumePendingUserMessage:()=>{let E=this.pendingPromptsController.consumeSteer(Z);return E?Y2(E.prompt,E.mode??T.mode):void 0},logger:y.logger??T.logger,extensionContext:T.extensionContext,onEvent:(E)=>this.eventBridge.dispatchAgentEvent(Z,T,E)};m.hooks={...m.hooks,onEvent:async(E)=>{if(await z.hooks?.onEvent?.(E),E.type!=="assistant-message")return;let p=this.sessions.get(Z);if(!p)return;let o0=p.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,o0,T.systemPrompt)}catch(u0){T.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:u0}),L1(T.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:u0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:T.providerId,modelId:T.modelId}})}}};let V0=this.createAgentInstance(m);if(m.onEvent)V0.subscribeEvents(m.onEvent);y.registerLeadAgent?.(V0);let B$=V$({agentId:V0.getAgentId(),conversationId:V0.getConversationId(),teamId:y.teamRuntime?.getTeamId(),teamName:y.teamRuntime?.getTeamName(),teamRole:y.teamRuntime?"lead":void 0});if(GX(T,Z,Q.length>0,B,B$),B$)i$(T.telemetry,{ulid:Z,modelId:T.modelId,provider:T.providerId,...B$});if(y.teamRuntime)B6(T.telemetry,{ulid:Z,teamId:y.teamRuntime.getTeamId(),teamName:y.teamRuntime.getTeamName(),leadAgentId:V0.getAgentId(),restoredFromPersistence:y.teamRestoredFromPersistence===!0});let v={sessionId:Z,config:T,sessionMetadata:W.sessionMetadata,...G?{artifacts:G}:{},source:f,startedAt:G?.manifest.started_at??J,updatedAt:G?.manifest.ended_at??G?.manifest.started_at??J,pendingPrompt:K.prompt,runtime:y,agent:V0,started:!1,status:G?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:z.pluginSandboxShutdown,submitAndExitObserved:!1};if(this.sessions.set(Z,v),this.emitStatus(Z,"running"),j.length>0&&!G){if(await this.ensureSessionPersisted(v),await this.invoke("persistSessionMessages",v.sessionId,j,v.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(v,"completed",0)}let s0;try{if(W.prompt?.trim())if(s0=await this.executeTurn(v,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!v.interactive)await this.finalizeSingleRun(v,s0.finishReason);else await this.completeInteractiveTurn(v,s0.finishReason)}catch(E){if(v.interactive&&v.aborting)s0=await this.completeAbortedInteractiveTurn(v);else throw L1(v.config.telemetry,{component:"core",operation:"session.start",error:E,severity:"error",handled:!1,context:{sessionId:v.sessionId,providerId:v.config.providerId,modelId:v.config.modelId}}),await this.failSession(v),E}return{sessionId:Z,manifest:K,manifestPath:A,messagesPath:V,result:s0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let Q=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),Q=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw L1(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=y5(this.usageBySession.get($)),J=y5(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&f.status!=="running"){await this.releaseSessionRuntime(f,"session_stop");return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&J.status!=="running"?this.releaseSessionRuntime(J,$):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return c9(f);let J=$.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return tf(Q);let Z=await this.readManifest(J);return Z?M5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(tf),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift(c9(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return S$(J.messagesPath);let Q=await this.readManifest(f);return S$(Q?.messages_path)}async dispatchHookEvent($){await qW($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,Q,J.userImages,J.userFiles);while(s5($,Z.finishReason)){let W=await o5($);if(W.length===0)break;let j=e5($,W);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(H2($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.updateStatus($,J?"cancelled":Q?"failed":"completed",Q?1:0),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f,ts:Date.now()}}),$.aborting=!1}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),Q=K0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,Q){let Z=$.started||$.agent.getMessages().length>0,W=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??K0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=K0(),$.turnUsageByAgent=new Map,W6($.config.telemetry,$.sessionId,$.config.mode),Hf($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let H=Z?()=>$.agent.continue(f,J,Q):()=>$.agent.run(f,J,Q),Y=await this.runWithAuthRetry($,H,W);$.started=!0;let V=n8(Y.messages,Y,W);$.persistedMessages=V;let A=A4($.turnUsageByAgent?.values()??[]),B=H0(j,Y.usage),K=H0(H0(K0(),Y.usage),A),G=H0(X,K);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,G),await this.persistSessionMetadata($.sessionId,(R)=>({...R??{},totalCost:B.totalCost,aggregatedAgentsCost:G.totalCost,usage:B,aggregateUsage:G})),await this.invoke("persistSessionMessages",$.sessionId,V,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(H){throw L1($.config.telemetry,{component:"core",operation:"session.turn",error:H,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),H}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((Q)=>Q.name===Z0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,q2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=g$($.config),Q=$_(f.prompt).trim();if(!Q)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await B8(Q,J);PX($.config.telemetry,Z);let W=Y2(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),H=Array.from(new Set([...j,...X]));return{prompt:W,userImages:f.userImages,userFiles:H.length>0?H:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=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:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(H2($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.shutdownSession($,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)q2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});H4($);let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),L1($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){Q("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),L1($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,f==="running")delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??n(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=Q.endedAt??n(),$.endedAt=f==="running"?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(Q){if(!ez(Q,$.config.providerId))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(Q){if(Q instanceof q4)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=Error(`session not found: ${$}`);throw L1(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>sz(Q)?Q:p9($,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return V$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=H0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let Q=p9(f),Z=`${J}.messages.json`,W;try{W=az($)}catch{return K0()}let j=K0();for(let X of W){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let H=p9($,X);if(H===Q)continue;let Y=await S$(H);if(Y.length===0)continue;j=H0(j,B4(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=J_(f.metadata?.aggregateUsage);if(J)return Q_($,J);let Q=f.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:h$({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),sX))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(sX)).find((Q)=>Q.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return iX(this.sessionService,$,...f)}invokeOptional($,...f){return nX(this.sessionService,$,...f)}invokeOptionalValue($,...f){return aX(this.sessionService,$,...f)}}function Z_($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var U2,L2;function W_($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;rW(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function j_($){await $.reconcileDeadSessions?.().catch(()=>{})}function $H($){try{let f=new k$;return f.init(),new I$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),eX($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new Q9(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function oX($,f,J){return new u$({sessionService:J??$.sessionService??$H($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function X_($){if(U2)return U2;if(L2)return await L2;return L2=(async()=>{return U2=$H($),await j_(U2),U2})().finally(()=>{L2=void 0}),await L2}async function S4($){let f=P1($.distinctId);$.telemetry?.setDistinctId(f);let J=Z_($);if(W_(J,$),J==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new $4({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let Q=$.hub?.endpoint?.trim(),Z=Q||await J2({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new G1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let Q=await g5({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new G1({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(W){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),eX($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),oX($,f)}return oX($,f)}class r9{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,Q,Z,W,j,X,H){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=X,this.settings=t3($),this.pendingPrompts=s3($),this.automation=new c6(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=H?new rf({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:BQ(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:KQ({host:$,getExtensionContext:()=>p2({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:H.dbPath,logger:H.logger,pollIntervalMs:H.pollIntervalMs,claimLeaseSeconds:H.claimLeaseSeconds,globalMaxConcurrency:H.globalMaxConcurrency,watcherDebounceMs:H.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((Y)=>{if(Y.type!=="ended")return;this.disposeSessionBootstrap(Y.payload.sessionId)})}static async create($={}){let f=P0($.capabilities),J=await S4({...$,capabilities:f}),Q=AQ($.automation),Z=new r9(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,Q?{...Q,logger:$.logger}:void 0);if(Q&&Q.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=o3($),J=await this.prepare?.(f);try{let Q=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(tJ(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>p2({automationService:this.automationService,automation:this.automation,context:W,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return e3({input:Q,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(Q){throw await Promise.resolve(J?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await q5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?tJ($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>p2({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as JH,HookEventPayloadSchema as QH,parseHookEventPayload as E4,resolveHookSessionContext as G_}from"@cline/shared";import{z as O1}from"zod";import{spawn as H_}from"node:child_process";import{augmentNodeCommandForDebug as Y_,withResolvedClineBuildEnv as V_}from"@cline/shared";function A_($){let f=$.trim();if(!f)return{};let Q=f.split(`
696
- `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function B_($,f){let J=$ instanceof Error?$:Error(String($)),Q=J,Z=f.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function K_($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end(f,(j)=>{if(J.off("error",W),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function C4($,f){let J=Y_(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!f.detached,Z=H_(J[0],J.slice(1),{cwd:f.cwd,env:V_(f.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,K)=>{Z.once("error",(G)=>{K(B_(G,J))})});if(await K_(Z,JSON.stringify($)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",H="",Y=!1,V;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{H+=B.toString()});let A=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(K)=>{if(V)clearTimeout(V);let{parsedJson:G,parseError:R}=A_(X);B({exitCode:K,stdout:X,stderr:H,parsedJson:G,parseError:R,timedOut:Y})})});return await Promise.race([A,j])}var P_=O1.object({contextModification:O1.string().optional(),cancel:O1.boolean().optional(),review:O1.boolean().optional(),errorMessage:O1.string().optional(),context:O1.string().optional(),overrideInput:O1.unknown().optional()}).passthrough();var F_=["agent","hook"];async function h4($,f={}){let J=f.command??F_;return await C4($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function ZH($){return $ instanceof Error?$:Error(String($))}function D_($){if(!$||typeof $!=="object")return;let f=P_.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function fH($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))if(typeof Q==="string")f[J]=Q;else f[J]=JSON.stringify(Q);return f}function A$($,f,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:G_(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function R_($){return{name:$.name,message:$.message,stack:$.stack}}function U_($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function L_($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function O_($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function z_($){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 __($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function z1($,f){try{let J=await h4($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(ZH(J),$)}}function WH($={}){return{hooks:{beforeRun:async(X)=>{let H=L_(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...A$("agent_resume",H,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await z1(V,$)}else{let V={...A$("agent_start",H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await z1(V,$)}return},beforeTool:async(X)=>{let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...A$("tool_call",H,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:fH(X.input)}};try{let V=await h4(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return __(D_(V?.parsedJson))}catch(V){$.onDispatchError?.(ZH(V),Y);return}},afterTool:async(X)=>{let H=z_(X),Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...A$("tool_result",Y,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:H,postToolUse:{toolName:H.name,parameters:fH(H.input),result:typeof H.output==="string"?H.output:JSON.stringify(H.output),success:!H.error,executionTimeMs:H.durationMs}};await z1(V,$);return},afterRun:async({snapshot:X,result:H})=>{let Y={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(H.status==="completed"){let B={...A$("agent_end",Y,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}};await z1(B,$);return}let V=H.status==="aborted"||U_(H.error?.message)?"agent_abort":"agent_error",A=V==="agent_error"?{...A$(V,Y,$),hookName:V,iteration:H.iterations,error:R_(H.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...A$(V,Y,$),hookName:V,reason:H.error?.message,taskCancel:{taskMetadata:{}}};await z1(A,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...A$("prompt_submit",H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:O_(X.message.content),attachments:[]}};await z1(Y,$)}},shutdown:async({agentId:X,conversationId:H,parentAgentId:Y,reason:V})=>{let A={...A$("session_shutdown",{agentId:X,conversationId:H,parentAgentId:Y},$),hookName:"session_shutdown",reason:V};await z1(A,$)}}}import{createSessionId as y_}from"@cline/shared";function k0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function jH($,f,J){return{version:$.version,requestId:$.requestId??y_("hubreq_"),ok:!1,error:{code:f,message:J}}}class b4{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return k0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return k0($,{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 k0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return k0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return k0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return k0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return k0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return k0($,{execution:await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return k0($,{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 k0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return k0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return k0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return jH($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return jH($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}function I4($){return $?new Date($).getTime():void 0}function N_($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function k4($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:I4($.nextRunAt),lastRunAt:I4($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:N_($)}}function T_($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function XH($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:I4($.startedAt),endedAt:I4($.completedAt),status:T_($.status),errorMessage:$.error}}class x4{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new pf({dbPath:$.dbPath}),this.materializer=new vf({store:this.store}),this.runner=new cf({store:this.store,materializer:this.materializer,runtimeHandlers:$.runtimeHandlers,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(X5($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return k4(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?k4(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>k4(f))}updateSchedule($,f){if(f.cronPattern!==void 0)X5(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let Q=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule($,{...f,scheduleId:$});return W?k4(W):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return XH(J,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let W=f??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return XH(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}c4();function a_($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var t_="cline-hub-auth.";function s_($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function o_($,f){let J=new URL($),Q=new URL(f);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function e_($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=D0(),Q=await B0(J.discoveryPath);if(Q?.url&&o_($.toString(),Q.url))return Q.authToken;return}async function $y($={}){let f=C$($);if(!s_($)){let J=D0(),Q=await B0(J.discoveryPath);if(Q?.url)return Q.url}return j$(f.host,f.port,f.pathname)}async function VH($){return await new Promise((f,J)=>{(async()=>{let Q=new URL($),Z=await e_(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${t_}${Z}`]:void 0),j=new Map,X=0;W.addEventListener("open",()=>{f({send(H){let Y=H.requestId??`hub-client-${++X}`;return new Promise((V,A)=>{j.set(Y,{resolve:V,reject:A});let B={kind:"command",envelope:{...H,requestId:Y}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(H)=>{let Y=JSON.parse(String(H.data));if(Y.kind==="reply"&&Y.envelope.requestId){let V=j.get(Y.envelope.requestId);if(V)j.delete(Y.envelope.requestId),V.resolve(Y.envelope)}}),W.addEventListener("close",()=>{for(let H of j.values())H.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(H)=>{J(a_(H,$))})})().catch(J)})}async function Rm($){try{return(await VH($)).close(),!0}catch{return!1}}async function Um($,f){let J=await $y($),Q=await VH(J);try{return await Q.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{Q.close()}}function c0($){return $?JSON.parse(JSON.stringify($)):{}}function u4($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?c0(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function AH($,f){return $.error?.message??`hub command failed: ${f}`}function fy($){let f=c0($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...f,error:Q.message.trim()};return f}function Jy($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function Qy($){let f=$.sessionId?.trim();if(!f)return;switch($.event){case"iteration.started":return{sessionId:f,eventType:"runtime.chat.iteration_start",payload:c0($.payload)};case"iteration.finished":return{sessionId:f,eventType:"runtime.chat.iteration_end",payload:c0($.payload)};case"assistant.delta":return{sessionId:f,eventType:"runtime.chat.text_delta",payload:c0($.payload)};case"usage.updated":return{sessionId:f,eventType:"runtime.chat.usage",payload:c0($.payload)};case"tool.started":return{sessionId:f,eventType:"runtime.chat.tool_call_start",payload:c0($.payload)};case"tool.finished":return{sessionId:f,eventType:"runtime.chat.tool_call_end",payload:c0($.payload)};case"approval.requested":return{sessionId:f,eventType:"approval.requested",payload:c0($.payload)};case"run.aborted":return{sessionId:f,eventType:"runtime.chat.aborted",payload:c0($.payload)};case"run.failed":return{sessionId:f,eventType:"runtime.chat.failed",payload:fy($.payload)};case"run.completed":return{sessionId:f,eventType:"runtime.chat.completed",payload:c0($.payload)};default:return}}class Zy{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new X$({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=u4(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.get",void 0,$);return u4(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(AH(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},f);if(!Z.ok)throw Error(AH(Z,"session.restore"));let W=u4(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=Jy(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((Q)=>u4({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=Qy(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;f.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress($,f){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;f.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{f.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class Wy{client;constructor($){this.client=new X$({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{normalizeProviderId as jy}from"@cline/llms";function Xy($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function Hy($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function Sm($={}){let f=new u$({sessionService:new I$(new k$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||G0.CLI,interactive:!1,config:{providerId:jy(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:Hy(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:Xy(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function Yy($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
697
- `).trim()||void 0}var BH=120,t9="...";function s9($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=BH)return f;let J=BH-Buffer.byteLength(t9,"utf8");if(J<=0)return t9;let Q="";for(let Z of f){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${t9}`}async function KH($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await S$(J)].reverse().find((H)=>H.role==="assistant"),W=Z?Yy(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:s9(W&&W.length>0?W:X.length>0?X:j),severity:"info"}}import{captureSdkError as r4,createSessionId as gy}from"@cline/shared";import{createSessionId as Ky}from"@cline/shared";import{createSessionId as By}from"@cline/shared";function Vy($){switch($){case"completed":return"completed";case"failed":return"failed";case"cancelled":return"aborted";default:return"running"}}function Ay($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function d4($,f,J,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:Vy($.status),participants:f?[...f.participants.values()]:[],metadata:Ay($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function x($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function b($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function l4($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function _0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function y1($,f,J){return{version:"v1",event:$,eventId:By("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function I0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let Q=await $.sessionHost.getAccumulatedUsage?.(f);return d4(J,$.sessionState.get(f),Q?.usage,Q?.aggregateUsage)}async function x0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[Q,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return h$({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function p4($,f,J,Q,Z={}){let W=$.sessionState.get(f);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(f,j),j}async function o9($,f){let J=Ky("approval_"),Q=f.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{$.pendingApprovals.set(J,{sessionId:Q,resolve:W}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},Q))})}function e9($,f,J){let Q=$.pendingApprovals.get(f);if(!Q)return;return $.pendingApprovals.delete(f),Q.resolve(J),{sessionId:Q.sessionId}}function $7($,f,J){let Q=0;for(let[Z,W]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:W.sessionId}))continue;$.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function GH($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return b(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,W=f.payload?.approved===!0,j=e9($,J,{approved:W,reason:Z});if(!j)return b(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),x(f,{approvalId:J,approved:W})}import{createSessionId as Fy}from"@cline/shared";function Gy($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var PH={debug:10,info:20,warn:30,error:40,silent:50};function Py(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function I($,f,J={}){if(PH[$]<PH[Py()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,Gy(W)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function f7($,f){let J=f instanceof Error?f.stack||f.message:String(f);I("error",$,{error:J})}async function FH($,f,J,Q,Z,W){let j=Fy("capreq_"),X=performance.now();return I("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((H,Y)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(V)=>{if(I(V.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-X)}),!V.ok){Y(Error(V.error||`Capability ${J} was rejected by ${Z}.`));return}H(V.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},f)),I("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function DH($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return b(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==Q.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return Q.onProgress?.(W),x(f,{requestId:J})}function d$($,f,J){let Q=0;for(let[Z,W]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...W}))continue;$.pendingCapabilityRequests.delete(Z),I("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function RH($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",Q=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!Q||!Z)return b(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,Q,W,Z);return x(f,j)}catch(W){return b(f,"capability_request_failed",W instanceof Error?W.message:String(W))}}function UH($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return b(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==Q.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(J);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return I(X?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,error:j}),Q.resolve({ok:X,payload:W,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,payload:W,error:j},Q.sessionId)),x(f,{requestId:J,ok:X})}import{createSessionId as Dy}from"@cline/shared";function LH($,f){let J=f.payload,Q=J?.clientId?.trim()||f.clientId?.trim()||Dy("client_");return $.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),x(f,{clientId:Q})}function OH($,f){let J=f.clientId?.trim(),Q=J?$.clients.get(J):void 0;if(!J||!Q)return b(f,"client_not_found","Client is not registered with this hub.");let Z=l4(f.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return x(f)}function zH($,f,J){let Q=f.clientId?.trim();if(Q)$.clients.delete(Q),J(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return x(f)}function _H($,f){return x(f,{clients:[...$.clients.values()]})}var Ry=30000;function Uy($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function Ly($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function Oy($){return $?$:void 0}function zy($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function _y($,f,J,Q){let Z=performance.now(),W=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:Q},X=setInterval(()=>{if(W)return;let V=Math.round(performance.now()-Z);I("warn","run.heartbeat",{...j,elapsedMs:V}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:V,...Q?{timeoutMs:Q}:{}},J.sessionId))},Ry),H=$.sessionHost.runTurn(J);H.then((V)=>{if(!W)return;I("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:V?.finishReason})},(V)=>{if(!W)return;I("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:V})});let Y;try{if(!Q)return await H;return await Promise.race([H,new Promise((V,A)=>{Y=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${Q}ms.`;W=!0,clearInterval(X),A(Error(B)),I("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),$7($,(K)=>K.sessionId===J.sessionId,B),d$($,(K)=>K.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((K)=>{I("error","run.timeout_abort_failed",{...j,error:K})})},Q)})])}finally{if(W=!0,clearInterval(X),Y)clearTimeout(Y)}}async function yH($,f){let J=_0(f),Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return b(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((V)=>typeof V==="string"):void 0,X=zy(Q);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let H;try{H=await _y($,f,{sessionId:J,prompt:Z,mode:Oy(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(V){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);throw $.publish($.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(H){let V=await x0($,J),A=Ly(H);if($.publish($.buildEvent(Uy(H.finishReason),{reason:H.finishReason,...A?{error:A}:{},result:H,...V?{snapshot:V}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let Y=await x0($,J);return x(f,H||Y?{...H?{result:H}:{},...Y?{snapshot:Y}:{}}:void 0)}async function NH($,f){let J=_0(f),Q=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";return $7($,(Z)=>Z.sessionId===J,Q),await $.sessionHost.abort(J,f.payload?.reason),d$($,(Z)=>Z.sessionId===J,Q),$.publish($.buildEvent("run.aborted",{reason:Q},J)),x(f,{applied:!0})}async function TH($,f){let J=E4(f.payload?.payload);if(!J)return b(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),x(f,{applied:!0})}async function MH($,f){switch(f.type){case"chunk":return;case"agent_event":await yy($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([I0($,f.payload.sessionId),x0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},f.payload.sessionId));return}case"ended":await Ny($,f);return;default:return}}async function yy($,f){let{sessionId:J,event:Q}=f.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function Ny($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),Q=J===f.payload.reason||J==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,W]=await Promise.all([I0($,f.payload.sessionId),x0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await KH(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(Q)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...W?{snapshot:W}:{}},f.payload.sessionId))}import{createSessionId as wH,parseRuntimeConfigExtensions as SH}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as jv,HUB_COMPACTION_CAPABILITY as Xv,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Hv,HUB_HOOK_CAPABILITY_PREFIX as Yv,HUB_MISTAKE_LIMIT_CAPABILITY as Vv,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Av,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Bv,isHubToolExecutorName as Ty}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Dv,HUB_COMPACTION_CAPABILITY as Rv,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Uv,HUB_HOOK_CAPABILITY_PREFIX as Lv,HUB_MISTAKE_LIMIT_CAPABILITY as Ov,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as zv,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as _v}from"@cline/shared";var My=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function N1($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function qy($,f){let J=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",W=N1($.inputSchema);if(!J||!Q||!W||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...N1($.lifecycle)?{lifecycle:N1($.lifecycle)}:{}}}function Q7($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let X=qy(Z,J);if(X)f.push(X);continue}if(W==="toolExecutor"){let X=Z.executor;if(!Ty(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(W==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(W==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...N1(Z.config)?{config:N1(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...N1(Z.config)?{config:N1(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function qH($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function wy($){return Object.hasOwn($,"update")?$.update:$}function y2($){return $.trim().replace(/^\/+/,"").toLowerCase()}function Sy($){let f=($??[]).map(y2).filter(Boolean);return f.length>0?new Set(f):void 0}function Cy($,f,J){if(!J)return!0;let Q=y2($),Z=y2(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function J7($,f){let J=Sy(f);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>Cy(Q.id,Q.name,J))}function Ey($,f){let J=async(Q,Z)=>{let W=y2(Q),X=J7($,f).filter((B)=>B.id===W||y2(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(X.length!==1)return X.length>1?`Skill "${Q}" is ambiguous. Use one of: ${X.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let H=X[0].skill,Y=Z?.trim(),V=Y?`
693
+ version = team_outcome_fragments.version + 1`,[Q,W.outcomeId,W.id,W.section,W.sourceAgentId,W.sourceRunId??null,W.content,W.status,W.reviewedBy??null,W.reviewedAt?W.reviewedAt.toISOString():null])})}markInProgressRunsInterrupted($,f){let J=H2($),Q=this.queryAll("SELECT run_id FROM team_runs WHERE team_name = ? AND status IN ('queued', 'running')",[J]);if(Q.length===0)return[];let Z=r9();return this.run(`UPDATE team_runs SET status = 'interrupted', error = ?, ended_at = ?, version = version + 1
694
+ WHERE team_name = ? AND status IN ('queued', 'running')`,[f,Z,J]),Q.map((W)=>W.run_id)}handleTeamEvent($,f){this.appendTeamEvent($,f.type,f)}}function HH($={}){try{let f=new L8($);return f.init(),f}catch{let f=new I6({teamDir:$.teamDir});return f.init(),f}}function i9($,f){return X_($,f)}function Y_($,f){let J=f?.["*"]??{},Q=f?.[$]??{};return{...J,...Q}.enabled!==!1}function V_($,f){return $.filter((J)=>Y_(J.name,f))}function YH($,f){return l1(V_($,f))}function VH(){return`team-${H_(5)}`}function n9($,f,J,Q,Z,W,j,X){let H=r0[N$({mode:J})],Y=L2(f,Q,J,Z??R2);return YH(M2({cwd:$,...H,enableSkills:!!j,...Y,executors:{...j?{skills:j}:{},...X??{}}}),W)}function A_($){return n9($.cwd,$.providerId,$.mode,$.modelId,$.toolRoutingRules,$.toolPolicies,B_,$.toolExecutors).some((f)=>f.name==="skills")}var B_=async()=>"";async function G_($){let f=C0();if(!X1({filePath:f}))return{tools:[]};let J=new b2({clientFactory:b4({settingsPath:f})}),Q;try{Q=await E2(J,{filePath:f})}catch(X){await J.dispose().catch(()=>{});let H=X instanceof Error?X.message:String(X);return $?.log(`[mcp] Failed to load MCP settings, skipping MCP tools: ${H}`),{tools:[]}}let Z=Q.filter((X)=>X.disabled!==!0),W=await Promise.allSettled(Z.map((X)=>I4({serverName:X.name,provider:J}))),j=[];for(let[X,H]of W.entries())if(H.status==="fulfilled")j.push(...H.value);else{let Y=H.reason instanceof Error?H.reason.message:String(H.reason);$?.log(`[mcp] Failed to load tools from MCP server "${Z[X].name}", skipping: ${Y}`)}return{tools:j,shutdown:async()=>{await J.dispose()}}}function K_($,f){if(!$)return;for(let J of $.getTeammateIds())try{$.shutdownTeammate(J,f)}catch{}}function F_($){if($===void 0)return!0;switch($){case"session_stop":case"session_complete":case"session_error":case"session_manager_dispose":case"cli_run_shutdown":case"cli_interactive_shutdown":case"cli_interactive_startup_cancelled":case"provider_change":case"acp_shutdown":case"hub_server_stop":case"vscode_webview_dispose":return!0;default:return!1}}function P_($){let f=r0[N$({mode:$.mode})];return{sessionId:$.sessionId||"",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",enableTools:$.enableTools!==!1,enableSpawnAgent:$.enableSpawnAgent??f.enableSpawnAgent??!0,enableAgentTeams:$.enableAgentTeams??f.enableAgentTeams??!0,disableMcpSettingsTools:$.disableMcpSettingsTools===!0,yolo:$.yolo===!0,missionLogIntervalSteps:typeof $.missionLogIntervalSteps==="number"&&Number.isFinite($.missionLogIntervalSteps)?$.missionLogIntervalSteps:3,missionLogIntervalMs:typeof $.missionLogIntervalMs==="number"&&Number.isFinite($.missionLogIntervalMs)?$.missionLogIntervalMs:120000}}class x6{teamRuntimeEntries=new Map;async build($){let{config:f,hooks:J,extensions:Q,logger:Z,telemetry:W,createSpawnTool:j,onTeamRestored:X,userInstructionService:H,configExtensions:Y,toolExecutors:V}=$,A=$.onTeamEvent??(()=>{}),B=P_(f),G=Q$(),K=[],D=f.teamName?.trim()||VH(),F=f.sessionId?.trim()||D,P=i9(Y,"rules"),U=i9(Y,"skills"),z=i9(Y,"workflows"),_=P||U||z,R=!1,L=Boolean(H),N=H,M;if(!N&&_)N=c1({skills:{workspacePath:f.cwd},rules:{workspacePath:f.cwd},workflows:{workspacePath:f.cwd}});if(N)await N.start().catch(()=>{});let o=B.enableTools&&U&&Boolean(N)&&N?.hasConfiguredSkills(f.skills)===!0&&A_({cwd:f.cwd,providerId:f.providerId,mode:B.mode,modelId:f.modelId,toolRoutingRules:f.toolRoutingRules,toolPolicies:f.toolPolicies,toolExecutors:V}),e=N&&_?N.createExtension({includeRules:P,includeSkills:U,includeWorkflows:z,registerSkillsTool:o,allowedSkillNames:f.skills}):void 0,a=e?[...Q??f.extensions??[],e]:Q??f.extensions;if(B.enableTools){if(K.push(...n9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,V)),!B.disableMcpSettingsTools){let p=await G_(f.logger);K.push(...p.tools),M=p.shutdown}}let v,V0=B.enableAgentTeams?HH():void 0,B$=V0?.loadRuntime(F),u=B$?.state,s0=B$?.teammates??[],h=new Map(s0.map((p)=>[p.agentId,p])),l=f.sessionId||D,M0,L0=[],r$=!1,y1=N4({providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey??"",baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:J,extensions:a,logger:Z??f.logger,telemetry:$.telemetry??f.telemetry,workspaceMetadata:f.workspaceMetadata});if(!this.teamRuntimeEntries.has(l))this.teamRuntimeEntries.set(l,{delegatedAgentConfigProvider:y1});let Y2=()=>{if(!B.enableAgentTeams)return;let p=this.teamRuntimeEntries.get(l)??{delegatedAgentConfigProvider:y1};if(this.teamRuntimeEntries.set(l,p),v=p.runtime,!v){if(v=new V8({teamName:D,leadAgentId:f.sessionId||"lead",missionLogIntervalSteps:B.missionLogIntervalSteps,missionLogIntervalMs:B.missionLogIntervalMs,onTeamEvent:(s)=>{if(A(s),v&&V0){if(s.type==="teammate_spawned"&&s.teammate?.rolePrompt){let o0={agentId:s.agentId,rolePrompt:s.teammate.rolePrompt,modelId:s.teammate.modelId,maxIterations:s.teammate.maxIterations};h.set(o0.agentId,o0)}if(s.type==="teammate_shutdown"&&!F_(s.reason))h.delete(s.agentId);V0.handleTeamEvent(F,s),V0.persistRuntime(F,v.exportState(),Array.from(h.values()))}}}),u)v.hydrateState(u),r$=!0;p.runtime=v}if(!R){if(!v)return;R=!0;let s=y4({runtime:v,leadAgentId:f.sessionId||"lead",restoredFromPersistence:Boolean(u),restoredTeammates:s0,includeLeadSpawnTool:!0,includeLeadManagementTools:!0,onLeadToolsUnlocked:(o0)=>{L0=o0,M0?.addTools(o0)},createBaseTools:B.enableTools?()=>n9(f.cwd,f.providerId,B.mode,f.modelId,f.toolRoutingRules,f.toolPolicies,void 0,V):void 0,teammateConfigProvider:y1});if(r$)v.recoverActiveRuns("runtime_recovered");if(s.restoredFromPersistence)X?.();K.push(...s.tools)}return v};if(B.enableSpawnAgent&&j){let p=j();K.push({...p,execute:async(s,o0)=>{return Y2(),p.execute(s,o0)}})}if(B.enableAgentTeams)Y2();let w8=YH(K,f.toolPolicies),Wf=w8.some((p)=>p.name===W0.SUBMIT_AND_EXIT&&p.lifecycle?.completesRun===!0),w1=B.enableAgentTeams?()=>{let p=this.teamRuntimeEntries.get(l)?.runtime;if(!p)return;let s=p.listTasks(),o0=s.some((G$)=>G$.status==="in_progress"||G$.status==="pending"),E7=p.listRuns({}),rY=E7.some((G$)=>G$.status==="running"||G$.status==="queued");if(o0||rY){let G$=s.filter((q0)=>q0.status==="in_progress"||q0.status==="pending").map((q0)=>`${q0.id} (${q0.status}): ${q0.title}`).join(", "),b7=E7.filter((q0)=>q0.status==="running"||q0.status==="queued").map((q0)=>`${q0.id} (${q0.status})`).join(", "),jf=[];if(G$)jf.push(`Unfinished tasks: ${G$}`);if(b7)jf.push(`Active runs: ${b7}`);return`[SYSTEM] You still have team obligations. ${jf.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,V2=Wf?{requireCompletionTool:!0,...w1?{completionGuard:w1}:{}}:w1?{completionGuard:w1}:void 0;return{tools:w8,logger:Z??f.logger,telemetry:W??f.telemetry,teamRuntime:v,teamRestoredFromPersistence:Boolean(u),delegatedAgentConfigProvider:this.teamRuntimeEntries.get(l)?.delegatedAgentConfigProvider??y1,extensions:a,completionPolicy:V2,registerLeadAgent:(p)=>{if(M0=p,L0.length>0)p.addTools(l1(L0,[...G]))},shutdown:async(p)=>{if(K_(v,p),this.teamRuntimeEntries.delete(l),await M?.(),!L)N?.stop()}}}}import{getClineEnvironmentConfig as U_,isOAuthProviderId as D_}from"@cline/shared";var a9="workos:";function R_($,f){if($==="cline")return`${a9}${f}`;return f}function L_($,f){if($==="cline"&&f.toLowerCase().startsWith(a9))return f.slice(a9.length);return f}function O_($){let J=K0($)?.exp;if(typeof J==="number"&&J>0)return J*1000;return null}function z_($,f){let J=$.auth?.expiresAt;if(typeof J==="number"&&Number.isFinite(J)&&J>0)return J;let Q=O_(f);if(Q)return Q;return Date.now()-1}function __($,f){let J=f.auth?.accessToken?.trim(),Q=f.auth?.refreshToken?.trim();if(!J||!Q)return null;let Z=L_($,J);if(!Z)return null;return{access:Z,refresh:Q,expires:z_(f,Z),accountId:f.auth?.accountId}}function N_($,f){let J=$?.expiresAt,Q=f?.expiresAt;return $?.accessToken===f?.accessToken&&$?.refreshToken===f?.refreshToken&&$?.accountId===f?.accountId&&J===Q}class m6 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 t9{providerSettingsManager;telemetry;refreshInFlight=new Map;constructor($){this.providerSettingsManager=$?.providerSettingsManager??new d$,this.telemetry=$?.telemetry}async resolveProviderApiKey($){if(!D_($.providerId))return null;return this.resolveWithSingleFlight($.providerId,$.forceRefresh)}async resolveWithSingleFlight($,f=!1){let J=this.refreshInFlight.get($);if(J)return J;let Q=this.resolveProviderApiKeyInternal($,f).catch((Z)=>{throw Z}).finally(()=>{this.refreshInFlight.delete($)});return this.refreshInFlight.set($,Q),Q}async resolveProviderApiKeyInternal($,f){let J=this.providerSettingsManager.getProviderSettings($);if(!J)return null;let Q=__($,J);if(!Q)return null;let Z=await this.resolveCredentials($,J,Q,f);if(!Z)throw new m6($);let W=R_($,Z.access),j={...J.auth??{},accessToken:W,refreshToken:Z.refresh,accountId:Z.accountId};j.expiresAt=Z.expires;let X={...J,auth:j},H=!N_(J.auth,X.auth);if(H)this.providerSettingsManager.saveProviderSettings(X,{setLastUsed:!1,tokenSource:"oauth"});return{providerId:$,apiKey:W,accountId:Z.accountId,refreshed:H}}async resolveCredentials($,f,J,Q){if($==="cline")return Ef(J,{apiBaseUrl:f.baseUrl?.trim()||U_().apiBaseUrl,telemetry:this.telemetry},{forceRefresh:Q});if($==="oca")return uf(J,{forceRefresh:Q,telemetry:this.telemetry},{mode:f.oca?.mode,telemetry:this.telemetry});return kf(J,{forceRefresh:Q,telemetry:this.telemetry})}}import{normalizeUserInput as T_}from"@cline/shared";import{nanoid as M_}from"nanoid";class AH{list($){return $?x0($):[]}update($,f){if(!$)return{sessionId:f.sessionId,prompts:[],updated:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((H)=>H.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:x0($),updated:!1};let Z=$.pendingPrompts[Q];if(!Z)return{sessionId:f.sessionId,prompts:x0($),updated:!1};let W=f.prompt===void 0?Z.prompt:T_(f.prompt).trim();if(!W)throw Error("prompt cannot be empty");let j=f.delivery??Z.delivery,X={...Z,prompt:W,mode:f.mode??Z.mode,delivery:j};return $.pendingPrompts.splice(Q,1),q_($,X,Q,Z.delivery),{sessionId:f.sessionId,prompts:x0($),prompt:g6(X),updated:!0}}delete($,f){if(!$)return{sessionId:f.sessionId,prompts:[],removed:!1};let J=f.promptId.trim(),Q=$.pendingPrompts.findIndex((W)=>W.id===J);if(Q<0)return{sessionId:f.sessionId,prompts:x0($),removed:!1};let[Z]=$.pendingPrompts.splice(Q,1);return{sessionId:f.sessionId,prompts:x0($),prompt:Z?g6(Z):void 0,removed:!0}}enqueue($,f){let{prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j}=f,X=$.pendingPrompts.findIndex((H)=>H.prompt===J);if(X>=0){let[H]=$.pendingPrompts.splice(X,1),Y={...H,prompt:J,mode:Q??H.mode,userImages:W??H.userImages,userFiles:j??H.userFiles};if(Z==="steer"||H.delivery==="steer")$.pendingPrompts.unshift({...Y,delivery:"steer"});else $.pendingPrompts.push(Y)}else{let H={id:`pending_${Date.now()}_${M_(5)}`,prompt:J,mode:Q,delivery:Z,userImages:W,userFiles:j};if(Z==="steer")$.pendingPrompts.unshift(H);else $.pendingPrompts.push(H)}return x0($)}consumeSteer($){let f=$.pendingPrompts.findIndex((Q)=>Q.delivery==="steer");if(f<0)return{prompts:x0($)};let[J]=$.pendingPrompts.splice(f,1);return{entry:J,prompts:x0($)}}shiftNext($){return{entry:$.pendingPrompts.shift(),prompts:x0($)}}requeueFront($,f){return $.pendingPrompts.unshift(f),x0($)}clear($){return $.pendingPrompts.length=0,[]}}class s9{deps;service=new AH;constructor($){this.deps=$}list($){return this.service.list(this.deps.getSession($))}update($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],updated:!1};let J=this.service.update(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}delete($){let f=this.deps.getSession($.sessionId);if(!f||f.aborting)return{sessionId:$.sessionId,prompts:[],removed:!1};let J=this.service.delete(f,$);return this.emitPrompts(f),this.scheduleDrain($.sessionId,f),J}enqueue($,f){let J=this.deps.getSession($);if(!J||J.aborting)return;this.service.enqueue(J,f),this.emitPrompts(J),this.scheduleDrain($,J)}consumeSteer($){let f=this.deps.getSession($);if(!f)return;let{entry:J}=this.service.consumeSteer(f);if(!J)return;return this.emitPrompts(f),this.emitSubmitted(f,J),J}clearAborted($){if($.pendingPrompts.length===0)return;this.service.clear($),this.emitPrompts($)}emitPrompts($){this.deps.emit({type:"pending_prompts",payload:{sessionId:$.sessionId,prompts:x0($)}})}scheduleDrain($,f){if(f.pendingPrompts.length===0||f.aborting||f.drainingPendingPrompts||!f.agent.canStartRun())return;queueMicrotask(()=>{this.drain($)})}async drain($){let f=this.deps.getSession($);if(!f)return;if(f.aborting||f.drainingPendingPrompts)return;if(!f.agent.canStartRun())return;let{entry:J}=this.service.shiftNext(f);if(!J)return;this.emitPrompts(f),this.emitSubmitted(f,J),f.drainingPendingPrompts=!0;let Q=!0;try{await this.deps.send({sessionId:$,prompt:J.prompt,...J.mode?{mode:J.mode}:{},userImages:J.userImages,userFiles:J.userFiles})}catch{Q=!1,this.service.requeueFront(f,J),this.emitPrompts(f)}finally{if(f.drainingPendingPrompts=!1,Q&&f.pendingPrompts.length>0&&f.status!=="failed"&&f.status!=="cancelled")queueMicrotask(()=>{this.drain($)})}}emitSubmitted($,f){let J=g6(f);this.deps.emit({type:"pending_prompt_submitted",payload:{sessionId:$.sessionId,id:J.id,prompt:J.prompt,delivery:J.delivery,attachmentCount:J.attachmentCount}})}}function g6($){return{id:$.id,prompt:$.prompt,delivery:$.delivery,attachmentCount:($.userImages?.length??0)+($.userFiles?.length??0)}}function x0($){return $.pendingPrompts.map(g6)}function q_($,f,J,Q){if(f.delivery==="steer")$.pendingPrompts.unshift(f);else if(Q==="steer")$.pendingPrompts.push(f);else $.pendingPrompts.splice(J,0,f)}G0();class e9{deps;constructor($){this.deps=$}dispatchAgentEvent($,f,J){let Q=this.deps.getSession($),Z={sessionId:$,config:f,liveSession:Q,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit},W=M9(J),j=!!Q&&(!W.agentId||W.agentId===o9(Q.agent));q9(Z,J,j?{isPrimaryAgentEvent:!0,agentId:o9(Q.agent),conversationId:Q.agent.getConversationId(),...Q?.runtime.teamRuntime?{teamRole:"lead"}:{}}:{isPrimaryAgentEvent:!1})}async handleTeamEvent($,f){let J=this.deps.getSession($);if(J){if(X9(J,f),f.type==="agent_event"){let Q={sessionId:$,config:J.config,liveSession:J,usageBySession:this.deps.usageBySession,aggregateUsageBySession:this.deps.aggregateUsageBySession,persistMessages:this.deps.persistMessages,emit:this.deps.emit};q9(Q,f.event,{agentId:f.agentId,teamRole:"teammate",teamAgentId:f.agentId,isPrimaryAgentEvent:!1})}if(f.type==="teammate_spawned"){let Q=V$({agentId:f.teammate.runtimeAgentId??f.agentId,conversationId:f.teammate.conversationId,parentAgentId:f.teammate.parentAgentId,createdByAgentId:o9(J.agent),teamId:J.runtime.teamRuntime?.getTeamId(),teamName:J.runtime.teamRuntime?.getTeamName(),teamRole:"teammate",teamAgentId:f.agentId});if(Q)a$(J.config.telemetry,{ulid:$,modelId:f.teammate.modelId??J.config.modelId,provider:J.config.providerId,...Q})}}if(await H9($,f,this.deps.invokeBackendOptional),J)Y9(J,$,f,this.deps.emit)}async handlePluginEvent($,f,J){if(f.name==="plugin_log"){this.handlePluginLog($,f.payload);return}if(f.name==="automation_event"){let H=this.deps.getSession($)?.config.extensionContext?.automation??J;if(!H)return;let Y=f.payload&&typeof f.payload==="object"?f.payload:void 0;if(!Y)return;await H.ingestEvent(Y);return}if(f.name!=="steer_message"&&f.name!=="queue_message"&&f.name!=="pending_prompt")return;let Q=f.payload&&typeof f.payload==="object"?f.payload:void 0,Z=typeof Q?.sessionId==="string"&&Q.sessionId.trim().length>0?Q.sessionId.trim():$,W=typeof Q?.prompt==="string"?Q.prompt.trim():"";if(!W)return;let j=f.name==="steer_message"?"steer":f.name==="queue_message"?"queue":Q?.delivery==="steer"?"steer":"queue";this.deps.enqueuePendingPrompt(Z,{prompt:W,delivery:j})}handlePluginLog($,f,J){let Q=this.deps.getSession($),Z=J??Q?.config.extensionContext?.logger??Q?.config.logger;if(!Z||!f||typeof f!=="object")return;let W=f,j=typeof W.message==="string"?W.message:"";if(!j)return;let X=W.metadata&&typeof W.metadata==="object"?{...W.metadata}:{};if(X.sessionId??=$,typeof W.pluginName==="string"&&W.pluginName)X.pluginName=W.pluginName;if(W.level==="debug"){Z.debug(j,X);return}if(W.level==="error"){if(Z.error)Z.error(j,X);else Z.log(j,{...X,severity:"error"});return}Z.log(j,X)}}function o9($){return $.getAgentId()}function $7($){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:v$($.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 f7($,f){let J=$[f];return typeof J==="function"?J:null}async function BH($,f,...J){let Q=f7($,f);if(!Q)throw Error(`session service method not available: ${f}`);return Promise.resolve(Q.apply($,J))}async function GH($,f,...J){let Q=f7($,f);if(!Q)return;await Promise.resolve(Q.apply($,J))}async function KH($,f,...J){let Q=f7($,f);if(!Q)return;return await Promise.resolve(Q.apply($,J))}Z$();G0();function J7($,f,J,Q){return u1({configProvider:{getRuntimeConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getRuntimeConfig()??{providerId:f.providerId,modelId:f.modelId,cwd:f.cwd,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking,maxIterations:f.maxIterations,hooks:f.hooks,extensions:f.extensions,logger:f.logger,telemetry:f.telemetry},getConnectionConfig:()=>$.getSession(J)?.runtime.delegatedAgentConfigProvider?.getConnectionConfig()??{providerId:f.providerId,modelId:f.modelId,apiKey:f.apiKey,baseUrl:f.baseUrl,headers:f.headers,providerConfig:f.providerConfig,knownModels:f.knownModels,thinking:f.thinking},updateConnectionDefaults:()=>{}},createSubAgentTools:()=>{let W=f.enableTools?M2({cwd:f.cwd,...r0[N$({mode:f.mode})],executors:Q}):[];if(f.enableSpawnAgent)W.push(J7($,f,J,Q));return l1(W)},onSubAgentEvent:(W)=>$.onAgentEvent(J,f,W),onSubAgentStart:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime;$.subAgentStarts.set(W.subAgentId,{startedAt:Date.now(),rootSessionId:J});let X=V$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId});if(X)a$(f.telemetry,{ulid:J,modelId:f.modelId,provider:f.providerId,...X});E8(f.telemetry,{event:"started",ulid:J,durationMs:0,parentId:W.parentAgentId,agentId:W.subAgentId,...X}),$.invokeBackendOptional("handleSubAgentStart",J,W)},onSubAgentEnd:(W)=>{let j=$.getSession(J)?.runtime.teamRuntime,X=$.subAgentStarts.get(W.subAgentId),H=X?Date.now()-X.startedAt:0,Y=W.result?.text?W.result.text.split(`
695
+ `).length:0;E8(f.telemetry,{event:"ended",ulid:J,durationMs:H,outputLines:Y,errorMessage:W.error?String(W.error):void 0,agentId:W.subAgentId,parentId:W.parentAgentId,...V$({agentId:W.subAgentId,conversationId:W.conversationId,parentAgentId:W.parentAgentId,teamId:j?.getTeamId(),teamName:j?.getTeamName(),createdByAgentId:W.parentAgentId})}),$.subAgentStarts.delete(W.subAgentId),$.invokeBackendOptional("handleSubAgentEnd",J,W)}})}import{readFile as y_,stat as w_}from"node:fs/promises";var S_=20480000;async function FH($){let f=await w_($);if(!f.isFile())throw Error("Path is not a file");if(f.size>S_)throw Error("File is too large to read into context.");let J=await y_($,"utf8");if(J.includes("\x00"))throw Error("Cannot read binary file into context.");return J}var PH=5000;function O8($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function m_($){if(!$||typeof $!=="object"||Array.isArray($))return;let f=$,J=O8(f.inputTokens),Q=O8(f.outputTokens),Z=O8(f.cacheReadTokens),W=O8(f.cacheWriteTokens),j=O8(f.totalCost);if(J===void 0||Q===void 0||Z===void 0||W===void 0||j===void 0)return;return{inputTokens:J,outputTokens:Q,cacheReadTokens:Z,cacheWriteTokens:W,totalCost:j}}function g_($,f){return{inputTokens:Math.max($.inputTokens,f.inputTokens),outputTokens:Math.max($.outputTokens,f.outputTokens),cacheReadTokens:Math.max($.cacheReadTokens,f.cacheReadTokens),cacheWriteTokens:Math.max($.cacheWriteTokens,f.cacheWriteTokens),totalCost:Math.max($.totalCost,f.totalCost)}}class l${runtimeAddress=void 0;pendingPrompts;sessionService;runtimeBuilder;createAgentInstance;toolExecutors;defaultCapabilities;defaultToolPolicies;providerSettingsManager;oauthTokenManager;defaultTelemetry;defaultFetch;events=new f8;sessions=new Map;usageBySession=new Map;aggregateUsageBySession=new Map;subAgentStarts=new Map;pendingPromptsController;eventBridge;sessionVersioning=new j2;constructor($){let f=C_();if(f)x_(f);let J=U1($.distinctId);this.sessionService=$.sessionService,this.runtimeBuilder=$.runtimeBuilder??new x6,this.createAgentInstance=$.createAgent??((Q)=>new T$(Q)),this.defaultCapabilities=P0($.capabilities),this.toolExecutors=this.defaultCapabilities?.toolExecutors,this.defaultToolPolicies=$.toolPolicies,this.providerSettingsManager=$.providerSettingsManager??new d$,this.oauthTokenManager=$.oauthTokenManager??new t9({providerSettingsManager:this.providerSettingsManager,telemetry:$.telemetry}),this.defaultTelemetry=$.telemetry,this.defaultTelemetry?.setDistinctId(J),this.defaultFetch=$.fetch,this.pendingPromptsController=new s9({getSession:(Q)=>this.sessions.get(Q),emit:(Q)=>this.emit(Q),send:(Q)=>this.runTurn(Q)}),this.pendingPrompts={list:async(Q)=>this.pendingPromptsController.list(Q.sessionId),update:async(Q)=>this.pendingPromptsController.update(Q),delete:async(Q)=>this.pendingPromptsController.delete(Q)},this.eventBridge=new e9({getSession:(Q)=>this.sessions.get(Q),usageBySession:this.usageBySession,aggregateUsageBySession:this.aggregateUsageBySession,emit:(Q)=>this.emit(Q),persistMessages:(Q,Z,W)=>{this.invoke("persistSessionMessages",Q,Z,W)},enqueuePendingPrompt:(Q,Z)=>this.pendingPromptsController.enqueue(Q,Z),invokeBackendOptional:(Q,...Z)=>this.invokeOptional(Q,...Z)})}async startSession($){let f=$.source??F0.CLI,J=n(),Q=$.config.sessionId?.trim()??"",Z=Q||b_(),W=$,j=W.initialMessages??[],X=j.length>0?L6(j):B0(),H=await this.invokeOptionalValue("ensureSessionsDir")??"";if(!H)throw Error("session service method not available: ensureSessionsDir");let Y=Q7(H,Z),V=Q7(Y,`${Z}.messages.json`),A=Q7(Y,`${Z}.json`),B=v$($.config),G=_0.parse({version:1,session_id:Z,source:f,pid:process.pid,started_at:J,status:"running",interactive:$.interactive===!0,provider:W.config.providerId,model:W.config.modelId,cwd:W.config.cwd,workspace_root:B,team_name:W.config.teamName,enable_tools:W.config.enableTools,enable_spawn:W.config.enableSpawnAgent,enable_teams:W.config.enableAgentTeams,prompt:W.prompt?.trim()||void 0,messages_path:V}),K;if(Q.length>0&&j.length>0&&!W.prompt?.trim()){let h=await this.invokeOptionalValue("readSessionManifest",Z);if(h)G=h,K={manifestPath:A,messagesPath:h.messages_path||V,manifest:h}}let F=await this.seedAggregateUsageFromArtifacts({initialUsage:X,sessionDir:Y,rootMessagesPath:K?.messagesPath??V,manifest:G});this.usageBySession.set(Z,X),this.aggregateUsageBySession.set(Z,F);let P=P0(this.defaultCapabilities,$.capabilities),U=P?.toolExecutors??this.toolExecutors,z=$.localRuntime,_=z?.extensionContext?.logger??z?.logger,R=z?.extensionContext?.automation,L;L=await hX({input:W,localRuntime:$.localRuntime,sessionId:Z,providerSettingsManager:this.providerSettingsManager,defaultTelemetry:this.defaultTelemetry,defaultCapabilities:P,defaultToolPolicies:this.defaultToolPolicies,defaultFetch:this.defaultFetch,onPluginEvent:(h)=>{if(h.name==="plugin_log"){this.eventBridge.handlePluginLog(Z,h.payload,_);return}this.eventBridge.handlePluginEvent(Z,h,R)},onTeamEvent:(h)=>{this.eventBridge.handleTeamEvent(Z,h),L.config.onTeamEvent?.(h)},createSpawnTool:()=>J7({getSession:(h)=>this.sessions.get(h),subAgentStarts:this.subAgentStarts,onAgentEvent:(h,l,M0)=>this.eventBridge.dispatchAgentEvent(h,l,M0),invokeBackendOptional:(h,...l)=>this.invokeOptional(h,...l)},L.config,Z,U),readSessionMetadata:async()=>(await this.getSession(Z))?.metadata,writeSessionMetadata:async(h)=>{await this.persistSessionMetadata(Z,()=>h)}});let N=await this.runtimeBuilder.build(L.runtimeBuilderInput),M=L.config,o=L.providerConfig;if(N.teamRuntime&&!M.teamName?.trim())M.teamName=N.teamRuntime.getTeamName();let e=[...N.tools,...M.extraTools??[]],a=N.extensions??L.extensions,v={sessionId:Z,providerId:o.providerId,modelId:o.modelId,apiKey:o.apiKey,baseUrl:o.baseUrl,headers:o.headers,knownModels:o.knownModels,providerConfig:o,thinking:M.thinking,reasoningEffort:M.reasoningEffort??o.reasoningEffort,systemPrompt:M.systemPrompt,maxIterations:M.maxIterations,execution:M.execution,prepareTurn:T9(M),tools:e,hooks:L.hooks,extensions:a,hookErrorMode:M.hookErrorMode,initialMessages:L.effectiveInput.initialMessages,userFileContentLoader:FH,toolPolicies:L.toolPolicies,requestToolApproval:L.requestToolApproval?async(h)=>{let l=L.requestToolApproval,M0=this.sessions.get(Z);if(M0)await this.markTurnPending(M0);try{if(!l)return{approved:!1,reason:"Tool approval callback is not configured."};return await l(h)}finally{let L0=this.sessions.get(Z);if(L0?.status==="pending")await this.markTurnRunning(L0)}}:void 0,telemetry:M.telemetry,onConsecutiveMistakeLimitReached:M.onConsecutiveMistakeLimitReached,completionPolicy:N.completionPolicy,consumePendingUserMessage:()=>{let h=this.pendingPromptsController.consumeSteer(Z);return h?B8(h.prompt,h.mode??M.mode):void 0},logger:N.logger??M.logger,extensionContext:M.extensionContext,onEvent:(h)=>this.eventBridge.dispatchAgentEvent(Z,M,h)};v.hooks={...v.hooks,onEvent:async(h)=>{if(await L.hooks?.onEvent?.(h),h.type!=="assistant-message")return;let l=this.sessions.get(Z);if(!l)return;let M0=l.agent.getMessages();try{await this.invoke("persistSessionMessages",Z,M0,M.systemPrompt)}catch(L0){M.logger?.error?.("Failed to persist session messages after assistant response",{sessionId:Z,error:L0}),z1(M.telemetry,{component:"core",operation:"session.persist_messages_after_assistant_response",error:L0,severity:"warn",handled:!0,context:{sessionId:Z,providerId:M.providerId,modelId:M.modelId}})}}};let V0=this.createAgentInstance(v);if(v.onEvent)V0.subscribeEvents(v.onEvent);N.registerLeadAgent?.(V0);let B$=V$({agentId:V0.getAgentId(),conversationId:V0.getConversationId(),teamId:N.teamRuntime?.getTeamId(),teamName:N.teamRuntime?.getTeamName(),teamRole:N.teamRuntime?"lead":void 0});if(CX(M,Z,Q.length>0,B,B$),B$)a$(M.telemetry,{ulid:Z,modelId:M.modelId,provider:M.providerId,...B$});if(N.teamRuntime)_f(M.telemetry,{ulid:Z,teamId:N.teamRuntime.getTeamId(),teamName:N.teamRuntime.getTeamName(),leadAgentId:V0.getAgentId(),restoredFromPersistence:N.teamRestoredFromPersistence===!0});let u={sessionId:Z,config:M,sessionMetadata:W.sessionMetadata,...K?{artifacts:K}:{},source:f,startedAt:K?.manifest.started_at??J,updatedAt:K?.manifest.ended_at??K?.manifest.started_at??J,pendingPrompt:G.prompt,runtime:N,agent:V0,started:!1,status:K?.manifest.status??"running",aborting:!1,interactive:$.interactive===!0,persistedMessages:j,activeTeamRunIds:new Set,pendingTeamRunUpdates:[],teamRunWaiters:[],pendingPrompts:[],drainingPendingPrompts:!1,pluginSandboxShutdown:L.pluginSandboxShutdown,submitAndExitObserved:!1,lastInteractiveTurnFinishReason:void 0};if(this.sessions.set(Z,u),this.emitStatus(Z,"running"),j.length>0&&!K){if(await this.ensureSessionPersisted(u),await this.invoke("persistSessionMessages",u.sessionId,j,u.config.systemPrompt),!W.prompt?.trim())await this.updateStatus(u,"completed",0)}let s0;try{if(W.prompt?.trim())if(s0=await this.executeTurn(u,{prompt:W.prompt,userImages:W.userImages,userFiles:W.userFiles}),!u.interactive)await this.finalizeSingleRun(u,s0.finishReason);else await this.completeInteractiveTurn(u,s0.finishReason)}catch(h){if(u.interactive&&u.aborting)s0=await this.completeAbortedInteractiveTurn(u);else throw z1(u.config.telemetry,{component:"core",operation:"session.start",error:h,severity:"error",handled:!1,context:{sessionId:u.sessionId,providerId:u.config.providerId,modelId:u.config.modelId}}),await this.failSession(u),h}return{sessionId:Z,manifest:G,manifestPath:A,messagesPath:V,result:s0}}async restoreSession($){return this.sessionVersioning.restoreCheckpoint({...$,getSession:(f)=>this.getSession(f),readMessages:(f)=>this.readSessionMessages(f),buildStartInput:(f,J)=>{let Q=f.restoredCheckpointMetadata?{...J.sessionMetadata??{},checkpoint:f.restoredCheckpointMetadata}:J.sessionMetadata;return{...J,...Q?{sessionMetadata:Q}:{},initialMessages:f.initialMessages}},startSession:(f)=>this.startSession(f),getStartedSessionId:(f)=>f.sessionId,readRestoredSession:(f)=>this.getSession(f)})}async runTurn($){let f=this.getSessionOrThrow($.sessionId),J=f.agent.canStartRun(),Q=$.delivery??(f.interactive&&!J?"queue":void 0);if(f.config.telemetry?.capture({event:"session.input_sent",properties:{sessionId:$.sessionId,promptLength:$.prompt.length,userImageCount:$.userImages?.length??0,userFileCount:$.userFiles?.length??0,delivery:Q??"immediate"}}),Q==="queue"||Q==="steer"){this.pendingPromptsController.enqueue($.sessionId,{prompt:$.prompt,mode:$.mode,delivery:Q,userImages:$.userImages,userFiles:$.userFiles});return}try{let Z=await this.executeTurn(f,{prompt:$.prompt,mode:$.mode,userImages:$.userImages,userFiles:$.userFiles});if(!f.interactive)await this.finalizeSingleRun(f,Z.finishReason);else await this.completeInteractiveTurn(f,Z.finishReason);if(Z.finishReason==="error"||Z.finishReason==="aborted")return Z;return queueMicrotask(()=>{this.pendingPromptsController.drain($.sessionId)}),Z}catch(Z){if(f.interactive&&f.aborting)return await this.completeAbortedInteractiveTurn(f);throw z1(f.config.telemetry,{component:"core",operation:"session.submit",error:Z,severity:"error",handled:!1,context:{sessionId:f.sessionId,providerId:f.config.providerId,modelId:f.config.modelId}}),await this.failSession(f),Z}}async getAccumulatedUsage($){let f=x5(this.usageBySession.get($)),J=x5(this.aggregateUsageBySession.get($));return f||J?{usage:f,aggregateUsage:J}:void 0}async abort($,f){let J=this.sessions.get($);if(!J)return;J.config.telemetry?.capture({event:"session.aborted",properties:{sessionId:$}}),J.aborting=!0,this.pendingPromptsController.clearAborted(J),J.agent.abort(f)}async stopSession($){let f=this.sessions.get($);if(!f)return;if(f.config.telemetry?.capture({event:"session.stopped",properties:{sessionId:$}}),f.interactive&&!f0(f.status)){await this.releaseSessionRuntime(f,"session_stop");return}if(f.interactive&&f.agent.canStartRun()){await this.shutdownSession(f,{status:this.resolveInteractiveStopStatus(f),exitCode:this.resolveInteractiveStopExitCode(f),shutdownReason:"session_stop",endReason:"stopped"});return}f.aborting=!0,f.agent.abort(Error("session_stop")),await this.shutdownSession(f,{status:"cancelled",exitCode:0,shutdownReason:"session_stop",endReason:"stopped"})}async dispose($="session_manager_dispose"){let f=[...this.sessions.values()];if(f.length===0)return;await Promise.allSettled(f.map((J)=>J.interactive&&!f0(J.status)?this.releaseSessionRuntime(J,$):J.interactive&&J.agent.canStartRun()?this.shutdownSession(J,{status:this.resolveInteractiveStopStatus(J),exitCode:this.resolveInteractiveStopExitCode(J),shutdownReason:$,endReason:"disposed"}):this.shutdownSession(J,{status:"cancelled",exitCode:0,shutdownReason:$,endReason:"disposed"}))),this.usageBySession.clear(),this.aggregateUsageBySession.clear()}async getSession($){let f=this.sessions.get($);if(f)return $7(f);let J=$.trim();if(!J)return;let Q=await this.getRow(J);if(Q)return e2(Q);let Z=await this.readManifest(J);return Z?v5(Z):void 0}async listSessions($=200){let J=(await this.listRows($)).map(e2),Q=new Set(J.map((Z)=>Z.sessionId));for(let Z of this.sessions.values()){if(Q.has(Z.sessionId))continue;J.unshift($7(Z))}return J.slice(0,$)}async deleteSession($){if(this.sessions.has($))await this.stopSession($);let f=await this.invoke("deleteSession",$);if(f.deleted)this.usageBySession.delete($),this.aggregateUsageBySession.delete($);return f.deleted}async updateSession($,f){return{updated:(await this.invokeOptionalValue("updateSession",{sessionId:$,prompt:f.prompt,metadata:f.metadata,title:f.title}))?.updated===!0}}async readSessionMessages($){let f=$.trim();if(!f)return[];let J=await this.getRow(f);if(J?.messagesPath)return h$(J.messagesPath);let Q=await this.readManifest(f);return h$(Q?.messages_path)}async dispatchHookEvent($){await lW($,{queueSpawnRequest:(f)=>this.invokeOptional("queueSpawnRequest",f),upsertSubagentSessionFromHook:(f)=>this.invokeOptionalValue("upsertSubagentSessionFromHook",f),appendSubagentHookAudit:(f,J)=>this.invokeOptional("appendSubagentHookAudit",f,J),applySubagentStatus:(f,J)=>this.invokeOptional("applySubagentStatus",f,J)})}subscribe($,f){return this.events.subscribe($,f)}async updateSessionModel($,f){let J=this.getSessionOrThrow($);J.config.modelId=f,J.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({modelId:f}),J.agent.updateConnection({modelId:f})}handlePluginEvent($,f,J){return this.eventBridge.handlePluginEvent($,f,J)}async executeTurn($,f){let J=await this.prepareTurnInput($,f),Q=J.prompt.trim();if(!Q)throw Error("prompt cannot be empty");if(!$.artifacts&&!$.pendingPrompt)$.pendingPrompt=Q;await this.ensureSessionPersisted($),await this.syncOAuthCredentials($),await this.markTurnRunning($);let Z=await this.executeAgentTurn($,Q,J.userImages,J.userFiles);while(V9($,Z.finishReason)){let W=await A9($);if(W.length===0)break;let j=B9($,W);Z=await this.executeAgentTurn($,j)}return Z}async completeInteractiveTurn($,f){if(A8($))return;$.lastInteractiveTurnFinishReason=f,await this.markTurnIdle($),$.aborting=!1}resolveInteractiveStopStatus($){let f=$.lastInteractiveTurnFinishReason;if(!f)return"cancelled";switch(f){case"completed":return"completed";case"error":return"failed";case"aborted":case"max_iterations":case"mistake_limit":return"cancelled"}return f}resolveInteractiveStopExitCode($){return $.lastInteractiveTurnFinishReason==="error"?1:0}async completeAbortedInteractiveTurn($){let f=new Date,J=$.agent.getMessages(),Q=B0();return $.persistedMessages=J,$.started=$.started||J.length>0,this.eventBridge.dispatchAgentEvent($.sessionId,$.config,{type:"done",reason:"aborted",text:"",iterations:0,usage:Q}),await this.completeInteractiveTurn($,"aborted"),{text:"",usage:Q,messages:J,toolCalls:[],iterations:0,finishReason:"aborted",model:{id:$.config.modelId,provider:$.config.providerId},startedAt:f,endedAt:f,durationMs:0}}async executeAgentTurn($,f,J,Q){let Z=$.started||$.agent.getMessages().length>0,W=$.persistedMessages??$.agent.getMessages(),j=this.usageBySession.get($.sessionId)??B0(),X=this.aggregateUsageBySession.get($.sessionId)??j;$.turnUsageBaseline=j,$.turnAggregateUsageBaseline=X,$.turnPrimaryUsage=B0(),$.turnUsageByAgent=new Map,Pf($.config.telemetry,$.sessionId,$.config.mode),A2($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,model:$.config.modelId,source:"user",mode:$.config.mode,...this.getSessionAgentTelemetryIdentity($)});try{let H=Z?()=>$.agent.continue(f,J,Q):()=>$.agent.run(f,J,Q),Y=await this.runWithAuthRetry($,H,W);$.started=!0;let V=J6(Y.messages,Y,W);$.persistedMessages=V;let A=R6($.turnUsageByAgent?.values()??[]),B=H0(j,Y.usage),G=H0(H0(B0(),Y.usage),A),K=H0(X,G);return this.usageBySession.set($.sessionId,B),this.aggregateUsageBySession.set($.sessionId,K),await this.persistSessionMetadata($.sessionId,(D)=>({...D??{},totalCost:B.totalCost,aggregatedAgentsCost:K.totalCost,usage:B,aggregateUsage:K})),await this.invoke("persistSessionMessages",$.sessionId,V,$.config.systemPrompt),this.observeTaskCompletionTool($,Y),Y}catch(H){throw z1($.config.telemetry,{component:"core",operation:"session.turn",error:H,severity:"error",handled:!1,context:{sessionId:$.sessionId,providerId:$.config.providerId,modelId:$.config.modelId}}),await this.invoke("persistSessionMessages",$.sessionId,$.agent.getMessages(),$.config.systemPrompt),H}finally{$.turnUsageBaseline=void 0,$.turnAggregateUsageBaseline=void 0,$.turnPrimaryUsage=void 0,$.turnUsageByAgent=void 0}}observeTaskCompletionTool($,f){if($.submitAndExitObserved)return;if(!f.toolCalls.some((Q)=>Q.name===W0.SUBMIT_AND_EXIT&&Q.error===void 0))return;$.submitAndExitObserved=!0,h8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"submit_and_exit",...this.getSessionAgentTelemetryIdentity($)})}async prepareTurnInput($,f){let J=v$($.config),Q=I_(f.prompt).trim();if(!Q)return{prompt:"",userImages:f.userImages,userFiles:this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles)};let Z=await D4(Q,J);EX($.config.telemetry,Z);let W=B8(Z.prompt,f.mode??$.config.mode),j=this.resolveAbsoluteFilePaths($.config.cwd,f.userFiles),X=this.resolveAbsoluteFilePaths(J,Z.matchedFiles),H=Array.from(new Set([...j,...X]));return{prompt:W,userImages:f.userImages,userFiles:H.length>0?H:void 0}}async ensureSessionPersisted($){if($.artifacts)return;let f=v$($.config);$.artifacts=await this.invoke("createRootSessionWithArtifacts",{sessionId:$.sessionId,source:$.source,pid:process.pid,interactive:$.interactive,provider:$.config.providerId,model:$.config.modelId,cwd:$.config.cwd,workspaceRoot:f,teamName:$.config.teamName,enableTools:$.config.enableTools,enableSpawn:$.config.enableSpawnAgent,enableTeams:$.config.enableAgentTeams,prompt:$.pendingPrompt,metadata:$.sessionMetadata,startedAt:$.startedAt})}async markTurnRunning($){if($.status==="running")return;await this.updateStatus($,"running",null)}async markTurnPending($){if($.status==="pending")return;await this.updateStatus($,"pending",null)}async markTurnIdle($){if($.status==="idle")return;await this.updateStatus($,"idle",null)}async persistSessionMetadata($,f){let J=this.sessions.get($),Q=await this.invokeOptionalValue("readSessionManifest",$)??J?.artifacts?.manifest,Z=f(Q?.metadata);if(!J?.artifacts)return;if((await this.invokeOptionalValue("updateSession",{sessionId:$,metadata:Z}))?.updated===!1)return;J.sessionMetadata=Z,J.artifacts.manifest.metadata=Z}async finalizeSingleRun($,f){if(A8($))return;let J=f==="aborted"||$.aborting,Q=f==="error";await this.shutdownSession($,{status:J?"cancelled":Q?"failed":"completed",exitCode:Q?1:0,shutdownReason:Q?"session_error":"session_complete",endReason:f})}async failSession($){await this.shutdownSession($,{status:"failed",exitCode:1,shutdownReason:"session_error",endReason:"error"})}async shutdownSession($,f){if(f.status==="completed"&&!$.submitAndExitObserved)h8($.config.telemetry,{ulid:$.sessionId,provider:$.config.providerId,modelId:$.config.modelId,mode:$.config.mode,durationMs:Date.now()-Date.parse($.startedAt),source:"shutdown",...this.getSessionAgentTelemetryIdentity($)});P6($);let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session shutdown cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),z1($.config.telemetry,{component:"core",operation:"session.shutdown_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,status:f.status,shutdownReason:f.shutdownReason,providerId:$.config.providerId,modelId:$.config.modelId}})};if($.artifacts){try{await this.updateStatus($,f.status,f.exitCode)}catch(Z){Q("update_status",Z)}try{await $.agent.shutdown(f.shutdownReason)}catch(Z){Q("agent_shutdown",Z)}}try{await Promise.resolve($.runtime.shutdown(f.shutdownReason))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),this.emit({type:"ended",payload:{sessionId:$.sessionId,reason:f.endReason,ts:Date.now()}}),J.length>0&&f.status==="failed")throw J[0]}async releaseSessionRuntime($,f){let J=[],Q=(Z,W)=>{J.push(W),$.config.logger?.log("Session runtime cleanup failed",{sessionId:$.sessionId,stage:Z,error:W,severity:"warn"}),z1($.config.telemetry,{component:"core",operation:"session.runtime_cleanup",error:W,severity:"warn",handled:!0,context:{sessionId:$.sessionId,stage:Z,reason:f,providerId:$.config.providerId,modelId:$.config.modelId}})};try{await $.agent.shutdown(f)}catch(Z){Q("agent_shutdown",Z)}try{await Promise.resolve($.runtime.shutdown(f))}catch(Z){Q("runtime_shutdown",Z)}try{await $.pluginSandboxShutdown?.()}catch(Z){Q("plugin_sandbox_shutdown",Z)}if(this.sessions.delete($.sessionId),J.length>0)throw J[0]}async updateStatus($,f,J){if(!$.artifacts)return;let Q=await this.invoke("updateSessionStatus",$.sessionId,f,J);if(!Q.updated)return;let Z=await this.invokeOptionalValue("readSessionManifest",$.sessionId)??$.artifacts.manifest;if(Z.status=f,f0(f))delete Z.ended_at,Z.exit_code=null;else Z.ended_at=Q.endedAt??n(),Z.exit_code=typeof J==="number"?J:null;$.artifacts.manifest=Z,$.status=f,$.updatedAt=Q.endedAt??n(),$.endedAt=f0(f)?null:Z.ended_at,$.exitCode=Z.exit_code,await this.invoke("writeSessionManifest",$.artifacts.manifestPath,Z),this.emitStatus($.sessionId,f)}async runWithAuthRetry($,f,J){try{return await f()}catch(Q){if(!k_(Q,$.config.providerId))throw Q;return await this.syncOAuthCredentials($,{forceRefresh:!0}),$.agent.restore(J),f()}}async syncOAuthCredentials($,f){let J=null;try{J=await this.oauthTokenManager.resolveProviderApiKey({providerId:$.config.providerId,forceRefresh:f?.forceRefresh})}catch(Q){if(Q instanceof m6)throw Error(`${Q.providerId} requires re-authentication.`);throw Q}if(!J?.apiKey||$.config.apiKey===J.apiKey)return;$.config.apiKey=J.apiKey,$.agent.updateConnection({apiKey:J.apiKey}),$.runtime.delegatedAgentConfigProvider?.updateConnectionDefaults({apiKey:J.apiKey}),$.runtime.teamRuntime?.updateTeammateConnections({apiKey:J.apiKey})}getSessionOrThrow($){let f=this.sessions.get($);if(!f){let J=Error(`session not found: ${$}`);throw z1(this.defaultTelemetry,{component:"core",operation:"session.active_lookup",error:J,severity:"warn",handled:!0,context:{sessionId:$,activeSessionCount:this.sessions.size}}),J}return f}resolveAbsoluteFilePaths($,f){if(!f||f.length===0)return[];let J=f.map((Q)=>Q.trim()).filter((Q)=>Q.length>0).map((Q)=>E_(Q)?Q:Z7($,Q));return Array.from(new Set(J))}getSessionAgentTelemetryIdentity($){return V$({agentId:$.agent.getAgentId(),conversationId:$.agent.getConversationId(),teamId:$.runtime.teamRuntime?.getTeamId(),teamName:$.runtime.teamRuntime?.getTeamName(),teamRole:$.runtime.teamRuntime?"lead":void 0})}async seedAggregateUsageFromArtifacts($){let f=await this.summarizePersistedTeammateUsage($.sessionDir,$.rootMessagesPath,$.manifest.session_id),J=H0($.initialUsage,f);return this.withPersistedAggregateUsageFloor(J,$.manifest)}async summarizePersistedTeammateUsage($,f,J){let Q=Z7(f),Z=`${J}.messages.json`,W;try{W=h_($)}catch{return B0()}let j=B0();for(let X of W){if(!X.endsWith(".messages.json"))continue;if(X===Z)continue;let H=Z7($,X);if(H===Q)continue;let Y=await h$(H);if(Y.length===0)continue;j=H0(j,L6(Y))}return j}withPersistedAggregateUsageFloor($,f){let J=m_(f.metadata?.aggregateUsage);if(J)return g_($,J);let Q=f.metadata?.aggregatedAgentsCost;if(typeof Q!=="number"||!Number.isFinite(Q)||Q<=$.totalCost)return $;return{...$,totalCost:Q}}emitStatus($,f){this.emitSessionSnapshot($),this.emit({type:"status",payload:{sessionId:$,status:f}})}async emitSessionSnapshot($){let f=await this.getSession($);if(!f)return;this.emit({type:"session_snapshot",payload:{sessionId:$,snapshot:b$({session:f,messages:await this.readSessionMessages($),usage:this.usageBySession.get($),aggregateUsage:this.aggregateUsageBySession.get($)})}})}emit($){this.events.emit($)}async listRows($){return this.invoke("listSessions",Math.min(Math.max(1,Math.floor($)),PH))}async getRow($){let f=$.trim();if(!f)return;return(await this.listRows(PH)).find((Q)=>Q.sessionId===f)}async readManifest($){let f=$.trim();if(!f)return;return await this.invokeOptionalValue("readSessionManifest",f)}invoke($,...f){return BH(this.sessionService,$,...f)}invokeOptional($,...f){return GH(this.sessionService,$,...f)}invokeOptionalValue($,...f){return KH(this.sessionService,$,...f)}}function v_($){if($.backendMode)return $.backendMode;if(process.env.CLINE_VCR?.trim())return"local";let f=process.env.CLINE_SESSION_BACKEND_MODE?.trim().toLowerCase();if(f==="local"||f==="hub"||f==="remote")return f;return"auto"}var z8,_8;function u_($,f){if($!=="auto"&&$!=="hub")return;if(f.hub?.endpoint?.trim())return;Hj(f.hub?.workspaceRoot?.trim()||f.hub?.cwd?.trim()||process.cwd())}async function c_($){await $.reconcileDeadSessions?.().catch(()=>{})}function RH($){try{let f=new x$;return f.init(),new m$(f,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}catch(f){return $.telemetry?.capture({event:"session_backend_fallback",properties:{requestedBackend:"sqlite",fallbackBackend:"file"}}),DH($.telemetry,{component:"core",operation:"session_backend.sqlite_init",error:f,severity:"warn",handled:!0,context:{requestedBackend:"sqlite",fallbackBackend:"file"}}),new P9(void 0,{messagesArtifactUploader:$.messagesArtifactUploader,logger:$.logger})}}function UH($,f,J){return new l$({sessionService:J??$.sessionService??RH($),capabilities:$.capabilities,telemetry:$.telemetry,toolPolicies:$.toolPolicies,distinctId:f,fetch:$.fetch})}async function d_($){if(z8)return z8;if(_8)return await _8;return _8=(async()=>{return z8=RH($),await c_(z8),z8})().finally(()=>{_8=void 0}),await _8}async function v6($){let f=U1($.distinctId);$.telemetry?.setDistinctId(f);let J=v_($);if(u_(J,$),J==="remote"){let Q=$.remote?.endpoint?.trim();if(!Q)throw Error("Remote runtime mode requires `remote.endpoint` to be configured.");return $.logger?.log("Using remote runtime host",{endpoint:Q}),new H6({endpoint:Q,authToken:$.remote?.authToken,clientType:$.remote?.clientType,displayName:$.remote?.displayName,workspaceRoot:$.remote?.workspaceRoot,cwd:$.remote?.cwd,capabilities:$.capabilities})}if(J==="hub"){let Q=$.hub?.endpoint?.trim(),Z=Q||await W8({strategy:$.hub?.strategy??"require-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(!Z)throw Error("No compatible hub runtime is available.");return $.logger?.log("Using hub runtime host",{url:Z,explicitEndpoint:Q||void 0}),new P1({url:Z,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd})}if(J==="auto"){let Q=await s5({endpoint:$.hub?.endpoint,strategy:$.hub?.strategy??"prefer-hub",workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});if(Q){$.logger?.log("Using discovered local hub runtime host",{url:Q});let Z=new P1({url:Q,authToken:$.hub?.authToken,clientType:$.hub?.clientType,displayName:$.hub?.displayName,capabilities:$.capabilities,telemetry:$.telemetry},{workspaceRoot:$.hub?.workspaceRoot,cwd:$.hub?.cwd});try{return await Z.connect(),Z}catch(W){$.logger?.log("Falling back to local runtime host",{reason:"hub_connect_failed",severity:"warn",error:W}),DH($.telemetry,{component:"core",operation:"runtime_host.hub_connect",error:W,severity:"warn",handled:!0,context:{backendMode:"auto",fallbackBackend:"local"}})}}return $.logger?.log("Falling back to local runtime host",{reason:"compatible_hub_unavailable",severity:"warn"}),UH($,f)}return UH($,f)}class W7{clientName;runtimeAddress;automation;settings;pendingPrompts;host;prepare;capabilities;logger;telemetry;distinctId;automationService;activeSessionBootstraps=new Map;unsubscribeBootstrapCleanup;constructor($,f,J,Q,Z,W,j,X,H){this.clientName=f,this.runtimeAddress=J,this.host=$,this.prepare=Q,this.capabilities=Z,this.logger=W,this.telemetry=j,this.distinctId=X,this.settings=BW($),this.pendingPrompts=GW($),this.automation=new of(()=>{if(!this.automationService)throw Error("ClineCore automation is not enabled. Pass `automation: true` or automation options to ClineCore.create().");return this.automationService}),this.automationService=H?new t2({workspaceRoot:H.workspaceRoot??process.cwd(),specs:{cronSpecsDir:H.cronSpecsDir??H.cronDir,scope:qQ(H.cronScope),workspaceRoot:H.workspaceRoot},runtimeHandlers:yQ({host:$,getExtensionContext:()=>s8({automationService:this.automationService,automation:this.automation,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}),dbPath:H.dbPath,logger:H.logger,pollIntervalMs:H.pollIntervalMs,claimLeaseSeconds:H.claimLeaseSeconds,globalMaxConcurrency:H.globalMaxConcurrency,watcherDebounceMs:H.watcherDebounceMs}):void 0,this.unsubscribeBootstrapCleanup=this.host.subscribe((Y)=>{if(Y.type!=="ended")return;this.disposeSessionBootstrap(Y.payload.sessionId)})}static async create($={}){let f=P0($.capabilities),J=await v6({...$,capabilities:f}),Q=MQ($.automation),Z=new W7(J,$.clientName,J.runtimeAddress,$.prepare,f,$.logger,$.telemetry,$.distinctId,Q?{...Q,logger:$.logger}:void 0);if(Q&&Q.autoStart!==!1)await Z.automation.start();return Z}async disposeSessionBootstrap($){let f=this.activeSessionBootstraps.get($);if(!f)return;this.activeSessionBootstraps.delete($),await Promise.resolve(f.dispose?.())}async start($){let f=KW($),J=await this.prepare?.(f);try{let Q=J?await J.applyToStartSessionInput(f):f,Z=await this.host.startSession(Y5(Q,{defaultCapabilities:this.capabilities,withExtensionContext:(W)=>s8({automationService:this.automationService,automation:this.automation,context:W,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}));if(J)if(await this.host.getSession(Z.sessionId))this.activeSessionBootstraps.set(Z.sessionId,J);else await Promise.resolve(J.dispose?.());return FW({input:Q,sessionId:Z.sessionId,telemetry:this.telemetry,clientName:this.clientName,runtimeAddress:this.runtimeAddress}),Z}catch(Q){throw await Promise.resolve(J?.dispose?.()),Q}}send=(...$)=>this.host.runTurn(...$);getAccumulatedUsage=(...$)=>{return this.host.getAccumulatedUsage?.(...$)??Promise.resolve(void 0)};abort=(...$)=>this.host.abort(...$);stop=async($)=>{await this.host.stopSession($),await this.disposeSessionBootstrap($)};dispose=async(...$)=>{try{await this.automationService?.dispose(),await this.host.dispose(...$)}finally{this.unsubscribeBootstrapCleanup();let f=[...this.activeSessionBootstraps.keys()];await Promise.allSettled(f.map((J)=>this.disposeSessionBootstrap(J)))}};get=(...$)=>this.host.getSession(...$);listHistory=async($={})=>await u5(this.host,$);list=async($=200,f={})=>await this.listHistory({...f,limit:$});delete=async($)=>{let f=await this.host.deleteSession($);if(f)await this.disposeSessionBootstrap($);return f};update=(...$)=>this.host.updateSession(...$);readMessages=(...$)=>this.host.readSessionMessages(...$);async restore($){let f=$.start?Y5($.start,{defaultCapabilities:this.capabilities,withExtensionContext:(J)=>s8({automationService:this.automationService,automation:this.automation,context:J,clientName:this.clientName,distinctId:this.distinctId,logger:this.logger,telemetry:this.telemetry})}):void 0;return this.host.restoreSession({sessionId:$.sessionId,checkpointRunCount:$.checkpointRunCount,cwd:$.cwd,restore:$.restore,start:f})}ingestHookEvent=(...$)=>this.host.dispatchHookEvent(...$);subscribe($,f){return this.host.subscribe($,f)}updateSessionModel=(...$)=>{return this.host.updateSessionModel?.(...$)??Promise.resolve()}}import{HookEventNameSchema as OH,HookEventPayloadSchema as zH,parseHookEventPayload as c6,resolveHookSessionContext as t_}from"@cline/shared";import{z as _1}from"zod";import{spawn as l_}from"node:child_process";import{augmentNodeCommandForDebug as p_,withResolvedClineBuildEnv as r_}from"@cline/shared";function i_($){let f=$.trim();if(!f)return{};let Q=f.split(`
696
+ `).map((W)=>W.trim()).filter(Boolean).filter((W)=>W.startsWith("HOOK_CONTROL\t")).map((W)=>W.slice(13)),Z=Q.length>0?Q[Q.length-1]:f;try{return{parsedJson:JSON.parse(Z)}}catch(W){return{parseError:W instanceof Error?W.message:"Failed to parse subprocess stdout JSON"}}}function n_($,f){let J=$ instanceof Error?$:Error(String($)),Q=J,Z=f.join(" ");if(Q.code==="EACCES")return Error(`Failed to execute hook command "${Z}" (EACCES). Configure hooks with an explicit interpreter/command array (for example: ["bash", "/path/to/script"]) or make the script executable with a valid shebang.`);return Error(`Failed to execute hook command "${Z}": ${J.message}`)}async function a_($,f){let J=$.stdin;if(!J)throw Error("runSubprocessEvent failed to create stdin pipe");await new Promise((Q,Z)=>{let W=(j)=>{J.off("error",W);let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j)};J.once("error",W),J.end(f,(j)=>{if(J.off("error",W),j){let X=j.code;if(X==="EPIPE"||X==="ERR_STREAM_DESTROYED"){Q();return}Z(j);return}Q()})})}async function u6($,f){let J=p_(f.command,{env:f.env,debugRole:"hook"});if(!Array.isArray(J)||J.length===0)throw Error("runSubprocessEvent requires a non-empty command");let Q=!!f.detached,Z=l_(J[0],J.slice(1),{cwd:f.cwd,env:r_(f.env),stdio:Q?["pipe","ignore","ignore"]:["pipe","pipe","pipe"],detached:Q}),W=new Promise((B)=>{Z.once("spawn",()=>{try{f.onSpawn?.({command:J,pid:Z.pid??void 0,detached:Q})}catch{}B()})}),j=new Promise((B,G)=>{Z.once("error",(K)=>{G(n_(K,J))})});if(await a_(Z,JSON.stringify($)),Q){await Promise.race([W,j]),Z.unref();return}if(!Z.stdout||!Z.stderr)throw Error("runSubprocessEvent failed to create stdout/stderr pipes");let X="",H="",Y=!1,V;Z.stdout.on("data",(B)=>{X+=B.toString()}),Z.stderr.on("data",(B)=>{H+=B.toString()});let A=new Promise((B)=>{if((f.timeoutMs??0)>0)V=setTimeout(()=>{Y=!0,Z.kill("SIGKILL")},f.timeoutMs);Z.once("close",(G)=>{if(V)clearTimeout(V);let{parsedJson:K,parseError:D}=i_(X);B({exitCode:G,stdout:X,stderr:H,parsedJson:K,parseError:D,timedOut:Y})})});return await Promise.race([A,j])}var s_=_1.object({contextModification:_1.string().optional(),cancel:_1.boolean().optional(),review:_1.boolean().optional(),errorMessage:_1.string().optional(),context:_1.string().optional(),overrideInput:_1.unknown().optional()}).passthrough();var o_=["agent","hook"];async function d6($,f={}){let J=f.command??o_;return await u6($,{command:J,cwd:f.cwd,env:f.env,detached:f.detached,timeoutMs:f.timeoutMs,onSpawn:f.onSpawn})}function _H($){return $ instanceof Error?$:Error(String($))}function e_($){if(!$||typeof $!=="object")return;let f=s_.safeParse($);if(!f.success)return;let J=f.data;if(!(("cancel"in J)||("review"in J)||("context"in J)||("contextModification"in J)||("overrideInput"in J)||("errorMessage"in J)))return;let Z=typeof J.context==="string"?J.context:typeof J.contextModification==="string"?J.contextModification:typeof J.errorMessage==="string"&&J.errorMessage.length>0?J.errorMessage:void 0;return{cancel:typeof J.cancel==="boolean"?J.cancel:void 0,review:typeof J.review==="boolean"?J.review:void 0,context:Z,overrideInput:Object.hasOwn(J,"overrideInput")?J.overrideInput:void 0}}function LH($){if(!$||typeof $!=="object")return{};let f={};for(let[J,Q]of Object.entries($))if(typeof Q==="string")f[J]=Q;else f[J]=JSON.stringify(Q);return f}function A$($,f,J){let Q=J.env??process.env,Z=Q.CLINE_USER_ID?.trim()||Q.USER?.trim()||"unknown",W=J.cwd||process.cwd();return{clineVersion:Q.CLINE_VERSION?.trim()||"",hookName:$,timestamp:new Date().toISOString(),taskId:f.conversationId,sessionContext:t_(J.sessionContext,{hookName:$,conversationId:f.conversationId,agentId:f.agentId,parentAgentId:f.parentAgentId}),workspaceRoots:W?[W]:[],workspaceInfo:J.workspaceInfo,userId:Z,agent_id:f.agentId,parent_agent_id:f.parentAgentId}}function $N($){return{name:$.name,message:$.message,stack:$.stack}}function fN($){let f=String($??"").toLowerCase();return f.includes("cancel")||f.includes("abort")||f.includes("interrupt")}function JN($){return{agentId:$.snapshot.agentId,conversationId:$.snapshot.conversationId??$.snapshot.runId??$.snapshot.agentId,parentAgentId:$.snapshot.parentAgentId??null}}function QN($){return $.filter((f)=>f.type==="text"&&typeof f.text==="string").map((f)=>f.text).join("")}function ZN($){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 WN($){if(!$)return;let f={};if($.cancel===!0)f.stop=!0;if($.overrideInput!==void 0)f.input=$.overrideInput;return Object.keys(f).length>0?f:void 0}async function N1($,f){try{let J=await d6($,{command:f.command,cwd:f.cwd,env:f.env,detached:!0,onSpawn:f.onSpawn});f.onDispatch?.({payload:$,result:J,detached:!0})}catch(J){f.onDispatchError?.(_H(J),$)}}function NH($={}){return{hooks:{beforeRun:async(X)=>{let H=JN(X);if(($.env??process.env).CLINE_HOOK_AGENT_RESUME==="1"){let V={...A$("agent_resume",H,$),hookName:"agent_resume",taskResume:{taskMetadata:{},previousState:{}}};await N1(V,$)}else{let V={...A$("agent_start",H,$),hookName:"agent_start",taskStart:{taskMetadata:{}}};await N1(V,$)}return},beforeTool:async(X)=>{let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...A$("tool_call",H,$),hookName:"tool_call",iteration:X.snapshot.iteration,tool_call:{id:X.toolCall.toolCallId,name:X.toolCall.toolName,input:X.input},preToolUse:{toolName:X.toolCall.toolName,parameters:LH(X.input)}};try{let V=await d6(Y,{command:$.command,cwd:$.cwd,env:$.env,detached:!1,timeoutMs:$.timeoutMs,onSpawn:$.onSpawn});if($.onDispatch?.({payload:Y,result:V,detached:!1}),V?.timedOut)throw Error("tool_call hook command timed out");if(V?.parseError)throw Error(`tool_call hook produced invalid control JSON: ${V.parseError}`);return WN(e_(V?.parsedJson))}catch(V){$.onDispatchError?.(_H(V),Y);return}},afterTool:async(X)=>{let H=ZN(X),Y={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},V={...A$("tool_result",Y,$),hookName:"tool_result",iteration:X.snapshot.iteration,tool_result:H,postToolUse:{toolName:H.name,parameters:LH(H.input),result:typeof H.output==="string"?H.output:JSON.stringify(H.output),success:!H.error,executionTimeMs:H.durationMs}};await N1(V,$);return},afterRun:async({snapshot:X,result:H})=>{let Y={agentId:X.agentId,conversationId:X.conversationId??X.runId??X.agentId,parentAgentId:X.parentAgentId??null};if(H.status==="completed"){let B={...A$("agent_end",Y,$),hookName:"agent_end",iteration:H.iterations,turn:{outputText:H.outputText,status:H.status},taskComplete:{taskMetadata:{}}};await N1(B,$);return}let V=H.status==="aborted"||fN(H.error?.message)?"agent_abort":"agent_error",A=V==="agent_error"?{...A$(V,Y,$),hookName:V,iteration:H.iterations,error:$N(H.error??Error("Agent run failed")),taskCancel:{taskMetadata:{}}}:{...A$(V,Y,$),hookName:V,reason:H.error?.message,taskCancel:{taskMetadata:{}}};await N1(A,$)},onEvent:async(X)=>{if(X.type!=="message-added"||X.message.role!=="user")return;let H={agentId:X.snapshot.agentId,conversationId:X.snapshot.conversationId??X.snapshot.runId??X.snapshot.agentId,parentAgentId:X.snapshot.parentAgentId??null},Y={...A$("prompt_submit",H,$),hookName:"prompt_submit",userPromptSubmit:{prompt:QN(X.message.content),attachments:[]}};await N1(Y,$)}},shutdown:async({agentId:X,conversationId:H,parentAgentId:Y,reason:V})=>{let A={...A$("session_shutdown",{agentId:X,conversationId:H,parentAgentId:Y},$),hookName:"session_shutdown",reason:V};await N1(A,$)}}}import{createSessionId as jN}from"@cline/shared";function m0($,f){return{version:$.version,requestId:$.requestId,ok:!0,payload:f}}function TH($,f,J){return{version:$.version,requestId:$.requestId??jN("hubreq_"),ok:!1,error:{code:f,message:J}}}class l6{schedules;constructor($){this.schedules=$}async handleCommand($){try{switch($.command){case"schedule.create":return m0($,{schedule:this.schedules.createSchedule(this.toCreateInput($.payload??{}))});case"schedule.list":return m0($,{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 m0($,{schedule:this.schedules.getSchedule(String($.payload?.scheduleId??""))});case"schedule.update":return m0($,{schedule:this.schedules.updateSchedule(String($.payload?.scheduleId??""),this.toUpdateInput($.payload??{}))});case"schedule.delete":return m0($,{deleted:this.schedules.deleteSchedule(String($.payload?.scheduleId??""))});case"schedule.enable":return m0($,{schedule:this.schedules.resumeSchedule(String($.payload?.scheduleId??""))});case"schedule.disable":return m0($,{schedule:this.schedules.pauseSchedule(String($.payload?.scheduleId??""))});case"schedule.trigger":return m0($,{execution:await this.schedules.triggerScheduleNow(String($.payload?.scheduleId??""))});case"schedule.list_executions":return m0($,{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 m0($,{stats:this.schedules.getScheduleStats(String($.payload?.scheduleId??""))});case"schedule.active":return m0($,{executions:this.schedules.getActiveExecutions()});case"schedule.upcoming":return m0($,{runs:this.schedules.getUpcomingRuns(typeof $.payload?.limit==="number"?$.payload.limit:void 0)});default:return TH($,"unsupported_command",`Unsupported hub schedule command: ${$.command}`)}}catch(f){return TH($,"schedule_command_failed",f instanceof Error?f.message:String(f))}}toCreateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider&&$.model?{providerId:String($.provider),modelId:String($.model)}:void 0;return{...$,modelSelection:f}}toUpdateInput($){let f=$.modelSelection&&typeof $.modelSelection==="object"&&!Array.isArray($.modelSelection)?$.modelSelection:$.provider||$.model?{providerId:typeof $.provider==="string"?$.provider:"",modelId:typeof $.model==="string"?$.model:""}:void 0;return{...$,modelSelection:f}}}function r6($){return $?new Date($).getTime():void 0}function XN($){let f=$.metadata?{...$.metadata}:void 0;if(f)delete f.__hubScheduleCreatedBy,delete f.__hubScheduleCwd,delete f.__hubRuntimeOptions;return f}function p6($){let f=$.metadata;return{scheduleId:$.externalId,name:$.title,cronPattern:$.scheduleExpr??"",prompt:$.prompt??"",workspaceRoot:$.workspaceRoot??"",cwd:typeof f?.__hubScheduleCwd==="string"?f.__hubScheduleCwd:void 0,modelSelection:$.providerId||$.modelId?{providerId:$.providerId??"",modelId:$.modelId??""}:void 0,enabled:$.enabled&&!$.removed&&$.parseStatus==="valid",mode:$.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act",systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,maxParallel:$.maxParallel??1,createdAt:new Date($.createdAt).getTime(),updatedAt:new Date($.updatedAt).getTime(),nextRunAt:r6($.nextRunAt),lastRunAt:r6($.lastRunAt),createdBy:typeof f?.__hubScheduleCreatedBy==="string"?f.__hubScheduleCreatedBy:void 0,tags:$.tags,runtimeOptions:f?.__hubRuntimeOptions&&typeof f.__hubRuntimeOptions==="object"&&!Array.isArray(f.__hubRuntimeOptions)?f.__hubRuntimeOptions:void 0,metadata:XN($)}}function HN($){switch($){case"done":return"success";case"cancelled":return"aborted";case"running":return"running";case"queued":return"pending";default:return"failed"}}function MH($,f){return{executionId:$.runId,scheduleId:f,sessionId:$.sessionId,triggeredAt:new Date($.scheduledFor??$.createdAt).getTime(),startedAt:r6($.startedAt),endedAt:r6($.completedAt),status:HN($.status),errorMessage:$.error}}class i6{store;materializer;runner;started=!1;disposed=!1;constructor($){this.store=new a2({dbPath:$.dbPath}),this.materializer=new l2({store:this.store}),this.runner=new p2({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(L5($.cronPattern),!$.workspaceRoot?.trim())throw Error("workspaceRoot is required for schedules");return p6(this.store.createHubSchedule($))}getSchedule($){let f=this.store.getHubSchedule($);return f?p6(f):void 0}listSchedules($={}){return this.store.listHubSchedules($).map((f)=>p6(f))}updateSchedule($,f){if(f.cronPattern!==void 0)L5(f.cronPattern);let J=this.store.getHubSchedule($);if(!J)return;let Q=f.workspaceRoot!==void 0?f.workspaceRoot.trim():J.workspaceRoot;if((f.enabled??J.enabled)&&!Q)throw Error("workspaceRoot is required for enabled schedules");let W=this.store.updateHubSchedule($,{...f,scheduleId:$});return W?p6(W):void 0}deleteSchedule($){return this.store.deleteHubSchedule($)}pauseSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!1})}resumeSchedule($){return this.updateSchedule($,{scheduleId:$,enabled:!0})}async triggerScheduleNow($){let f=this.store.enqueueHubScheduleRun($,"manual");if(!f)return;await this.runner.tick();let J=this.store.getRun(f.runId)??f;return MH(J,$)}listScheduleExecutions($){let f=$.scheduleId?this.store.getHubSchedule($.scheduleId):void 0,J={specId:f?.specId,limit:$.limit};return this.store.listRuns(J).map((Z)=>{let W=f??this.store.getSpec(Z.specId);if(!W||W.source!=="hub-schedule")return;return MH(Z,W.externalId)}).filter((Z)=>{if(!Z)return!1;return!$.status||Z.status===$.status})}getScheduleStats($){let f=this.listScheduleExecutions({scheduleId:$,limit:1e4});if(f.length===0)return{totalRuns:0,successRate:0,avgDurationSeconds:0};let J=0,Q=0,Z=0,W;for(let j of f){if(j.status==="success"||j.status==="completed")J+=1;if(!W&&j.status!=="success"&&j.status!=="completed")W=j;if(j.startedAt&&j.endedAt)Z+=j.endedAt-j.startedAt,Q+=1}return{totalRuns:f.length,successRate:J/f.length,avgDurationSeconds:Q>0?Z/Q/1000:0,lastFailure:W}}getActiveExecutions(){return this.runner.getActiveRuns().flatMap(($)=>{let f=this.store.getSpec($.specId);if(!f||f.source!=="hub-schedule"||!$.sessionId)return[];return[{executionId:$.runId,scheduleId:f.externalId,sessionId:$.sessionId,startedAt:$.startedAt??new Date().toISOString(),timeoutAt:f.timeoutSeconds&&$.startedAt?new Date(new Date($.startedAt).getTime()+f.timeoutSeconds*1000).toISOString():void 0}]})}getUpcomingRuns($=20){let f={triggerKind:"schedule",enabled:!0,limit:$};return this.store.listSpecs(f).flatMap((J)=>J.source==="hub-schedule"&&J.nextRunAt?[{spec:J,nextRunAt:J.nextRunAt}]:[]).sort((J,Q)=>String(J.nextRunAt).localeCompare(String(Q.nextRunAt))).slice(0,$).map(({spec:J,nextRunAt:Q})=>({scheduleId:J.externalId,name:J.title,nextRunAt:Q}))}}s6();function hN($,f){if($ instanceof Error)return $;if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string"&&$.message.trim())return Error($.message.trim());let J=$&&typeof $==="object"&&"type"in $&&typeof $.type==="string"?$.type.trim():"";return Error(J?`Failed to connect to hub at ${f} (${J} event before socket open).`:`Failed to connect to hub at ${f}.`)}var CN="cline-hub-auth.";function EN($){return $.host!==void 0||$.port!==void 0||$.pathname!==void 0}function bN($,f){let J=new URL($),Q=new URL(f);return J.search="",J.hash="",Q.search="",Q.hash="",J.toString()===Q.toString()}async function kN($){let f=$.searchParams.get("authToken")?.trim();if($.searchParams.delete("authToken"),f)return f;let J=D0(),Q=await A0(J.discoveryPath);if(Q?.url&&bN($.toString(),Q.url))return Q.authToken;return}async function IN($={}){let f=C$($);if(!EN($)){let J=D0(),Q=await A0(J.discoveryPath);if(Q?.url)return Q.url}return j$(f.host,f.port,f.pathname)}async function wH($){return await new Promise((f,J)=>{(async()=>{let Q=new URL($),Z=await kN(Q);Q.hash="";let W=new WebSocket(Q.toString(),Z?[`${CN}${Z}`]:void 0),j=new Map,X=0;W.addEventListener("open",()=>{f({send(H){let Y=H.requestId??`hub-client-${++X}`;return new Promise((V,A)=>{j.set(Y,{resolve:V,reject:A});let B={kind:"command",envelope:{...H,requestId:Y}};W.send(JSON.stringify(B))})},close(){W.close()}})}),W.addEventListener("message",(H)=>{let Y=JSON.parse(String(H.data));if(Y.kind==="reply"&&Y.envelope.requestId){let V=j.get(Y.envelope.requestId);if(V)j.delete(Y.envelope.requestId),V.resolve(Y.envelope)}}),W.addEventListener("close",()=>{for(let H of j.values())H.reject(Error("Hub connection closed"));j.clear()}),W.addEventListener("error",(H)=>{J(hN(H,$))})})().catch(J)})}async function Yv($){try{return(await wH($)).close(),!0}catch{return!1}}async function Vv($,f){let J=await IN($),Q=await wH(J);try{return await Q.send({version:f.version??"v1",clientId:f.clientId??"hub-client",...f})}finally{Q.close()}}function Y7($){return $?JSON.parse(JSON.stringify($)):{}}function o6($){let f=$?.session&&typeof $.session==="object"?$.session:void 0;if(!f)return;let J=f.metadata&&typeof f.metadata==="object"?Y7(f.metadata):void 0;return{sessionId:typeof f.sessionId==="string"?f.sessionId:"",parentSessionId:typeof J?.parentSessionId==="string"?J.parentSessionId:void 0,messagesPath:typeof J?.messagesPath==="string"?J.messagesPath:void 0,metadata:J}}function SH($,f){return $.error?.message??`hub command failed: ${f}`}function xN($){let f=Y7($);if(typeof f.error==="string"&&f.error.trim())return{...f,error:f.error.trim()};let J=f.result&&typeof f.result==="object"?f.result:void 0;if(typeof J?.text==="string"&&J.text.trim())return{...f,error:J.text.trim()};let Q=J?.error&&typeof J.error==="object"?J.error:void 0;if(typeof Q?.message==="string"&&Q.message.trim())return{...f,error:Q.message.trim()};return f}function hH($){let f=$?.sessionId;return typeof f==="string"&&f.trim()?f.trim():void 0}function mN($){let f=$?.checkpoint;if(!f||typeof f!=="object"||Array.isArray(f))throw Error("hub checkpoint restore returned no checkpoint");let J=f;if(typeof J.ref!=="string"||typeof J.createdAt!=="number"||typeof J.runCount!=="number")throw Error("hub checkpoint restore returned an invalid checkpoint");return J}function gN($){let f=Y7($.payload);if($.event==="schedule.execution_completed")return{sessionId:$.sessionId?.trim()||hH(f)||"",eventType:"schedule.execution.completed",payload:f};if($.event==="schedule.execution_failed")return{sessionId:$.sessionId?.trim()||hH(f)||"",eventType:"schedule.execution.failed",payload:f};let J=$.sessionId?.trim();if(!J)return;switch($.event){case"iteration.started":return{sessionId:J,eventType:"runtime.chat.iteration_start",payload:f};case"iteration.finished":return{sessionId:J,eventType:"runtime.chat.iteration_end",payload:f};case"assistant.delta":return{sessionId:J,eventType:"runtime.chat.text_delta",payload:f};case"usage.updated":return{sessionId:J,eventType:"runtime.chat.usage",payload:f};case"tool.started":return{sessionId:J,eventType:"runtime.chat.tool_call_start",payload:f};case"tool.finished":return{sessionId:J,eventType:"runtime.chat.tool_call_end",payload:f};case"approval.requested":return{sessionId:J,eventType:"approval.requested",payload:f};case"run.aborted":return{sessionId:J,eventType:"runtime.chat.aborted",payload:f};case"run.failed":return{sessionId:J,eventType:"runtime.chat.failed",payload:xN($.payload)};case"run.completed":return{sessionId:J,eventType:"runtime.chat.completed",payload:f};default:return}}class vN{options;client;metadataApplied=!1;constructor($){this.options=$;this.client=new X$({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-session-client",displayName:$.displayName??"hub session client",workspaceRoot:$.workspaceRoot,cwd:$.cwd})}async ensureMetadataApplied(){if(this.metadataApplied||!this.options.metadata){if(!this.options.metadata)await this.client.connect();return}await this.client.connect(),await this.client.command("client.update",{metadata:this.options.metadata}),this.metadataApplied=!0}async connect(){await this.ensureMetadataApplied()}close(){this.client.close()}async dispose(){await this.client.dispose()}async startRuntimeSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.create",{workspaceRoot:$.workspaceRoot,cwd:$.cwd,sessionConfig:{providerId:$.provider,modelId:$.model,apiKey:$.apiKey,cwd:$.cwd??$.workspaceRoot,workspaceRoot:$.workspaceRoot,systemPrompt:$.systemPrompt??"",mode:$.mode??"act",rules:$.rules,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawnAgent:$.enableSpawn!==!1,enableAgentTeams:$.enableTeams!==!1,disableMcpSettingsTools:$.disableMcpSettingsTools,missionLogIntervalSteps:$.missionStepInterval,missionLogIntervalMs:$.missionTimeIntervalMs},metadata:{source:$.source??"cli",provider:$.provider,model:$.model,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,prompt:void 0,interactive:$.interactive!==!1},runtimeOptions:{mode:$.mode,systemPrompt:$.systemPrompt,maxIterations:$.maxIterations,timeoutSeconds:$.timeoutSeconds,enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,autoApproveTools:$.autoApproveTools,toolExecutors:$.toolExecutors,configExtensions:$.configExtensions},modelSelection:{provider:$.provider,model:$.model,apiKey:$.apiKey},toolPolicies:$.toolPolicies}),J=o6(f.payload);if(!J?.sessionId)throw Error("hub session create returned no session id");return{sessionId:J.sessionId,startResult:{sessionId:J.sessionId,manifestPath:"",messagesPath:J.messagesPath??""}}}async sendRuntimeSession($,f,J){return await this.ensureMetadataApplied(),{result:(await this.client.command("session.send_input",{prompt:f.prompt,mode:f.config.mode,attachments:f.attachments,delivery:f.delivery,timeoutSeconds:f.config.timeoutSeconds},$,J)).payload?.result}}async stopRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("session.detach",{sessionId:$},$),{applied:!0}}async abortRuntimeSession($){return await this.ensureMetadataApplied(),await this.client.command("run.abort",{sessionId:$},$),{applied:!0}}async updateSession($){return await this.ensureMetadataApplied(),await this.client.command("session.update",{sessionId:$.sessionId,metadata:$.metadata},$.sessionId),{updated:!0}}async getSession($){await this.ensureMetadataApplied();let f=await this.client.command("session.get",void 0,$);return o6(f.payload)}async readMessages($){let f=$.trim();if(!f)return[];await this.ensureMetadataApplied();let J=await this.client.command("session.messages",{sessionId:f},f);if(!J.ok)throw Error(SH(J,"session.messages"));let Q=J.payload?.messages;return Array.isArray(Q)?Q:[]}async restore($){let f=$.sessionId.trim();if(!f)throw Error("sessionId is required");let J=$.restore?.messages!==!1;if(J&&!$.config)throw Error("config is required when restore.messages is true");await this.ensureMetadataApplied();let Q=$.config,Z=await this.client.command("session.restore",{sessionId:f,checkpointRunCount:$.checkpointRunCount,restore:$.restore,...Q?{workspaceRoot:Q.workspaceRoot,cwd:Q.cwd,sessionConfig:{providerId:Q.provider,modelId:Q.model,apiKey:Q.apiKey,cwd:Q.cwd??Q.workspaceRoot,workspaceRoot:Q.workspaceRoot,systemPrompt:Q.systemPrompt??"",mode:Q.mode??"act",rules:Q.rules,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawnAgent:Q.enableSpawn!==!1,enableAgentTeams:Q.enableTeams!==!1,disableMcpSettingsTools:Q.disableMcpSettingsTools,missionLogIntervalSteps:Q.missionStepInterval,missionLogIntervalMs:Q.missionTimeIntervalMs},metadata:{source:Q.source??"cli",provider:Q.provider,model:Q.model,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,prompt:void 0,interactive:Q.interactive!==!1},runtimeOptions:{mode:Q.mode,systemPrompt:Q.systemPrompt,maxIterations:Q.maxIterations,enableTools:Q.enableTools,enableSpawn:Q.enableSpawn,enableTeams:Q.enableTeams,autoApproveTools:Q.autoApproveTools,configExtensions:Q.configExtensions},modelSelection:{provider:Q.provider,model:Q.model,apiKey:Q.apiKey},toolPolicies:Q.toolPolicies}:{}},f);if(!Z.ok)throw Error(SH(Z,"session.restore"));let W=o6(Z.payload);if(J&&!W?.sessionId)throw Error("hub checkpoint restore returned no session id");let j=Array.isArray(Z.payload?.messages)?Z.payload.messages:void 0,X=mN(Z.payload);return{sessionId:W?.sessionId,startResult:W?.sessionId?{sessionId:W.sessionId,manifestPath:"",messagesPath:W.messagesPath??""}:void 0,...j?{messages:j}:{},checkpoint:X}}async listSessions($){await this.ensureMetadataApplied();let f=await this.client.command("session.list",{limit:$?.limit??200});return(Array.isArray(f.payload?.sessions)?f.payload?.sessions:[]).map((Q)=>o6({session:Q})).filter((Q)=>Boolean(Q?.sessionId))}async deleteSession($,f=!0){return await this.ensureMetadataApplied(),(await this.client.command("session.delete",{sessionId:$,deleteCheckpointRefs:f})).payload?.deleted===!0}async respondToolApproval($){await this.ensureMetadataApplied(),await this.client.command("approval.respond",{approvalId:$.approvalId,approved:$.approved,payload:$.reason?{reason:$.reason}:void 0,responderClientId:$.responderClientId})}streamEvents($,f){let J=new Set(($.sessionIds??[]).map((Z)=>Z.trim()).filter(Boolean)),Q=this.client.subscribe((Z)=>{let W=gN(Z);if(!W)return;if(J.size>0&&!J.has(W.sessionId))return;f.onEvent?.(W)});return this.ensureMetadataApplied().catch((Z)=>{f.onError?.(Z instanceof Error?Z:Error(String(Z)))}),Q}streamTeamProgress($,f){let J=this.client.subscribe((Q)=>{if(Q.event!=="team.progress"||!Q.payload)return;f.onProjection?.(Q.payload)});return this.ensureMetadataApplied().catch((Q)=>{f.onError?.(Q instanceof Error?Q:Error(String(Q)))}),J}async createSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.create",$)).payload?.schedule}async listSchedules($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.list");return Array.isArray(f.payload?.schedules)?f.payload?.schedules:[]}async getSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.get",{scheduleId:$})).payload?.schedule}async updateSchedule($,f){return await this.ensureMetadataApplied(),(await this.client.command("schedule.update",{scheduleId:$,...f})).payload?.schedule}async pauseSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.disable",{scheduleId:$})).payload?.schedule}async resumeSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.enable",{scheduleId:$})).payload?.schedule}async deleteSchedule($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.delete",{scheduleId:$})).payload?.deleted===!0}async triggerScheduleNow($){return await this.ensureMetadataApplied(),(await this.client.command("schedule.trigger",{scheduleId:$})).payload?.execution}async listScheduleExecutions($,f){await this.ensureMetadataApplied();let J=await this.client.command("schedule.list_executions",{scheduleId:$,limit:f});return Array.isArray(J.payload?.executions)?J.payload?.executions:[]}async getScheduleStats(){return await this.ensureMetadataApplied(),(await this.client.command("schedule.stats")).payload?.stats}async getActiveScheduledExecutions(){await this.ensureMetadataApplied();let $=await this.client.command("schedule.active");return Array.isArray($.payload?.executions)?$.payload?.executions:[]}async getUpcomingScheduledRuns($){await this.ensureMetadataApplied();let f=await this.client.command("schedule.upcoming",{limit:$});return Array.isArray(f.payload?.upcoming)?f.payload?.upcoming:[]}}class uN{client;constructor($){this.client=new X$({url:$.address,authToken:$.authToken,clientId:$.clientId,clientType:$.clientType??"hub-ui-client",displayName:$.displayName??"hub ui client"})}async connect(){await this.client.connect()}close(){this.client.close()}async dispose(){await this.client.dispose()}getClientId(){return this.client.getClientId()}async sendNotify($){await this.client.command("ui.notify",$)}async sendShowWindow($){await this.client.command("ui.show_window",$??{})}async listClients(){let $=await this.client.command("client.list");return Array.isArray($.payload?.clients)?$.payload.clients:[]}async listSessions($=200){let f=await this.client.command("session.list",{limit:$});return Array.isArray(f.payload?.sessions)?f.payload.sessions:[]}subscribeUI($){return this.client.subscribe((f)=>{switch(f.event){case"ui.notify":$.onNotify?.(f.payload);break;case"ui.show_window":$.onShowWindow?.(f.payload);break;case"hub.client.registered":$.onClientRegistered?.(f.payload??{});break;case"hub.client.disconnected":$.onClientDisconnected?.(f.payload??{});break;case"session.created":$.onSessionCreated?.(f.payload??{});break;case"session.updated":$.onSessionUpdated?.(f.payload??{});break;case"session.detached":$.onSessionDetached?.(f.payload??{});break}})}}import{normalizeProviderId as cN}from"@cline/llms";function dN($){return{text:$.text,usage:$.usage,inputTokens:$.usage.inputTokens,outputTokens:$.usage.outputTokens,iterations:$.iterations,finishReason:$.finishReason,toolCalls:$.toolCalls.map((f)=>({name:f.name,input:f.input,output:f.output,error:f.error,durationMs:f.durationMs}))}}function lN($){return $.mode==="plan"?"plan":$.mode==="yolo"?"yolo":"act"}function Ov($={}){let f=new l$({sessionService:new m$(new x$),fetch:$.fetch,telemetry:$.telemetry});return{async startSession(J){let Q=(J.cwd?.trim()||J.workspaceRoot).trim(),Z=await f.startSession({source:J.source?.trim()||F0.CLI,interactive:!1,config:{providerId:cN(J.provider),modelId:J.model,apiKey:J.apiKey?.trim()||void 0,cwd:Q,workspaceRoot:J.workspaceRoot,systemPrompt:J.systemPrompt??"",mode:lN(J),maxIterations:J.maxIterations,enableTools:J.enableTools!==!1,enableSpawnAgent:J.enableSpawn!==!1,enableAgentTeams:J.enableTeams!==!1,disableMcpSettingsTools:J.disableMcpSettingsTools,missionLogIntervalSteps:J.missionStepInterval,missionLogIntervalMs:J.missionTimeIntervalMs},toolPolicies:J.toolPolicies??{"*":{autoApprove:J.autoApproveTools!==!1}},localRuntime:{configExtensions:J.configExtensions}});return{sessionId:Z.sessionId,startResult:{sessionId:Z.sessionId,manifestPath:Z.manifestPath,messagesPath:Z.messagesPath}}},async sendSession(J,Q){let Z=await f.runTurn({sessionId:J,prompt:Q.prompt,userImages:Q.attachments?.userImages,userFiles:Q.attachments?.userFiles?.map((W)=>W.content)});if(!Z)throw Error("local hub schedule runtime returned no turn result");return{result:dN(Z)}},async abortSession(J){return await f.abort(J,Error("hub schedule abort")),{applied:!0}},async stopSession(J){return await f.stopSession(J),{applied:!0}}}}function pN($){if(typeof $==="string")return $.trim()||void 0;if(!Array.isArray($))return;return $.map((J)=>{if(J&&typeof J==="object"&&"type"in J&&J.type==="text"&&"text"in J&&typeof J.text==="string")return J.text.trim();return""}).filter(Boolean).join(`
697
+ `).trim()||void 0}var CH=120,V7="...";function A7($){let f=$.trim();if(!f)return"";if(Buffer.byteLength(f,"utf8")<=CH)return f;let J=CH-Buffer.byteLength(V7,"utf8");if(J<=0)return V7;let Q="";for(let Z of f){if(Buffer.byteLength(Q+Z,"utf8")>J)break;Q+=Z}return`${Q}${V7}`}async function EH($){let f=$?.sessionId?.trim()||"unknown",J=typeof $?.metadata?.messagesPath==="string"?$.metadata.messagesPath:void 0,Z=[...await h$(J)].reverse().find((H)=>H.role==="assistant"),W=Z?pN(Z.content):void 0,j=$?.workspaceRoot?.trim()||"workspace",X=typeof $?.metadata?.prompt==="string"?$.metadata.prompt.trim():j;return{title:`Task completed (${f})`,body:A7(W&&W.length>0?W:X.length>0?X:j),severity:"info"}}import{captureSdkError as Jf,createSessionId as LT}from"@cline/shared";import{createSessionId as aN}from"@cline/shared";import{createSessionId as nN}from"@cline/shared";function rN($){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 iN($){let f=$.metadata&&typeof $.metadata==="object"?JSON.parse(JSON.stringify($.metadata)):{};if($.parentSessionId?.trim())f.parentSessionId=$.parentSessionId;if($.parentAgentId?.trim())f.parentAgentId=$.parentAgentId;if($.agentId?.trim())f.agentId=$.agentId;if($.conversationId?.trim())f.conversationId=$.conversationId;if($.messagesPath?.trim())f.messagesPath=$.messagesPath;if($.prompt?.trim())f.prompt=$.prompt;if($.provider?.trim())f.provider=$.provider;if($.model?.trim())f.model=$.model;if($.source?.trim())f.source=$.source;if(typeof $.pid==="number")f.pid=$.pid;return Object.keys(f).length>0?f:void 0}function e6($,f,J,Q){return{sessionId:$.sessionId,workspaceRoot:$.workspaceRoot,cwd:$.cwd,createdAt:Date.parse($.startedAt),updatedAt:Date.parse($.updatedAt),createdByClientId:f?.createdByClientId??"hub",status:rN($.status),participants:f?[...f.participants.values()]:[],metadata:iN($),runtimeOptions:{enableTools:$.enableTools,enableSpawn:$.enableSpawn,enableTeams:$.enableTeams,mode:typeof $.metadata?.mode==="string"?$.metadata.mode:void 0,systemPrompt:typeof $.metadata?.systemPrompt==="string"?$.metadata.systemPrompt:void 0},runtimeSession:$.agentId?{agentId:$.agentId,team:$.teamName?{teamId:$.teamName}:void 0}:void 0,...J?{usage:{...J}}:{},...Q?{aggregateUsage:{...Q}}:{}}}function m($,f){return{version:$.version,requestId:$.requestId,ok:!0,...f!==void 0?{payload:f}:{}}}function b($,f,J){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:f,message:J}}}function $f($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function T0($){if(typeof $.payload?.sessionId==="string")return $.payload.sessionId.trim();return $.sessionId?.trim()??""}function M1($,f,J){return{version:"v1",event:$,eventId:nN("hevt_"),sessionId:J,timestamp:Date.now(),payload:f}}async function g0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let Q=await $.sessionHost.getAccumulatedUsage?.(f);return e6(J,$.sessionState.get(f),Q?.usage,Q?.aggregateUsage)}async function v0($,f){let J=await $.sessionHost.getSession(f);if(!J)return;let[Q,Z]=await Promise.all([typeof $.sessionHost.readSessionMessages==="function"?$.sessionHost.readSessionMessages(f):[],$.sessionHost.getAccumulatedUsage?.(f)]);return b$({session:J,messages:Q,usage:Z?.usage,aggregateUsage:Z?.aggregateUsage})}function ff($,f,J,Q,Z={}){let W=$.sessionState.get(f);if(W){if(Z.interactive!==void 0)W.interactive=Z.interactive;if(!W.participants.has(J))W.participants.set(J,{clientId:J,attachedAt:Date.now(),role:Q});return W}let j={createdByClientId:J,interactive:Z.interactive??!0,participants:new Map([[J,{clientId:J,attachedAt:Date.now(),role:Q}]])};return $.sessionState.set(f,j),j}async function B7($,f){let J=aN("approval_"),Q=f.sessionId;if($.sessionState.get(Q)?.interactive===!1)return{approved:!1,reason:"Tool approval requires an interactive session, but this session is non-interactive."};return await new Promise((W)=>{$.pendingApprovals.set(J,{sessionId:Q,resolve:W}),$.publish($.buildEvent("approval.requested",{approvalId:J,sessionId:f.sessionId,agentId:f.agentId,conversationId:f.conversationId,iteration:f.iteration,toolCallId:f.toolCallId,toolName:f.toolName,inputJson:JSON.stringify(f.input??null),policy:f.policy},Q))})}function G7($,f,J){let Q=$.pendingApprovals.get(f);if(!Q)return;return $.pendingApprovals.delete(f),Q.resolve(J),{sessionId:Q.sessionId}}function K7($,f,J){let Q=0;for(let[Z,W]of[...$.pendingApprovals.entries()]){if(!f({approvalId:Z,sessionId:W.sessionId}))continue;$.pendingApprovals.delete(Z),W.resolve({approved:!1,reason:J}),$.publish($.buildEvent("approval.resolved",{approvalId:Z,approved:!1,cancelled:!0,reason:J},W.sessionId)),Q+=1}return Q}async function bH($,f){let J=typeof f.payload?.approvalId==="string"?f.payload.approvalId.trim():"";if(!$.pendingApprovals.get(J))return b(f,"approval_not_found",`Unknown approval: ${J}`);let Z=typeof f.payload?.reason==="string"?f.payload.reason:f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)&&typeof f.payload.payload.reason==="string"?f.payload.payload.reason:void 0,W=f.payload?.approved===!0,j=G7($,J,{approved:W,reason:Z});if(!j)return b(f,"approval_not_found",`Unknown approval: ${J}`);return $.publish($.buildEvent("approval.resolved",{approvalId:J,approved:W,reason:Z},j.sessionId)),m(f,{approvalId:J,approved:W})}import{createSessionId as oN}from"@cline/shared";function tN($){if($ instanceof Error)return{name:$.name,message:$.message,stack:$.stack};if($===void 0)return;return $}var kH={debug:10,info:20,warn:30,error:40,silent:50};function sN(){let $=process.env.CLINE_HUB_LOG_LEVEL?.trim().toLowerCase();if($==="debug"||$==="info"||$==="warn"||$==="error"||$==="silent")return $;return process.env.VITEST?"error":"info"}function I($,f,J={}){if(kH[$]<kH[sN()])return;let Q=JSON.stringify({ts:new Date().toISOString(),level:$,component:"hub",message:f,...Object.fromEntries(Object.entries(J).map(([Z,W])=>[Z,tN(W)]).filter(([,Z])=>Z!==void 0))});if($==="error"||$==="warn"){console.error(`[hub] ${Q}`);return}console.log(`[hub] ${Q}`)}function F7($,f){let J=f instanceof Error?f.stack||f.message:String(f);I("error",$,{error:J})}async function IH($,f,J,Q,Z,W){let j=oN("capreq_"),X=performance.now();return I("info","capability.request.start",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z}),await new Promise((H,Y)=>{$.pendingCapabilityRequests.set(j,{sessionId:f,targetClientId:Z,capabilityName:J,onProgress:W,resolve:(V)=>{if(I(V.ok?"info":"warn","capability.request.end",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z,ok:V.ok,error:V.error,durationMs:Math.round(performance.now()-X)}),!V.ok){Y(Error(V.error||`Capability ${J} was rejected by ${Z}.`));return}H(V.payload)}}),$.publish($.buildEvent("capability.requested",{requestId:j,targetClientId:Z,capabilityName:J,payload:Q},f)),I("info","capability.request.published",{requestId:j,sessionId:f,capabilityName:J,targetClientId:Z})})}function xH($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return b(f,"capability_not_found",`Unknown capability request: ${J}`);if((f.clientId?.trim()||"")!==Q.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{};return Q.onProgress?.(W),m(f,{requestId:J})}function p$($,f,J){let Q=0;for(let[Z,W]of[...$.pendingCapabilityRequests.entries()]){if(!f({requestId:Z,...W}))continue;$.pendingCapabilityRequests.delete(Z),I("warn","capability.request.cancelled",{requestId:Z,sessionId:W.sessionId,capabilityName:W.capabilityName,targetClientId:W.targetClientId,reason:J}),W.resolve({ok:!1,error:J}),$.publish($.buildEvent("capability.resolved",{requestId:Z,capabilityName:W.capabilityName,targetClientId:W.targetClientId,ok:!1,cancelled:!0,error:J},W.sessionId)),Q+=1}return Q}async function mH($,f){let J=typeof f.payload?.sessionId==="string"?f.payload.sessionId.trim():f.sessionId?.trim()||"",Q=typeof f.payload?.capabilityName==="string"?f.payload.capabilityName.trim():"",Z=typeof f.payload?.targetClientId==="string"?f.payload.targetClientId.trim():"";if(!J||!Q||!Z)return b(f,"invalid_capability_request","capability.request requires sessionId, capabilityName, and targetClientId");try{let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:{},j=await $.requestCapability(J,Q,W,Z);return m(f,j)}catch(W){return b(f,"capability_request_failed",W instanceof Error?W.message:String(W))}}function gH($,f){let J=typeof f.payload?.requestId==="string"?f.payload.requestId.trim():"",Q=$.pendingCapabilityRequests.get(J);if(!Q)return b(f,"capability_not_found",`Unknown capability request: ${J}`);let Z=f.clientId?.trim()||"";if(Z!==Q.targetClientId)return b(f,"capability_wrong_client",`Capability request ${J} is owned by ${Q.targetClientId}`);if(f.sessionId?.trim()&&f.sessionId.trim()!==Q.sessionId)return b(f,"capability_wrong_session",`Capability request ${J} belongs to session ${Q.sessionId}`);$.pendingCapabilityRequests.delete(J);let W=f.payload?.payload&&typeof f.payload.payload==="object"&&!Array.isArray(f.payload.payload)?f.payload.payload:void 0,j=typeof f.payload?.error==="string"?f.payload.error:void 0,X=f.payload?.ok===!0;return I(X?"info":"warn","capability.respond",{requestId:J,sessionId:Q.sessionId,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,error:j}),Q.resolve({ok:X,payload:W,error:j}),$.publish($.buildEvent("capability.resolved",{requestId:J,capabilityName:Q.capabilityName,targetClientId:Q.targetClientId,respondedByClientId:Z,ok:X,payload:W,error:j},Q.sessionId)),m(f,{requestId:J,ok:X})}import{createSessionId as eN}from"@cline/shared";function vH($,f){let J=f.payload,Q=J?.clientId?.trim()||f.clientId?.trim()||eN("client_");return $.clients.set(Q,{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,actorKind:J?.actorKind??"client",connectedAt:Date.now(),lastSeenAt:Date.now(),transport:J?.transport??"native",capabilities:J?.capabilities??[],metadata:J?.metadata,workspaceContext:J?.workspaceContext}),$.publish($.buildEvent("hub.client.registered",{clientId:Q,clientType:J?.clientType??"unknown",displayName:J?.displayName,connectedAt:Date.now()})),m(f,{clientId:Q})}function uH($,f){let J=f.clientId?.trim(),Q=J?$.clients.get(J):void 0;if(!J||!Q)return b(f,"client_not_found","Client is not registered with this hub.");let Z=$f(f.payload?.metadata);if(Q.lastSeenAt=Date.now(),Z)Q.metadata=JSON.parse(JSON.stringify(Z));return m(f)}function cH($,f,J){let Q=f.clientId?.trim();if(Q)$.clients.delete(Q),J(Q),$.publish($.buildEvent("hub.client.disconnected",{clientId:Q}));return m(f)}function dH($,f){return m(f,{clients:[...$.clients.values()]})}var $T=30000;function fT($){if($==="aborted")return"run.aborted";if($==="error"||$==="failed")return"run.failed";return"run.completed"}function JT($){if($.finishReason!=="error")return;return $.text.trim()||void 0}function QT($){return $?$:void 0}function ZT($){let f=typeof $.timeoutMs==="number"?$.timeoutMs:typeof $.timeout_ms==="number"?$.timeout_ms:void 0;if(f&&Number.isFinite(f)&&f>0)return Math.floor(f);let J=typeof $.timeoutSeconds==="number"?$.timeoutSeconds:typeof $.timeout_seconds==="number"?$.timeout_seconds:void 0;if(J&&Number.isFinite(J)&&J>0)return Math.floor(J*1000);return}async function WT($,f,J,Q){let Z=performance.now(),W=!1,j={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J.sessionId,timeoutMs:Q},X=setInterval(()=>{if(W)return;let V=Math.round(performance.now()-Z);I("warn","run.heartbeat",{...j,elapsedMs:V}),$.publish($.buildEvent("run.heartbeat",{requestId:f.requestId,elapsedMs:V,...Q?{timeoutMs:Q}:{}},J.sessionId))},$T),H=$.sessionHost.runTurn(J);H.then((V)=>{if(!W)return;I("warn","run.late_end",{...j,elapsedMs:Math.round(performance.now()-Z),finishReason:V?.finishReason})},(V)=>{if(!W)return;I("error","run.late_error",{...j,elapsedMs:Math.round(performance.now()-Z),error:V})});let Y;try{if(!Q)return await H;return await Promise.race([H,new Promise((V,A)=>{Y=setTimeout(()=>{let B=`Hub run ${f.command} timed out after ${Q}ms.`;W=!0,clearInterval(X),A(Error(B)),I("error","run.timeout",{...j,elapsedMs:Math.round(performance.now()-Z)}),K7($,(G)=>G.sessionId===J.sessionId,B),p$($,(G)=>G.sessionId===J.sessionId,B),$.sessionHost.abort(J.sessionId,B).catch((G)=>{I("error","run.timeout_abort_failed",{...j,error:G})})},Q)})])}finally{if(W=!0,clearInterval(X),Y)clearTimeout(Y)}}async function lH($,f){let J=T0(f),Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.prompt==="string"?Q.prompt:typeof Q.input==="string"?Q.input:"";if(!Z.trim())return b(f,"invalid_session_input","session input requires a prompt string");$.publish($.buildEvent("run.started",void 0,J));let W=Q.attachments&&typeof Q.attachments==="object"&&!Array.isArray(Q.attachments)?Q.attachments:void 0,j=Array.isArray(W?.userFiles)?W.userFiles.filter((V)=>typeof V==="string"):void 0,X=ZT(Q);$.suppressNextTerminalEventBySession.set(J,"run.start.reply");let H;try{H=await WT($,f,{sessionId:J,prompt:Z,mode:QT(Q.mode),delivery:Q.delivery==="queue"||Q.delivery==="steer"?Q.delivery:void 0,userImages:Array.isArray(W?.userImages)?W.userImages:void 0,userFiles:j,timeoutMs:X},X)}catch(V){if($.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J);throw $.publish($.buildEvent("run.failed",{reason:"error",error:V instanceof Error?V.message:String(V)},J)),V}if(H){let V=await v0($,J),A=JT(H);if($.publish($.buildEvent(fT(H.finishReason),{reason:H.finishReason,...A?{error:A}:{},result:H,...V?{snapshot:V}:{}},J)),$.suppressNextTerminalEventBySession.get(J)==="run.start.reply")$.suppressNextTerminalEventBySession.delete(J)}else $.suppressNextTerminalEventBySession.delete(J);let Y=await v0($,J);return m(f,H||Y?{...H?{result:H}:{},...Y?{snapshot:Y}:{}}:void 0)}async function pH($,f){let J=T0(f),Q=typeof f.payload?.reason==="string"?f.payload.reason:"Run was aborted before pending approval or capability request was resolved.";K7($,(Z)=>Z.sessionId===J,Q);try{await $.sessionHost.abort(J,f.payload?.reason)}catch(Z){I("warn","run.abort_failed",{command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:J,error:Z})}finally{p$($,(Z)=>Z.sessionId===J,Q)}return m(f,{applied:!0})}async function rH($,f){let J=c6(f.payload?.payload);if(!J)return b(f,"invalid_hook_payload","session.hook requires a valid hook event payload");return await $.sessionHost.dispatchHookEvent(J),m(f,{applied:!0})}async function iH($,f){switch(f.type){case"chunk":return;case"agent_event":await jT($,f);return;case"hook":if(f.payload.hookEventName==="tool_call")$.publish($.buildEvent("tool.started",{toolName:f.payload.toolName},f.payload.sessionId));else if(f.payload.hookEventName==="tool_result")$.publish($.buildEvent("tool.finished",{toolName:f.payload.toolName},f.payload.sessionId));return;case"team_progress":{let J={type:"team_progress_projection",version:1,sessionId:f.payload.sessionId,summary:f.payload.summary,lastEvent:f.payload.lifecycle};$.publish($.buildEvent("team.progress",J,f.payload.sessionId));return}case"pending_prompts":$.publish($.buildEvent("session.pending_prompts",{sessionId:f.payload.sessionId,prompts:f.payload.prompts},f.payload.sessionId));return;case"pending_prompt_submitted":{let J={id:f.payload.id,prompt:f.payload.prompt,delivery:f.payload.delivery,attachmentCount:f.payload.attachmentCount};$.publish($.buildEvent("session.pending_prompt_submitted",{sessionId:f.payload.sessionId,prompt:J},f.payload.sessionId));return}case"session_snapshot":$.publish($.buildEvent("session.updated",{sessionId:f.payload.sessionId,snapshot:f.payload.snapshot},f.payload.sessionId));return;case"status":{let[J,Q]=await Promise.all([g0($,f.payload.sessionId),v0($,f.payload.sessionId)]);if(J)$.publish($.buildEvent("session.updated",{session:J,...Q?{snapshot:Q}:{}},f.payload.sessionId));return}case"ended":await XT($,f);return;default:return}}async function jT($,f){let{sessionId:J,event:Q}=f.payload;if(Q.type==="iteration_start"){$.publish($.buildEvent("iteration.started",{iteration:Q.iteration},J));return}if(Q.type==="iteration_end"){$.publish($.buildEvent("iteration.finished",{iteration:Q.iteration,hadToolCalls:Q.hadToolCalls,toolCallCount:Q.toolCallCount},J));return}if(Q.type==="content_start"){if(Q.contentType==="text"&&typeof Q.text==="string"&&Q.text.length>0){$.publish($.buildEvent("assistant.delta",{text:Q.text},J));return}if(Q.contentType==="reasoning"){if(Q.redacted&&!Q.reasoning){$.publish($.buildEvent("reasoning.delta",{text:"",redacted:!0},J));return}if(typeof Q.reasoning==="string"&&Q.reasoning.length>0)$.publish($.buildEvent("reasoning.delta",{text:Q.reasoning,redacted:Q.redacted===!0},J));return}if(Q.contentType==="tool"){$.publish($.buildEvent("tool.started",{toolCallId:Q.toolCallId,toolName:Q.toolName,input:Q.input},J));return}}if(Q.type==="content_end"){switch(Q.contentType){case"text":$.publish($.buildEvent("assistant.finished",{text:Q.text},J));break;case"reasoning":$.publish($.buildEvent("reasoning.finished",{reasoning:Q.reasoning},J));break;case"tool":$.publish($.buildEvent("tool.finished",{toolCallId:Q.toolCallId,toolName:Q.toolName,output:Q.output,error:Q.error},J));break}return}if(Q.type==="usage"){let Z;try{Z=await $.sessionHost.getAccumulatedUsage?.(J)}catch{Z=void 0}$.publish($.buildEvent("usage.updated",{sessionId:J,delta:{inputTokens:Q.inputTokens,outputTokens:Q.outputTokens,cacheReadTokens:Q.cacheReadTokens??0,cacheWriteTokens:Q.cacheWriteTokens??0,totalCost:Q.cost??0},totals:{inputTokens:Q.totalInputTokens,outputTokens:Q.totalOutputTokens,cacheReadTokens:Q.totalCacheReadTokens??0,cacheWriteTokens:Q.totalCacheWriteTokens??0,totalCost:Q.totalCost??0},usage:Z?.usage,aggregateUsage:Z?.aggregateUsage,agent:{kind:f.payload.teamRole==="teammate"?"teammate":Q.parentAgentId?"subagent":"lead",agentId:Q.agentId,conversationId:Q.conversationId,parentAgentId:Q.parentAgentId,teamAgentId:f.payload.teamAgentId,teamRole:f.payload.teamRole}},J));return}if(Q.type==="done")$.publish($.buildEvent("agent.done",{reason:Q.reason,text:Q.text,iterations:Q.iterations,usage:Q.usage},J))}async function XT($,f){let J=$.suppressNextTerminalEventBySession.get(f.payload.sessionId),Q=J===f.payload.reason||J==="run.start.reply";if(Q)$.suppressNextTerminalEventBySession.delete(f.payload.sessionId);let[Z,W]=await Promise.all([g0($,f.payload.sessionId),v0($,f.payload.sessionId)]);if(f.payload.reason==="completed"){let j=await EH(Z);$.publish($.buildEvent("ui.notify",j,f.payload.sessionId))}if(Q)return;$.publish($.buildEvent(f.payload.reason==="aborted"?"run.aborted":f.payload.reason==="error"||f.payload.reason==="failed"?"run.failed":"run.completed",{reason:f.payload.reason,...W?{snapshot:W}:{}},f.payload.sessionId))}import{createSessionId as aH,parseRuntimeConfigExtensions as tH}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as sv,HUB_COMPACTION_CAPABILITY as ov,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as ev,HUB_HOOK_CAPABILITY_PREFIX as $u,HUB_MISTAKE_LIMIT_CAPABILITY as fu,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Ju,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Qu,isHubToolExecutorName as HT}from"@cline/shared";import{HUB_CHECKPOINT_CAPABILITY as Hu,HUB_COMPACTION_CAPABILITY as Yu,HUB_CUSTOM_TOOL_CAPABILITY_PREFIX as Vu,HUB_HOOK_CAPABILITY_PREFIX as Au,HUB_MISTAKE_LIMIT_CAPABILITY as Bu,HUB_TOOL_EXECUTOR_CAPABILITY_PREFIX as Gu,HUB_USER_INSTRUCTIONS_SNAPSHOT_CAPABILITY as Ku}from"@cline/shared";var YT=["beforeRun","afterRun","beforeModel","afterModel","beforeTool","afterTool","onEvent"];function q1($){return $&&typeof $==="object"&&!Array.isArray($)?JSON.parse(JSON.stringify($)):void 0}function VT($,f){let J=typeof $.name==="string"?$.name.trim():"",Q=typeof $.description==="string"?$.description:"",Z=typeof $.capabilityName==="string"?$.capabilityName.trim():"",W=q1($.inputSchema);if(!J||!Q||!W||!Z||f.has(Z))return;return f.add(Z),{kind:"tool",capabilityName:Z,name:J,description:Q,inputSchema:W,...q1($.lifecycle)?{lifecycle:q1($.lifecycle)}:{}}}function U7($){if(!Array.isArray($))return[];let f=[],J=new Set;for(let Q of $){if(!Q||typeof Q!=="object"||Array.isArray(Q))continue;let Z=Q,W=Z.kind,j=typeof Z.capabilityName==="string"?Z.capabilityName.trim():"";if(!j||J.has(j))continue;if(W==="tool"){let X=VT(Z,J);if(X)f.push(X);continue}if(W==="toolExecutor"){let X=Z.executor;if(!HT(X))continue;J.add(j),f.push({kind:"toolExecutor",capabilityName:j,executor:X});continue}if(W==="hook"){let X=typeof Z.name==="string"?Z.name.trim():"";if(!X)continue;J.add(j),f.push({kind:"hook",capabilityName:j,name:X});continue}if(W==="compaction"){J.add(j),f.push({kind:"compaction",capabilityName:j,...q1(Z.config)?{config:q1(Z.config)}:{}});continue}if(W==="checkpoint"){J.add(j),f.push({kind:"checkpoint",capabilityName:j,...q1(Z.config)?{config:q1(Z.config)}:{}});continue}if(W==="mistakeLimit"){J.add(j),f.push({kind:"mistakeLimit",capabilityName:j});continue}if(W==="userInstructionService")J.add(j),f.push({kind:"userInstructionService",capabilityName:j})}return f}function nH($){return{agentId:$.agentId,conversationId:$.conversationId,iteration:$.iteration,metadata:$.metadata}}function AT($){return Object.hasOwn($,"update")?$.update:$}function q8($){return $.trim().replace(/^\/+/,"").toLowerCase()}function BT($){let f=($??[]).map(q8).filter(Boolean);return f.length>0?new Set(f):void 0}function GT($,f,J){if(!J)return!0;let Q=q8($),Z=q8(f),W=Q.includes(":")?Q.split(":").at(-1)??Q:Q,j=Z.includes(":")?Z.split(":").at(-1)??Z:Z;return J.has(Q)||J.has(Z)||J.has(W)||J.has(j)}function P7($,f){let J=BT(f);return $.records.skill.map((Q)=>({id:Q.id,name:Q.item.name,description:"description"in Q.item&&typeof Q.item.description==="string"?Q.item.description:void 0,disabled:Q.item.disabled===!0,skill:Q.item})).filter((Q)=>GT(Q.id,Q.name,J))}function KT($,f){let J=async(Q,Z)=>{let W=q8(Q),X=P7($,f).filter((B)=>B.id===W||q8(B.name)===W||B.id.endsWith(`:${W}`)).filter((B)=>!B.disabled);if(X.length!==1)return X.length>1?`Skill "${Q}" is ambiguous. Use one of: ${X.map((B)=>B.id).join(", ")}`:`Skill "${Q}" not found.`;let H=X[0].skill,Y=Z?.trim(),V=Y?`
698
698
  <command-args>${Y}</command-args>`:"",A=H.description?.trim()?`Description: ${H.description.trim()}
699
699
 
700
700
  `:"";return`<command-name>${H.name}</command-name>${V}
701
701
  <command-instructions>
702
702
  ${A}${H.instructions}
703
- </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>J7($,f).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function hy($,f,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:W,stop:()=>{},refreshType:async()=>{await W()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let H=j.match(/^\/(\S+)/)?.[1];if(!H)return j;let Y=Z.runtimeCommands.find((V)=>V.name===H);return Y?`${Y.instructions}${j.slice(H.length+1)}`:j},hasConfiguredSkills:(j)=>J7(Z,j).some((X)=>!X.disabled),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(j.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>t2(Z.records.rule.map((H)=>H.item).filter((H)=>H.disabled!==!0))});if(j.registerSkillsTool)X.registerTool(k1(Ey(Z,j.allowedSkillNames)));for(let H of Z.runtimeCommands.filter((Y)=>Y.kind==="skill"&&j.includeSkills||Y.kind==="workflow"&&j.includeWorkflows))X.registerCommand({name:H.name,description:H.description,handler:(Y)=>{let V=Y.trim();return V?`${H.instructions}
703
+ </command-instructions>`};return Object.defineProperty(J,"configuredSkills",{get:()=>P7($,f).map(({skill:Q,...Z})=>Z),enumerable:!0}),J}function FT($,f,J,Q){let Z={records:{skill:[],rule:[],workflow:[]},runtimeCommands:[]},W=async()=>{let j=await Q($,J.capabilityName,{},f);if(j?.snapshot)Z=j.snapshot};return{start:W,stop:()=>{},refreshType:async()=>{await W()},listRecords:(j)=>[...Z.records[j]],listRuntimeCommands:()=>[...Z.runtimeCommands],resolveRuntimeSlashCommand:(j)=>{if(!j.startsWith("/")||j.length<2)return j;let H=j.match(/^\/(\S+)/)?.[1];if(!H)return j;let Y=Z.runtimeCommands.find((V)=>V.name===H);return Y?`${Y.instructions}${j.slice(H.length+1)}`:j},hasConfiguredSkills:(j)=>P7(Z,j).some((X)=>!X.disabled),createExtension:(j)=>({name:"cline-hub-user-instructions",manifest:{capabilities:[j.includeRules?"rules":void 0,j.registerSkillsTool?"tools":void 0,j.includeSkills||j.includeWorkflows?"commands":void 0].filter((X)=>Boolean(X))},setup(X){if(j.includeRules)X.registerRule({id:"cline-hub-user-instructions:rules",source:"hub-user-instructions",content:()=>J4(Z.records.rule.map((H)=>H.item).filter((H)=>H.disabled!==!0))});if(j.registerSkillsTool)X.registerTool(x1(KT(Z,j.allowedSkillNames)));for(let H of Z.runtimeCommands.filter((Y)=>Y.kind==="skill"&&j.includeSkills||Y.kind==="workflow"&&j.includeWorkflows))X.registerCommand({name:H.name,description:H.description,handler:(Y)=>{let V=Y.trim();return V?`${H.instructions}
704
704
 
705
- ${V}`:H.instructions}})}})}}function by($,f,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let X=j.at(-1),H=j.slice(0,-1);return(await Q($,W.capabilityName,{executor:W.executor,args:H,context:qH(X)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function ky($,f,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q($,Z.capabilityName,{toolName:Z.name,input:W,context:qH(j)},f,j.emitUpdate?(H)=>{j.emitUpdate?.(wy(H))}:void 0))?.result}}))}function Iy($,f,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of My){let X=Z.get(j);if(!X)continue;W[j]=async(H)=>{return(await Q($,X.capabilityName,{context:H},f))?.control}}return Object.keys(W).length>0?W:void 0}function Z7($){let f=$.contributions.filter((H)=>H.kind==="toolExecutor"),J=$.contributions.filter((H)=>H.kind==="tool"),Q=$.contributions.filter((H)=>H.kind==="hook"),Z=$.contributions.find((H)=>H.kind==="compaction"),W=$.contributions.find((H)=>H.kind==="checkpoint"),j=$.contributions.find((H)=>H.kind==="mistakeLimit"),X=$.contributions.find((H)=>H.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:by($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...Q.length>0?{hooks:Iy($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J.length>0?{extraTools:ky($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(H)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...W?{checkpoint:{...$.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(H)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(H)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:H},$.targetClientId))?.result}}:{},...X?{userInstructionService:hy($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var CH="hubCapabilityOwnerClientId";function EH($,f){$[CH]=f}function xy($){let f=$?.[CH];return typeof f==="string"&&f.trim()?f.trim():void 0}async function hH($,f,J){let Q=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};I("info","session.create.begin",Z);let W=f.payload&&typeof f.payload==="object"?f.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,H=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof X?.mode==="string")j.mode=X.mode;else if(typeof H.mode==="string")j.mode=H.mode;if(typeof X?.systemPrompt==="string")j.systemPrompt=X.systemPrompt;else if(typeof H.systemPrompt==="string")j.systemPrompt=H.systemPrompt;if(X?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(H.checkpointEnabled===!0)j.checkpointEnabled=!0;let Y=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},V=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!V)return I("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),b(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let A=f.clientId?.trim()||"hub-client",B=Q7(H.clientContributions);if(I("info","session.create.contributions_parsed",{...Z,clientId:A,workspaceRoot:V,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)EH(j,A);let G=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||wH(),R=SH(H.configExtensions);I("info","session.create.runtime_build.begin",{...Z,sessionId:G,configExtensionCount:R?.length??0});let F=Z7({sessionId:G,targetClientId:A,contributions:B,sessionConfig:X,requestCapability:$.requestCapability});I("info","session.create.start_session.begin",{...Z,sessionId:G,provider:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),model:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub")});let P=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:R,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:G,providerId:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub"),apiKey:X?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:void 0),cwd:X?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():V),workspaceRoot:X?.workspaceRoot??V,systemPrompt:X?.systemPrompt??(typeof H.systemPrompt==="string"?H.systemPrompt:""),mode:X?.mode??(H.mode==="plan"||H.mode==="yolo"?H.mode:"act"),maxIterations:X?.maxIterations??(typeof H.maxIterations==="number"?H.maxIterations:void 0),enableTools:X?.enableTools??H.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??H.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??H.enableTeams!==!1,checkpoint:X?.checkpoint??(H.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):H.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});I("info","session.create.start_session.end",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!P.result}),p4($,P.sessionId,A,"creator",{interactive:j.interactive!==!1}),I("info","session.create.read_records.begin",{...Z,sessionId:P.sessionId});let[D,O]=await Promise.all([I0($,P.sessionId),x0($,P.sessionId)]);if(I("info","session.create.read_records.end",{...Z,sessionId:P.sessionId,hasSession:!!D,hasSnapshot:!!O,elapsedMs:Math.round(performance.now()-Q)}),D)$.publish($.buildEvent("session.created",{session:D,...O?{snapshot:O}:{}},P.sessionId));return I("info","session.create.reply",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q)}),x(f,{session:D,...O?{snapshot:O}:{}})}async function bH($,f,J){let Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():f.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return b(f,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},X=j.messages!==!1;if(typeof W!=="number")return b(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(X&&!H)return b(f,"invalid_restore","sessionConfig is required when restore.messages is true");let Y=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},V=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof H?.mode==="string")V.mode=H.mode;else if(typeof Y.mode==="string")V.mode=Y.mode;if(typeof H?.systemPrompt==="string")V.systemPrompt=H.systemPrompt;else if(typeof Y.systemPrompt==="string")V.systemPrompt=Y.systemPrompt;if(H?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)V.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=f.clientId?.trim()||"hub-client",K=Q7(Y.clientContributions);if(K.length>0)EH(V,B);let R=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||wH(),F=SH(Y.configExtensions),P=Z7({sessionId:R,targetClientId:B,contributions:K,sessionConfig:H,requestCapability:$.requestCapability}),O=await new Qf().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:H,cwd:typeof H?.cwd==="string"&&H.cwd.trim()||typeof H?.workspaceRoot==="string"&&H.workspaceRoot.trim()||void 0,getSession:(y)=>$.sessionHost.getSession(y),readMessages:(y)=>$.sessionHost.readSessionMessages(y),buildStartInput:(y)=>{if(y.restoredCheckpointMetadata)V.checkpoint=y.restoredCheckpointMetadata;let T=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():y.sourceSession.workspaceRoot||y.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:y.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:F,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:R,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:y.sourceSession.provider),modelId:H?.modelId??(typeof A.model==="string"?A.model:y.sourceSession.model),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:""),cwd:H?.cwd??y.plan.cwd,workspaceRoot:H?.workspaceRoot??T,systemPrompt:H?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:H?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:H?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:H?.enableTools??Y.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:H?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(y)=>$.sessionHost.startSession(y),getStartedSessionId:(y)=>y.sessionId,readRestoredSession:(y)=>$.sessionHost.getSession(y)});if(!X)return x(f,{checkpoint:O.checkpoint});let _=O.startResult;if(!_)return b(f,"restore_failed","Checkpoint restore did not start a session");p4($,_.sessionId,B,"creator",{interactive:V.interactive!==!1});let[L,z]=await Promise.all([I0($,_.sessionId),x0($,_.sessionId)]);if(L)$.publish($.buildEvent("session.created",{session:L,...z?{snapshot:z}:{}},_.sessionId));return x(f,{session:L,...z?{snapshot:z}:{},messages:O.messages??[],checkpoint:O.checkpoint})}catch(H){if(H instanceof v0)return b(f,H.code,H.code==="session_not_found"?`Unknown session: ${Z}`:H.message);return b(f,"restore_failed",H instanceof Error?H.message:String(H))}}async function kH($,f){let J=_0(f);if(!J)return b(f,"invalid_session_attach","session.attach requires a session id");p4($,J,f.clientId?.trim()||"hub-client","participant");let Q=await I0($,J);if(Q)$.publish($.buildEvent("session.attached",{session:Q},J));return Q?x(f,{session:Q}):b(f,"session_not_found",`Unknown session: ${J}`)}async function IH($,f){let J=_0(f);if(!J)return b(f,"invalid_session_detach","session.detach requires a session id");let Q=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([I0($,J)]),W=xy(Z?.metadata)??Q,j=$.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)$.sessionState.delete(J)}d$($,(Y)=>Y.sessionId===J&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[X,H]=await Promise.all([I0($,J),x0($,J)]);return $.publish($.buildEvent("session.detached",X?{session:X,...H?{snapshot:H}:{},clientId:Q}:{clientId:Q},J)),x(f)}async function xH($,f){let J=_0(f),Q=f.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([I0($,J),Q?x0($,J):Promise.resolve(void 0)]);return Z?x(f,{session:Z,...W?{snapshot:W}:{}}):b(f,"session_not_found",`Unknown session: ${J}`)}async function gH($,f){let J=_0(f);if(!J)return b(f,"invalid_session_id","session.messages requires a session id");if(!await I0($,J))return b(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return x(f,{sessionId:J,messages:Z})}async function mH($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((W)=>d4(W,$.sessionState.get(W.sessionId)));return x(f,{sessions:Z})}async function vH($,f){let J=_0(f),Q=l4(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([I0($,J),x0($,J)]);if(W)$.publish($.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function cH($,f){let J=_0(f),Q=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),x(f,{deleted:Q})}async function uH($,f){let J=_0(f),Q=$.sessionHost.pendingPrompts;if(!Q)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return x(f,{sessionId:J,prompts:Z})}async function dH($,f){let J=_0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,W=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return x(f,X)}async function lH($,f){let J=_0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return x(f,W)}function pH($){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 my=new Set(["skills","workflows","rules","tools","mcp"]);function W7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function N2($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function vy($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function rH($){if($===void 0)return{};if(!W7($))throw Error("settings.list payload must be an object.");return{cwd:N2($,"cwd"),workspaceRoot:N2($,"workspaceRoot"),availabilityContext:W7($.availabilityContext)?$.availabilityContext:void 0}}function cy($){if(!W7($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!my.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...rH($),type:f,id:N2($,"id"),path:N2($,"path"),name:N2($,"name"),enabled:vy($,"enabled")}}class i4{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=gy("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new u$({sessionService:new I$(new k$),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:(f)=>this.publish(f),buildEvent:y1,requestCapability:(f,J,Q,Z,W)=>FH(this.ctx,f,J,Q,Z,W)},this.schedules=new x4({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let Q=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(y1(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new b4(this.schedules),this.settings=$.settingsService??new r1,$.cronOptions)this.cronService=new rf({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{MH(this.ctx,f).catch((J)=>{f7("session event handling failed",J),r4(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.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())e9(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(d$(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 f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw r4(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return LH(this.ctx,$);case"client.update":return OH(this.ctx,$);case"client.unregister":return zH(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return _H(this.ctx,$);case"session.create":return await hH(this.ctx,$,(f)=>o9(this.ctx,f));case"session.restore":return await bH(this.ctx,$,(f)=>o9(this.ctx,f));case"session.attach":return await kH(this.ctx,$);case"session.detach":return await IH(this.ctx,$);case"session.get":return await xH(this.ctx,$);case"session.messages":return await gH(this.ctx,$);case"session.list":return await mH(this.ctx,$);case"session.update":return await vH(this.ctx,$);case"session.pending_prompts":return await uH(this.ctx,$);case"session.update_pending_prompt":return await dH(this.ctx,$);case"session.remove_pending_prompt":return await lH(this.ctx,$);case"session.delete":return await cH(this.ctx,$);case"session.hook":return await TH(this.ctx,$);case"run.start":case"session.send_input":return await yH(this.ctx,$);case"run.abort":return await NH(this.ctx,$);case"capability.request":return await RH(this.ctx,$);case"approval.respond":return await GH(this.ctx,$);case"capability.respond":return UH(this.ctx,$);case"capability.progress":return DH(this.ctx,$);case"ui.notify":return this.publish(y1("ui.notify",$.payload??{})),x($);case"ui.show_window":return this.publish(y1("ui.show_window",$.payload??{})),x($);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 f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=pH($.command);if(J)this.publish(y1(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!uy(f.error.code))return;r4(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(rH($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(cy($.payload));return this.publish(y1("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let Q=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return Q.add(Z),this.listeners.set($,Q),()=>{let W=this.listeners.get($);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);d$(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(Q){f7(`listener threw while publishing ${$.event}`,Q),r4(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function uy($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as ry}from"node:crypto";import iy from"node:http";import ny from"node:net";import{URL as aH}from"node:url";import{WebSocketServer as ay}from"ws";import{captureSdkError as iH,HUB_COMMAND_SLOW_LOG_MS as dy,resolveHubCommandTimeoutMs as ly,safeJsonParse as py}from"@cline/shared";function j7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function nH($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class X7{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,Q=!1,Z=(H)=>{try{$.send(JSON.stringify(H))}catch(Y){console.error(`[hub] failed to send websocket frame: ${Y instanceof Error?Y.stack||Y.message:String(Y)}`)}},W=(H)=>{Z({kind:"event",envelope:H})},j=async(H)=>{try{let Y=JSON.parse(H.data);switch(Y.kind){case"command":{let V=performance.now(),A=!1,B=j7(Y);I("info","command.start",B);let K=setTimeout(()=>{if(A)return;I("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},dy),G=this.transport.command(Y.envelope);G.then((_)=>{if(!A)return;I(_.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message})},(_)=>{if(!A)return;I("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:_})});let R=!1,F,P,D=ly(Y.envelope.command,Y.envelope.timeoutMs);try{P=D===null?await G:await Promise.race([G,new Promise((_)=>{F=setTimeout(()=>{R=!0,iH(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${Y.envelope.command} did not complete within ${D}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:D}}),_(nH(Y,"hub_command_timeout",`Hub command ${Y.envelope.command} did not complete within ${D}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${Y.envelope.requestId}.`))},D)})])}catch(_){if(clearTimeout(K),F)clearTimeout(F);throw _}if(A=R,clearTimeout(K),F)clearTimeout(F);let O=Math.round(performance.now()-V);if(R)I("error","command.timeout",{...B,durationMs:O,timeoutMs:D});else I(P.ok?"info":"warn","command.end",{...B,durationMs:O,ok:P.ok,errorCode:P.error?.code,errorMessage:P.error?.message});if(Y.envelope.command==="client.register"&&P.ok){let L=(Y.envelope.payload??{}).clientId?.trim()||Y.envelope.clientId?.trim();if(L)J.add(L)}else if(Y.envelope.command==="client.unregister"&&P.ok){let _=Y.envelope.clientId?.trim();if(_)J.delete(_)}Z({kind:"reply",envelope:P});break}case"stream.subscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;if(f.has(V))break;let A=await this.transport.subscribe(Y.clientId,W,{sessionId:Y.sessionId});f.set(V,A);break}case"stream.unsubscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;f.get(V)?.(),f.delete(V);break}case"reply":case"event":break}}catch(Y){let V=typeof H.data==="string"?py(H.data):void 0;if(!V||V.kind!=="command"){I("error","rejected malformed websocket frame",{error:Y});return}I("error","command.error",{...j7(V),error:Y}),iH(this.telemetry,{component:"core",operation:"hub.websocket_command",error:Y,severity:"error",handled:!0,context:j7(V)}),Z({kind:"reply",envelope:nH(V,"command_failed",Y instanceof Error?Y.message:"Unknown hub error")})}},X=()=>{if(Q)return;Q=!0;for(let H of f.values())H();f.clear();for(let H of J)this.transport.command({version:"v1",command:"client.unregister",clientId:H});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",X)};return $.addEventListener("message",j),$.addEventListener("close",X),X}}class H7{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function ty($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function sy($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(Q)=>{J({data:ty(Q)})});return}$.on("close",J)},removeEventListener(){}}}function oy($){try{$.write(`HTTP/1.1 400 Bad Request\r
705
+ ${V}`:H.instructions}})}})}}function PT($,f,J,Q){let Z=J.map((W)=>[W.executor,async(...j)=>{let X=j.at(-1),H=j.slice(0,-1);return(await Q($,W.capabilityName,{executor:W.executor,args:H,context:nH(X)},f))?.result}]);return Z.length>0?Object.fromEntries(Z):void 0}function UT($,f,J,Q){if(J.length===0)return;return J.map((Z)=>({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,lifecycle:Z.lifecycle,async execute(W,j){return(await Q($,Z.capabilityName,{toolName:Z.name,input:W,context:nH(j)},f,j.emitUpdate?(H)=>{j.emitUpdate?.(AT(H))}:void 0))?.result}}))}function DT($,f,J,Q){let Z=new Map(J.map((j)=>[j.name,j])),W={};for(let j of YT){let X=Z.get(j);if(!X)continue;W[j]=async(H)=>{return(await Q($,X.capabilityName,{context:H},f))?.control}}return Object.keys(W).length>0?W:void 0}function D7($){let f=$.contributions.filter((H)=>H.kind==="toolExecutor"),J=$.contributions.filter((H)=>H.kind==="tool"),Q=$.contributions.filter((H)=>H.kind==="hook"),Z=$.contributions.find((H)=>H.kind==="compaction"),W=$.contributions.find((H)=>H.kind==="checkpoint"),j=$.contributions.find((H)=>H.kind==="mistakeLimit"),X=$.contributions.find((H)=>H.kind==="userInstructionService");return{hasClientContributions:$.contributions.length>0,toolExecutors:PT($.sessionId,$.targetClientId,f,$.requestCapability),localRuntime:{...Q.length>0?{hooks:DT($.sessionId,$.targetClientId,Q,$.requestCapability)}:{},...J.length>0?{extraTools:UT($.sessionId,$.targetClientId,J,$.requestCapability)}:{},...Z?{compaction:{...$.sessionConfig?.compaction??{},...Z.config,compact:async(H)=>{return(await $.requestCapability($.sessionId,Z.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...W?{checkpoint:{...$.sessionConfig?.checkpoint??{},...W.config,createCheckpoint:async(H)=>{return(await $.requestCapability($.sessionId,W.capabilityName,{context:H},$.targetClientId))?.result}}}:{},...j?{onConsecutiveMistakeLimitReached:async(H)=>{return(await $.requestCapability($.sessionId,j.capabilityName,{context:H},$.targetClientId))?.result}}:{},...X?{userInstructionService:FT($.sessionId,$.targetClientId,X,$.requestCapability)}:{}}}}var sH="hubCapabilityOwnerClientId";function oH($,f){$[sH]=f}function RT($){let f=$?.[sH];return typeof f==="string"&&f.trim()?f.trim():void 0}async function eH($,f,J){let Q=performance.now(),Z={command:f.command,requestId:f.requestId,clientId:f.clientId,sessionId:f.sessionId};I("info","session.create.begin",Z);let W=f.payload&&typeof f.payload==="object"?f.payload:{},j=W.metadata&&typeof W.metadata==="object"?JSON.parse(JSON.stringify(W.metadata)):{},X=W.sessionConfig&&typeof W.sessionConfig==="object"?JSON.parse(JSON.stringify(W.sessionConfig)):void 0,H=W.runtimeOptions&&typeof W.runtimeOptions==="object"?W.runtimeOptions:{};if(typeof X?.mode==="string")j.mode=X.mode;else if(typeof H.mode==="string")j.mode=H.mode;if(typeof X?.systemPrompt==="string")j.systemPrompt=X.systemPrompt;else if(typeof H.systemPrompt==="string")j.systemPrompt=H.systemPrompt;if(X?.checkpoint?.enabled===!0)j.checkpointEnabled=!0;else if(H.checkpointEnabled===!0)j.checkpointEnabled=!0;let Y=W.modelSelection&&typeof W.modelSelection==="object"?W.modelSelection:{},V=typeof W.workspaceRoot==="string"&&W.workspaceRoot.trim()?W.workspaceRoot.trim():typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():"";if(!V)return I("warn","session.create.invalid",{...Z,reason:"missing_workspace_root"}),b(f,"invalid_session_create","session.create requires workspaceRoot or cwd");let A=f.clientId?.trim()||"hub-client",B=U7(H.clientContributions);if(I("info","session.create.contributions_parsed",{...Z,clientId:A,workspaceRoot:V,cwd:typeof W.cwd==="string"?W.cwd:void 0,contributionCount:B.length}),B.length>0)oH(j,A);let K=(typeof X?.sessionId==="string"?X.sessionId.trim():"")||aH(),D=tH(H.configExtensions);I("info","session.create.runtime_build.begin",{...Z,sessionId:K,configExtensionCount:D?.length??0});let F=D7({sessionId:K,targetClientId:A,contributions:B,sessionConfig:X,requestCapability:$.requestCapability});I("info","session.create.start_session.begin",{...Z,sessionId:K,provider:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),model:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub")});let P=await $.sessionHost.startSession({source:typeof j.source==="string"?j.source:void 0,interactive:j.interactive!==!1,sessionMetadata:Object.keys(j).length>0?j:void 0,initialMessages:Array.isArray(W.initialMessages)?W.initialMessages:void 0,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:D,...F.localRuntime},capabilities:{toolExecutors:F.toolExecutors,requestToolApproval:J},config:{...X??{},sessionId:K,providerId:X?.providerId??(typeof Y.provider==="string"?Y.provider:typeof j.provider==="string"?j.provider:"hub"),modelId:X?.modelId??(typeof Y.model==="string"?Y.model:typeof j.model==="string"?j.model:"hub"),apiKey:X?.apiKey??(typeof Y.apiKey==="string"?Y.apiKey:void 0),cwd:X?.cwd??(typeof W.cwd==="string"&&W.cwd.trim()?W.cwd.trim():V),workspaceRoot:X?.workspaceRoot??V,systemPrompt:X?.systemPrompt??(typeof H.systemPrompt==="string"?H.systemPrompt:""),mode:X?.mode??(H.mode==="plan"||H.mode==="yolo"?H.mode:"act"),maxIterations:X?.maxIterations??(typeof H.maxIterations==="number"?H.maxIterations:void 0),enableTools:X?.enableTools??H.enableTools!==!1,enableSpawnAgent:X?.enableSpawnAgent??H.enableSpawn!==!1,enableAgentTeams:X?.enableAgentTeams??H.enableTeams!==!1,checkpoint:X?.checkpoint??(H.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:X?.teamName??(typeof j.teamName==="string"?j.teamName:void 0)},toolPolicies:W.toolPolicies&&typeof W.toolPolicies==="object"&&!Array.isArray(W.toolPolicies)?JSON.parse(JSON.stringify(W.toolPolicies)):H.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0});I("info","session.create.start_session.end",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q),hasImmediateResult:!!P.result}),ff($,P.sessionId,A,"creator",{interactive:j.interactive!==!1}),I("info","session.create.read_records.begin",{...Z,sessionId:P.sessionId});let[U,z]=await Promise.all([g0($,P.sessionId),v0($,P.sessionId)]);if(I("info","session.create.read_records.end",{...Z,sessionId:P.sessionId,hasSession:!!U,hasSnapshot:!!z,elapsedMs:Math.round(performance.now()-Q)}),U)$.publish($.buildEvent("session.created",{session:U,...z?{snapshot:z}:{}},P.sessionId));return I("info","session.create.reply",{...Z,sessionId:P.sessionId,elapsedMs:Math.round(performance.now()-Q)}),m(f,{session:U,...z?{snapshot:z}:{}})}async function $Y($,f,J){let Q=f.payload&&typeof f.payload==="object"?f.payload:{},Z=typeof Q.sessionId==="string"?Q.sessionId.trim():f.sessionId?.trim()||"",W=Q.checkpointRunCount;if(!Z)return b(f,"invalid_restore","session.restore requires a session id");let j=Q.restore&&typeof Q.restore==="object"?Q.restore:{},X=j.messages!==!1;if(typeof W!=="number")return b(f,"invalid_restore","checkpointRunCount must be a positive integer");try{let H=Q.sessionConfig&&typeof Q.sessionConfig==="object"?JSON.parse(JSON.stringify(Q.sessionConfig)):void 0;if(X&&!H)return b(f,"invalid_restore","sessionConfig is required when restore.messages is true");let Y=Q.runtimeOptions&&typeof Q.runtimeOptions==="object"?Q.runtimeOptions:{},V=Q.metadata&&typeof Q.metadata==="object"?JSON.parse(JSON.stringify(Q.metadata)):{};if(typeof H?.mode==="string")V.mode=H.mode;else if(typeof Y.mode==="string")V.mode=Y.mode;if(typeof H?.systemPrompt==="string")V.systemPrompt=H.systemPrompt;else if(typeof Y.systemPrompt==="string")V.systemPrompt=Y.systemPrompt;if(H?.checkpoint?.enabled===!0)V.checkpointEnabled=!0;else if(Y.checkpointEnabled===!0)V.checkpointEnabled=!0;let A=Q.modelSelection&&typeof Q.modelSelection==="object"?Q.modelSelection:{},B=f.clientId?.trim()||"hub-client",G=U7(Y.clientContributions);if(G.length>0)oH(V,B);let D=(typeof H?.sessionId==="string"?H.sessionId.trim():"")||aH(),F=tH(Y.configExtensions),P=D7({sessionId:D,targetClientId:B,contributions:G,sessionConfig:H,requestCapability:$.requestCapability}),z=await new j2().restoreCheckpoint({sessionId:Z,checkpointRunCount:W,restore:{messages:j.messages,workspace:j.workspace,omitCheckpointMessageFromSession:j.omitCheckpointMessageFromSession===!0},start:H,cwd:typeof H?.cwd==="string"&&H.cwd.trim()||typeof H?.workspaceRoot==="string"&&H.workspaceRoot.trim()||void 0,getSession:(N)=>$.sessionHost.getSession(N),readMessages:(N)=>$.sessionHost.readSessionMessages(N),buildStartInput:(N)=>{if(N.restoredCheckpointMetadata)V.checkpoint=N.restoredCheckpointMetadata;let M=typeof Q.workspaceRoot==="string"&&Q.workspaceRoot.trim()?Q.workspaceRoot.trim():typeof Q.cwd==="string"&&Q.cwd.trim()?Q.cwd.trim():N.sourceSession.workspaceRoot||N.sourceSession.cwd;return{source:typeof V.source==="string"?V.source:void 0,interactive:V.interactive!==!1,sessionMetadata:{...V,restoredFromSessionId:Z,restoredCheckpointRunCount:W},initialMessages:N.initialMessages,localRuntime:{modelCatalogDefaults:{loadLatestOnInit:!0,loadPrivateOnAuth:!0},configExtensions:F,...P.localRuntime},capabilities:{toolExecutors:P.toolExecutors,requestToolApproval:J},config:{...H??{},sessionId:D,providerId:H?.providerId??(typeof A.provider==="string"?A.provider:N.sourceSession.provider),modelId:H?.modelId??(typeof A.model==="string"?A.model:N.sourceSession.model),apiKey:H?.apiKey??(typeof A.apiKey==="string"?A.apiKey:""),cwd:H?.cwd??N.plan.cwd,workspaceRoot:H?.workspaceRoot??M,systemPrompt:H?.systemPrompt??(typeof Y.systemPrompt==="string"?Y.systemPrompt:""),mode:H?.mode??(Y.mode==="plan"||Y.mode==="yolo"?Y.mode:"act"),maxIterations:H?.maxIterations??(typeof Y.maxIterations==="number"?Y.maxIterations:void 0),enableTools:H?.enableTools??Y.enableTools!==!1,enableSpawnAgent:H?.enableSpawnAgent??Y.enableSpawn!==!1,enableAgentTeams:H?.enableAgentTeams??Y.enableTeams!==!1,checkpoint:H?.checkpoint??(Y.checkpointEnabled===!0?{enabled:!0}:void 0),teamName:H?.teamName??(typeof V.teamName==="string"?V.teamName:void 0)},toolPolicies:Q.toolPolicies&&typeof Q.toolPolicies==="object"&&!Array.isArray(Q.toolPolicies)?JSON.parse(JSON.stringify(Q.toolPolicies)):Y.autoApproveTools===!0?{"*":{autoApprove:!0}}:void 0}},startSession:(N)=>$.sessionHost.startSession(N),getStartedSessionId:(N)=>N.sessionId,readRestoredSession:(N)=>$.sessionHost.getSession(N)});if(!X)return m(f,{checkpoint:z.checkpoint});let _=z.startResult;if(!_)return b(f,"restore_failed","Checkpoint restore did not start a session");ff($,_.sessionId,B,"creator",{interactive:V.interactive!==!1});let[R,L]=await Promise.all([g0($,_.sessionId),v0($,_.sessionId)]);if(R)$.publish($.buildEvent("session.created",{session:R,...L?{snapshot:L}:{}},_.sessionId));return m(f,{session:R,...L?{snapshot:L}:{},messages:z.messages??[],checkpoint:z.checkpoint})}catch(H){if(H instanceof d0)return b(f,H.code,H.code==="session_not_found"?`Unknown session: ${Z}`:H.message);return b(f,"restore_failed",H instanceof Error?H.message:String(H))}}async function fY($,f){let J=T0(f);if(!J)return b(f,"invalid_session_attach","session.attach requires a session id");ff($,J,f.clientId?.trim()||"hub-client","participant");let Q=await g0($,J);if(Q)$.publish($.buildEvent("session.attached",{session:Q},J));return Q?m(f,{session:Q}):b(f,"session_not_found",`Unknown session: ${J}`)}async function JY($,f){let J=T0(f);if(!J)return b(f,"invalid_session_detach","session.detach requires a session id");let Q=f.clientId?.trim()||"hub-client",[Z]=await Promise.all([g0($,J)]),W=RT(Z?.metadata)??Q,j=$.sessionState.get(J);if(j){if(j.participants.delete(Q),j.createdByClientId===Q)j.createdByClientId=W;if(j.participants.size===0)$.sessionState.delete(J)}p$($,(Y)=>Y.sessionId===J&&Y.targetClientId===Q,`Capability owner client ${Q} detached before request was resolved.`);let[X,H]=await Promise.all([g0($,J),v0($,J)]);return $.publish($.buildEvent("session.detached",X?{session:X,...H?{snapshot:H}:{},clientId:Q}:{clientId:Q},J)),m(f)}async function QY($,f){let J=T0(f),Q=f.payload?.includeSnapshot===!0,[Z,W]=await Promise.all([g0($,J),Q?v0($,J):Promise.resolve(void 0)]);return Z?m(f,{session:Z,...W?{snapshot:W}:{}}):b(f,"session_not_found",`Unknown session: ${J}`)}async function ZY($,f){let J=T0(f);if(!J)return b(f,"invalid_session_id","session.messages requires a session id");if(!await g0($,J))return b(f,"session_not_found",`Unknown session: ${J}`);let Z=await $.sessionHost.readSessionMessages(J);return m(f,{sessionId:J,messages:Z})}async function WY($,f){let J=typeof f.payload?.limit==="number"?f.payload.limit:200,Z=(await $.sessionHost.listSessions(J)).map((W)=>e6(W,$.sessionState.get(W.sessionId)));return m(f,{sessions:Z})}async function jY($,f){let J=T0(f),Q=$f(f.payload?.metadata),Z=await $.sessionHost.updateSession(J,{metadata:Q}),[W,j]=await Promise.all([g0($,J),v0($,J)]);if(W)$.publish($.buildEvent("session.updated",{session:W,...j?{snapshot:j}:{}},J));return{version:f.version,requestId:f.requestId,ok:Z.updated,payload:{updated:Z.updated,session:W,...j?{snapshot:j}:{}}}}async function XY($,f){let J=T0(f),Q=await $.sessionHost.deleteSession(J);return $.sessionState.delete(J),m(f,{deleted:Q})}async function HY($,f){let J=T0(f),Q=$.sessionHost.pendingPrompts;if(!Q)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let Z=await Q.list({sessionId:J});return m(f,{sessionId:J,prompts:Z})}async function YY($,f){let J=T0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=typeof f.payload?.prompt==="string"?f.payload.prompt:void 0,W=f.payload?.delivery==="queue"||f.payload?.delivery==="steer"?f.payload.delivery:void 0,j=$.sessionHost.pendingPrompts;if(!j)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let X=await j.update({sessionId:J,promptId:Q,prompt:Z,delivery:W});return m(f,X)}async function VY($,f){let J=T0(f),Q=typeof f.payload?.promptId==="string"?f.payload.promptId.trim():"",Z=$.sessionHost.pendingPrompts;if(!Z)return b(f,"pending_prompts_unavailable","Pending prompt service is not available.");let W=await Z.delete({sessionId:J,promptId:Q});return m(f,W)}function AY($){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 OT=new Set(["skills","workflows","rules","tools","mcp"]);function R7($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function y8($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="string")throw Error(`settings payload '${f}' must be a string.`);return J}function zT($,f){let J=$[f];if(J===void 0)return;if(typeof J!=="boolean")throw Error(`settings payload '${f}' must be a boolean.`);return J}function BY($){if($===void 0)return{};if(!R7($))throw Error("settings.list payload must be an object.");return{cwd:y8($,"cwd"),workspaceRoot:y8($,"workspaceRoot"),availabilityContext:R7($.availabilityContext)?$.availabilityContext:void 0}}function _T($){if(!R7($))throw Error("settings.toggle payload must be an object.");let{type:f}=$;if(typeof f!=="string"||!OT.has(f))throw Error("settings.toggle payload 'type' must be one of: skills, workflows, rules, tools, mcp.");return{...BY($),type:f,id:y8($,"id"),path:y8($,"path"),name:y8($,"name"),enabled:zT($,"enabled")}}class Qf{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=LT("hub_");ctx;constructor($){this.options=$;if(this.sessionHost=$.sessionHost??new l$({sessionService:new m$(new x$),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:(f)=>this.publish(f),buildEvent:M1,requestCapability:(f,J,Q,Z,W)=>IH(this.ctx,f,J,Q,Z,W)},this.schedules=new i6({...$.scheduleOptions,runtimeHandlers:$.runtimeHandlers,eventPublisher:(f,J)=>{let Q=f==="schedule.execution.completed"?"schedule.execution_completed":f==="schedule.execution.failed"?"schedule.execution_failed":void 0;if(!Q)return;this.publish(M1(Q,J&&typeof J==="object"?J:void 0))}}),this.scheduleCommands=new l6(this.schedules),this.settings=$.settingsService??new a1,$.cronOptions)this.cronService=new t2({runtimeHandlers:$.runtimeHandlers,...$.cronOptions});this.sessionHost.subscribe((f)=>{iH(this.ctx,f).catch((J)=>{F7("session event handling failed",J),Jf(this.options.telemetry,{component:"core",operation:"hub.session_event_project",error:J,severity:"error",handled:!0,context:{eventType:f.type,sessionId:f.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())G7(this.ctx,$,{approved:!1,reason:"Hub shutting down before approval was resolved."});if(p$(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 f=await this.dispatchCommand($);return this.captureFailedReply($,f),f}catch(f){throw Jf(this.options.telemetry,{component:"core",operation:"hub.command",error:f,severity:"error",handled:!1,context:this.commandTelemetryContext($)}),f}}async dispatchCommand($){switch($.command){case"client.register":return vH(this.ctx,$);case"client.update":return uH(this.ctx,$);case"client.unregister":return cH(this.ctx,$,(f)=>{this.listeners.delete(f),this.detachClientFromSessions(f)});case"client.list":return dH(this.ctx,$);case"session.create":return await eH(this.ctx,$,(f)=>B7(this.ctx,f));case"session.restore":return await $Y(this.ctx,$,(f)=>B7(this.ctx,f));case"session.attach":return await fY(this.ctx,$);case"session.detach":return await JY(this.ctx,$);case"session.get":return await QY(this.ctx,$);case"session.messages":return await ZY(this.ctx,$);case"session.list":return await WY(this.ctx,$);case"session.update":return await jY(this.ctx,$);case"session.pending_prompts":return await HY(this.ctx,$);case"session.update_pending_prompt":return await YY(this.ctx,$);case"session.remove_pending_prompt":return await VY(this.ctx,$);case"session.delete":return await XY(this.ctx,$);case"session.hook":return await rH(this.ctx,$);case"run.start":case"session.send_input":return await lH(this.ctx,$);case"run.abort":return await pH(this.ctx,$);case"capability.request":return await mH(this.ctx,$);case"approval.respond":return await bH(this.ctx,$);case"capability.respond":return gH(this.ctx,$);case"capability.progress":return xH(this.ctx,$);case"ui.notify":return this.publish(M1("ui.notify",$.payload??{})),m($);case"ui.show_window":return this.publish(M1("ui.show_window",$.payload??{})),m($);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 f=await this.scheduleCommands.handleCommand($);if(f.ok){let J=AY($.command);if(J)this.publish(M1(J,f.payload))}return f}}}captureFailedReply($,f){if(f.ok||!f.error||!NT(f.error.code))return;Jf(this.options.telemetry,{component:"core",operation:"hub.command_reply",error:Error(f.error.message),severity:f.error.code==="session_not_found"?"warn":"error",handled:!0,context:{...this.commandTelemetryContext($),errorCode:f.error.code}})}commandTelemetryContext($){return{command:$.command,requestId:$.requestId,clientId:$.clientId,sessionId:typeof $.payload?.sessionId==="string"?$.payload.sessionId:$.sessionId}}async handleSettingsList($){try{let f=await this.settings.list(BY($.payload));return{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_list_failed",message:f instanceof Error?f.message:String(f)}}}}async handleSettingsToggle($){try{let f=await this.settings.toggle(_T($.payload));return this.publish(M1("settings.changed",{types:f.changedTypes,snapshot:f.snapshot})),{version:$.version,requestId:$.requestId,ok:!0,payload:{snapshot:f.snapshot,changedTypes:f.changedTypes}}}catch(f){return{version:$.version,requestId:$.requestId,ok:!1,error:{code:"settings_toggle_failed",message:f instanceof Error?f.message:String(f)}}}}subscribe($,f,J){let Q=this.listeners.get($)??new Set,Z={sessionId:J?.sessionId,listener:f};return Q.add(Z),this.listeners.set($,Q),()=>{let W=this.listeners.get($);if(!W)return;if(W.delete(Z),W.size===0)this.listeners.delete($)}}detachClientFromSessions($){for(let[f,J]of this.sessionState.entries())if(J.participants.delete($),J.participants.size===0)this.sessionState.delete(f);p$(this.ctx,(f)=>f.targetClientId===$,`Capability owner client ${$} disconnected before request was resolved.`)}publish($){for(let f of this.listeners.values())for(let J of f){if(J.sessionId&&J.sessionId!==$.sessionId)continue;try{J.listener($)}catch(Q){F7(`listener threw while publishing ${$.event}`,Q),Jf(this.options.telemetry,{component:"core",operation:"hub.publish",error:Q,severity:"warn",handled:!0,context:{event:$.event,sessionId:$.sessionId}})}}}}function NT($){return $==="session_not_found"||$==="session_messages_not_found"||$==="hub_command_timeout"||$.endsWith("_failed")}import{timingSafeEqual as yT}from"node:crypto";import wT from"node:http";import ST from"node:net";import{URL as FY}from"node:url";import{WebSocketServer as hT}from"ws";import{captureSdkError as GY,HUB_COMMAND_SLOW_LOG_MS as TT,resolveHubCommandTimeoutMs as MT,safeJsonParse as qT}from"@cline/shared";function L7($){return{command:$.envelope.command,requestId:$.envelope.requestId,clientId:$.envelope.clientId,sessionId:$.envelope.sessionId}}function KY($,f,J){return{version:$.envelope.version,requestId:$.envelope.requestId,ok:!1,error:{code:f,message:J}}}class O7{transport;telemetry;constructor($,f){this.transport=$;this.telemetry=f}attach($){let f=new Map,J=new Set,Q=!1,Z=(H)=>{try{$.send(JSON.stringify(H))}catch(Y){console.error(`[hub] failed to send websocket frame: ${Y instanceof Error?Y.stack||Y.message:String(Y)}`)}},W=(H)=>{Z({kind:"event",envelope:H})},j=async(H)=>{try{let Y=JSON.parse(H.data);switch(Y.kind){case"command":{let V=performance.now(),A=!1,B=L7(Y);I("info","command.start",B);let G=setTimeout(()=>{if(A)return;I("warn","command.slow",{...B,elapsedMs:Math.round(performance.now()-V)})},TT),K=this.transport.command(Y.envelope);K.then((_)=>{if(!A)return;I(_.ok?"warn":"error","command.late_end",{...B,elapsedMs:Math.round(performance.now()-V),ok:_.ok,errorCode:_.error?.code,errorMessage:_.error?.message})},(_)=>{if(!A)return;I("error","command.late_error",{...B,elapsedMs:Math.round(performance.now()-V),error:_})});let D=!1,F,P,U=MT(Y.envelope.command,Y.envelope.timeoutMs);try{P=U===null?await K:await Promise.race([K,new Promise((_)=>{F=setTimeout(()=>{D=!0,GY(this.telemetry,{component:"core",operation:"hub.command_timeout",error:Error(`Hub command ${Y.envelope.command} did not complete within ${U}ms.`),severity:"error",handled:!0,context:{...B,timeoutMs:U}}),_(KY(Y,"hub_command_timeout",`Hub command ${Y.envelope.command} did not complete within ${U}ms. Check hub-daemon.log for command.start/command.slow logs with requestId ${Y.envelope.requestId}.`))},U)})])}catch(_){if(clearTimeout(G),F)clearTimeout(F);throw _}if(A=D,clearTimeout(G),F)clearTimeout(F);let z=Math.round(performance.now()-V);if(D)I("error","command.timeout",{...B,durationMs:z,timeoutMs:U});else I(P.ok?"info":"warn","command.end",{...B,durationMs:z,ok:P.ok,errorCode:P.error?.code,errorMessage:P.error?.message});if(Y.envelope.command==="client.register"&&P.ok){let R=(Y.envelope.payload??{}).clientId?.trim()||Y.envelope.clientId?.trim();if(R)J.add(R)}else if(Y.envelope.command==="client.unregister"&&P.ok){let _=Y.envelope.clientId?.trim();if(_)J.delete(_)}Z({kind:"reply",envelope:P});break}case"stream.subscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;if(f.has(V))break;let A=await this.transport.subscribe(Y.clientId,W,{sessionId:Y.sessionId});f.set(V,A);break}case"stream.unsubscribe":{let V=`${Y.clientId}:${Y.sessionId??"*"}`;f.get(V)?.(),f.delete(V);break}case"reply":case"event":break}}catch(Y){let V=typeof H.data==="string"?qT(H.data):void 0;if(!V||V.kind!=="command"){I("error","rejected malformed websocket frame",{error:Y});return}I("error","command.error",{...L7(V),error:Y}),GY(this.telemetry,{component:"core",operation:"hub.websocket_command",error:Y,severity:"error",handled:!0,context:L7(V)}),Z({kind:"reply",envelope:KY(V,"command_failed",Y instanceof Error?Y.message:"Unknown hub error")})}},X=()=>{if(Q)return;Q=!0;for(let H of f.values())H();f.clear();for(let H of J)this.transport.command({version:"v1",command:"client.unregister",clientId:H});J.clear(),$.removeEventListener("message",j),$.removeEventListener("close",X)};return $.addEventListener("message",j),$.addEventListener("close",X),X}}class z7{transport;constructor($){this.transport=$}command($){return this.transport.handleCommand($)}subscribe($,f,J){return this.transport.subscribe($,f,J)}}function CT($){if(typeof $==="string")return $;if($ instanceof Uint8Array)return Buffer.from($).toString();if($ instanceof ArrayBuffer)return Buffer.from($).toString();if(Array.isArray($))return Buffer.concat($.map((f)=>Buffer.from(f))).toString();return String($)}function ET($){return{send(f){$.send(f)},addEventListener(f,J){if(f==="message"){$.on("message",(Q)=>{J({data:CT(Q)})});return}$.on("close",J)},removeEventListener(){}}}function bT($){try{$.write(`HTTP/1.1 400 Bad Request\r
706
706
  Connection: close\r
707
707
  Content-Length: 0\r
708
708
  \r
709
- `),$.end()}catch{$.destroy()}}function ey($){try{$.write(`HTTP/1.1 401 Unauthorized\r
709
+ `),$.end()}catch{$.destroy()}}function kT($){try{$.write(`HTTP/1.1 401 Unauthorized\r
710
710
  Connection: close\r
711
711
  Content-Length: 0\r
712
712
  \r
713
- `),$.end()}catch{$.destroy()}}function tH($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),Q=Buffer.from(f,"utf8");return J.length===Q.length&&ry(J,Q)}function sH($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,W.code=J;if($ instanceof Error&&$.stack)W.stack=`${W.name}: ${W.message}
714
- Caused by: ${$.stack}`;return W}async function $N($){return await new Promise((f,J)=>{let Q=ny.createServer();Q.once("error",J),Q.listen(0,$,()=>{let Z=Q.address();if(!Z||typeof Z==="string"){Q.close(()=>J(Error("Failed to resolve free port")));return}let W=Z.port;Q.close((j)=>{if(j){J(j);return}f(W)})})})}function fN($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var Y7=new Map,oH="cline-hub-auth.",JN=30000;function eH($){return Array.isArray($)?$.join(","):$??""}function QN($){let f=eH($).trim();return/^Bearer\s+(.+)$/i.exec(f)?.[1]?.trim()||null}function ZN($){for(let f of eH($).split(",")){let J=f.trim();if(J.startsWith(oH))return J.slice(oH.length).trim()||null}return null}async function V7($){let f=$.owner??A1(),J=$.host??"127.0.0.1",Q=$.pathname??"/hub",Z=$.port??t8(),W=Z===0?await $N(J):Z,j=W,X=j$(J,W,Q),H=i1(),Y=cW(),V=new i4($);await V.start();let A=new X7(new H7(V),$.telemetry),B=new Set,K=new Date().toISOString(),G={protocolVersion:"v1",buildId:H,pid:process.pid,startedAt:K},R=new Set,F,P,D=async()=>{if(P)return P;return P=(async()=>{if(F)clearInterval(F),F=void 0;for(let z of R)z.terminate?.();R.clear();for(let z of B)z();if(B.clear(),await new Promise((z,y)=>{_.close((T)=>{if(T){y(T);return}z()})}),await new Promise((z,y)=>{O.close((T)=>{if(T){y(T);return}z()})}),await V.stop(),(await B0(f.discoveryPath))?.url===X)await n0(f.discoveryPath)})(),P},O=iy.createServer((L,z)=>{if((L.url??"/")==="/health"){let T=JSON.stringify({hubId:V.getHubId(),...G,authToken:"",host:J,port:j,url:X,updatedAt:new Date().toISOString()});z.statusCode=200,z.setHeader("content-type","application/json"),z.end(T);return}if((L.url??"/")==="/version"){z.statusCode=200,z.setHeader("content-type","application/json"),z.end(JSON.stringify(G));return}if(new aH(L.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&L.method==="POST"){if(!tH(QN(L.headers.authorization),Y)){z.statusCode=401,z.end("Unauthorized");return}z.statusCode=202,z.setHeader("content-type","application/json"),z.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{D()});return}z.statusCode=404,z.end("Not found")}),_=new ay({noServer:!0});F=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)}}},JN),O.on("upgrade",(L,z,y)=>{if(new aH(L.url??"/",`http://${J}:${j}`).pathname!==Q){z.destroy();return}if(!tH(ZN(L.headers["sec-websocket-protocol"]),Y)){ey(z);return}try{_.handleUpgrade(L,z,y,(e)=>{let $0=e;$0.isAlive=!0,$0.on("pong",()=>{$0.isAlive=!0}),R.add($0);let a=A.attach(sy(e));B.add(a),e.once("close",()=>{R.delete($0),a(),B.delete(a)})})}catch{oy(z)}});try{await new Promise((L,z)=>{O.once("error",(y)=>{z(sH(y,{host:J,port:W,pathname:Q}))}),O.listen(W,J,()=>{let y=O.address();if(!y||typeof y==="string"){z(sH(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=y.port,X=j$(J,j,Q),L()})})}catch(L){if(F)clearInterval(F),F=void 0;throw await V.stop().catch(()=>{return}),L}return await uW(f.discoveryPath,{hubId:V.getHubId(),protocolVersion:"v1",buildId:H,authToken:Y,host:J,port:j,url:X,pid:process.pid,startedAt:K,updatedAt:K}),{host:J,port:j,url:X,authToken:Y,close:D}}async function $Y($){let f=$.owner??A1(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",Z=$.port??t8(),W=$.pathname??"/hub",j=j$(Q,Z,W),X=f.discoveryPath,H=(V)=>{if(!J)n1(V.url,V.authToken);return V},Y=Y7.get(X);if(Y){let V=await Y;if(V.url===j)return H({server:V,url:V.url,authToken:V.authToken,action:"reuse"})}return await dW(f.discoveryPath,async()=>{let V=await B0(f.discoveryPath);if(V?.url&&(V.url===j||$.allowPortFallback===!0)){let G=await F0(V.url);if(G?.url&&await E$(G.url,{authToken:V.authToken}))return H({url:G.url,authToken:V.authToken,action:"reuse"})}if((await F0(j))?.url||V?.url)await n0(f.discoveryPath);let K=async(G)=>{let R=V7({...G,owner:f});Y7.set(X,R);try{let F=await R;return H({server:F,url:F.url,authToken:F.authToken,action:"started"})}catch(F){throw Y7.delete(X),F}};try{return await K($)}catch(G){if(!$.allowPortFallback||!fN(G))throw G;return await K({...$,port:0})}})}async function _c($){let f=C$({host:$.host,port:$.port,pathname:$.pathname});return await V7({...$,...f,owner:D0()})}async function yc($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=C$({host:$.host,port:$.port,pathname:$.pathname});return await $Y({...$,...J,allowPortFallback:$.allowPortFallback??!f,owner:D0()})}A7();import{buildRemoteConfigSessionBlobUploadMetadata as JY,clearRemoteConfigSessionBlobUpload as WN,createClineTelemetryServiceConfig as jN,createSessionId as XN,createRemoteConfigSessionMessagesArtifactUploader as HN,prepareRemoteConfigRuntime as YN,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as QY,readRemoteConfigSessionBlobUploadMetadata as VN,registerRemoteConfigSessionBlobUpload as ZY}from"@cline/shared";function AN($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return _1(jN(J)).telemetry}function BN(){let $=HN();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function KN($){let f=await YN($),J=AN(f,$),Q=[f.pluginDefinition],Z=f.claims?.subject,W=JY(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:Q,telemetry:J,applyToStartSessionInput(X){let H=X.config.extensions??[],Y=X.config.telemetry,V=W?X.config.sessionId?.trim()||XN():X.config.sessionId;if(V&&W)j=V;let A=V&&W?ZY(V,f.bundle?.remoteConfig,Z):void 0,B=A?{...X.sessionMetadata??{},[QY]:A}:X.sessionMetadata;return{...X,...B?{sessionMetadata:B}:{},config:{...X.config,...V?{sessionId:V}:{},extensions:[...H,...Q],telemetry:J??Y}}},async dispose(){if(j)WN(j)}}}import{mkdir as GN,readFile as PN,unlink as FN,writeFile as DN}from"node:fs/promises";import{join as WY}from"node:path";function RN($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function UN($){return new Promise((f)=>setTimeout(f,$))}async function B7($){try{await FN($)}catch{}}async function LN($,f={}){let J=f.approvalDir?.trim(),Q=f.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await GN(J,{recursive:!0});let Z=RN(`${$.toolCallId}`),W=WY(J,`${Q}.request.${Z}.json`),j=WY(J,`${Q}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await DN(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
715
- `,"utf8");let H=f.timeoutMs??300000,Y=f.pollIntervalMs??200,V=Date.now();while(Date.now()-V<H){try{let A=await PN(j,"utf8"),B=JSON.parse(A),K={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([B7(j),B7(W)]),K}catch{}await UN(Y)}return await B7(W),{approved:!1,reason:"Tool approval request timed out"}}Z$();import*as W0 from"@cline/llms";import{getClineEnvironmentConfig as ON,isOAuthProviderId as zN}from"@cline/shared";function _N($){return $.apiKey??$.auth?.apiKey}function yN($){return($.auth?.accessToken?.trim()??"").length>0}function jY($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function NN($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function TN($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of $)J=J*31+Q.charCodeAt(0)>>>0;return f[J%f.length]}function XY($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>OX(f,J))}async function MN($,f){let J=await W0.getModelsForProvider($);if(!f)return J;let Q=await x6($,{loadPrivateOnAuth:!0,failOnError:!1},f);return Q?.knownModels?{...J,...Q.knownModels}:J}function K7($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function qN($){if(!$?.length)return;return[...new Set($)]}function wN($,f){return qN([...$??[],...f??[]])}function SN($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function HY($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function G7($,f){let J=f?.includes("vision")??!1,Q=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function YY($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await m2($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function VY($,f){let J=$.read(),Q=!1;if(J.providers[f])delete J.providers[f],Q=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,Q=!0;if(Q)$.write(J);W0.unregisterProvider(f)}async function CN($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!Q&&!Z){let G=U1($);if((await ff(G)).providers[J]){let F=await BY($,{providerId:J});return{providerId:J,settingsPath:F.settingsPath,modelsPath:F.modelsPath,modelsCount:0}}return VY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:G,modelsCount:0}}if(W0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=f.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=K7(f.models),X=f.modelsSourceUrl?.trim(),H=await YY({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(H.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&H.includes(f.defaultModelId.trim())?f.defaultModelId.trim():H[0],V=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,A=HY(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:A,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=U1($),K=await ff(B);return K.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:V,modelsSourceUrl:X},models:G7(H,V)},await y4(B,K),F2(J,K.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:H.length}}async function AY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=U1($),Z=await ff(Q),W=Z.providers[J];if(!W){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let L=f.modelsSourceUrl?.trim(),z=K7(f.models)[0]??_.model?.trim();if(!z&&!L)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:f.name?.trim()||jY(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:z,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:z?G7([z],_.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??W.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let H=f.capabilities===void 0?W.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?W.provider.protocol:f.protocol??void 0,V=f.client===void 0?W.provider.client:f.client??void 0,A=K7(f.models),B=f.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,K=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,G=Object.keys(W.models??{}).map((_)=>_.trim()).filter(Boolean),R=await YY({providerId:J,explicitModels:A,modelsSourceUrl:B,fallbackModelIds:G,shouldRecompute:K});if(R.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let F=f.defaultModelId===void 0?W.provider.defaultModelId?.trim():f.defaultModelId?.trim(),P=F&&R.includes(F)?F:R[0],O={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:P};if(Y)O.protocol=Y;else delete O.protocol;if(V)O.client=V;else delete O.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)O.apiKey=_;else delete O.apiKey}if(f.headers!==void 0){let _=HY(f.headers);if(_)O.headers=_;else delete O.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")O.timeout=f.timeoutMs;else delete O.timeout;return $.saveProviderSettings(O,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:P,protocol:Y,client:V,capabilities:H,modelsSourceUrl:B},models:G7(R,H)},await y4(Q,Z),F2(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:R.length}}async function BY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=U1($),Z=await ff(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await y4(Q,Z),W0.unregisterProvider(J),VY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q}}async function EN($){let f=$.read(),J=W0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,X]=await Promise.all([W0.getProvider(W),W0.getModelsForProvider(W)]),H=XY(X),Y=f.providers[W]?.settings,V=j?.name??jY(W),A=wN(j?.capabilities,Y?.capabilities);return{provider:{id:W,name:V,models:H.length,color:TN(W),letter:NN(V),enabled:Boolean(Y),apiKey:Y?_N(Y):void 0,oauthAccessTokenPresent:Y?yN(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:H},rank:SN(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:$.getFilePath()}}async function hN($,f){let J=$.trim(),Q=await MN(J,f),Z=XY(Q);return{providerId:J,models:Z}}function bN($,f){let J=f.providerId.trim();if(f.enabled===!1){let W=$.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return $.write(W),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,W)&&typeof f[W]==="string")if(f[W].trim().length===0)delete Z[W];else Z[W]=f[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,W))Z[W]=f[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,W)&&f[W]!=null)Z[W]={...typeof Z[W]==="object"&&Z[W]!=null?Z[W]:{},...f[W]};return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function kN($,f){let J=f.trim(),Q=$.getProviderSettings(J),W=W0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),X=v2(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!X)return{providerId:J,refreshed:!1};let H=await AY($,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:X,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:H.modelsCount}}function IN($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function xN($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function gN($,f,J){let Q=e4({onPrompt:async(Z)=>Z.defaultValue??"",openUrl:J,onOpenUrlError:({error:Z})=>{throw Z instanceof Error?Z:Error(String(Z))}});if($==="cline")return b2({apiBaseUrl:f?.baseUrl?.trim()||ON().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Q});if($==="oca")return g2({mode:f?.oca?.mode,callbacks:Q});return I2(Q)}function mN($,f,J,Q){let Z={...J?.auth??{},accessToken:xN(f,Q),refreshToken:Q.refresh,accountId:Q.accountId,expiresAt:Q.expires},W={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(W,{tokenSource:"oauth"}),W}function vN($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}var cN=new Set(["ollama","lmstudio","litellm"]);function uN($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return cN.has($)}function dN($){let f=W0.normalizeProviderId($);if(zN(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=W0.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(uN(f,J))Z.baseUrl={defaultValue:Q};return{providerId:f,authMethod:"api-key",fields:Z}}R0();c4();import{appendFileSync as lN,existsSync as P7,mkdirSync as pN,readFileSync as rN,renameSync as iN,unlinkSync as nN,writeFileSync as aN}from"node:fs";import{join as F7}from"node:path";import{resolveTeamDataDir as tN}from"@cline/shared/storage";function sN($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class KY{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=sN($.teamName),J=$.baseDir?.trim()||tN();this.dirPath=F7(J,f),this.statePath=F7(this.dirPath,"state.json"),this.taskHistoryPath=F7(this.dirPath,"task-history.jsonl")}loadState(){if(!P7(this.statePath))return;try{let $=rN(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return Mj(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;aN(J,`${JSON.stringify(f,null,2)}
716
- `,"utf8"),iN(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),lN(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
717
- `,"utf8")}ensureDir(){if(!P7(this.dirPath))pN(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(P7(this.statePath))nN(this.statePath)}}import{z as q}from"zod";var GY=q.object({workspaceRoot:q.string().min(1),cwd:q.string().optional(),provider:q.string().min(1),model:q.string().min(1),mode:q.enum(["act","plan"]).default("act"),apiKey:q.string(),systemPrompt:q.string().optional(),rules:q.string().optional(),maxIterations:q.number().int().positive().optional(),enableTools:q.boolean(),enableSpawn:q.boolean().optional(),enableTeams:q.boolean().optional(),autoApproveTools:q.boolean().optional(),missionStepInterval:q.number().int().positive().optional(),missionTimeIntervalMs:q.number().int().positive().optional()}),PY=q.enum(["idle","starting","running","stopping","completed","cancelled","failed","error"]),FY=q.enum(["user","assistant","tool","system","status","error"]),DY=q.object({id:q.string().min(1),sessionId:q.string().nullable(),role:FY,content:q.string(),createdAt:q.number().int().nonnegative(),meta:q.object({stream:q.enum(["stdout","stderr"]).optional(),toolName:q.string().optional(),iteration:q.number().int().nonnegative().optional(),agentId:q.string().optional(),conversationId:q.string().optional(),hookEventName:q.string().optional(),inputTokens:q.number().int().nonnegative().optional(),outputTokens:q.number().int().nonnegative().optional(),checkpoint:q.object({ref:q.string(),createdAt:q.number().int().nonnegative(),runCount:q.number().int().positive(),kind:q.enum(["stash","commit"]).optional()}).optional()}).optional()}),RY=q.object({toolCalls:q.number().int().nonnegative(),tokensIn:q.number().int().nonnegative(),tokensOut:q.number().int().nonnegative()}),oN=q.object({sessionId:q.string().nullable(),status:PY,config:GY,messages:q.array(DY),rawTranscript:q.string(),error:q.string().nullable(),summary:RY});var eN=bW;import{Agent as dd,createAgentRuntime as ld}from"@cline/agents";import{getClineEnvironmentConfig as $T}from"@cline/shared";var fT=5000,LY={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 JT($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function UY($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function QT($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],Q=Array.isArray(f.free)?f.free:[],Z=J.map(UY).filter((j)=>j!==null),W=Q.map(UY).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function ZT($){let f=$.baseUrl?.trim();if(f)return f;let J=$T().apiBaseUrl;try{return($.providerSettingsManager??new c$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function WT($,f,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await $(f,{signal:Q.signal})}finally{clearTimeout(Z)}}async function jT($={}){try{let f=ZT($),J=$.fetchImpl??fetch,Q=await WT(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??fT);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=QT(Z);if(W)return W}catch{}return JT(LY)}import{readFile as XT}from"node:fs/promises";import HT from"node:path";function YT($){return $}async function VT($){let f=HT.resolve($),J=await XT(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${W}`)}return AT(Q,f)}function AT($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as _Y,createHandler as GT,createHandlerAsync as PT,getProviderCollection as FT,hasProvider as yY,registerAsyncHandler as DT,registerHandler as RT,registerModel as UT,registerProvider as NY}from"@cline/llms";function OY($){return $?{...$}:{}}function BT($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function KT($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function zY($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class D7{providers=new Map;register($){KT($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...OY($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:BT($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...OY($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class R7{configuredProviders=new D7;constructor($){this.applyConfig($)}createHandler($){return GT(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return PT(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(NY($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)RT($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)DT($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);NY({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){UT($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[..._Y]}async getBuiltInProviders(){return(await Promise.all(_Y.map((f)=>FT(f)))).filter((f)=>f!==void 0).map((f)=>zY({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=yY(f.id),Q=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof Q==="string"&&yY(Q);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function LT($){return new R7($)}i9();async function Mu(){return Promise.resolve().then(() => (A7(),fY))}export{uW as writeHubDiscovery,u1 as writeGlobalSettings,dW as withHubStartupLock,E$ as verifyHubConnection,Sf as updateMcpServerOAuthState,AY as updateLocalProvider,s9 as truncateNotificationBody,bJ as toggleDisabledTool,X4 as toTeamProgressLifecycleEvent,f$ as toProviderConfig,dD as toHubHealthUrl,D9 as toHookConfigFileName,B4 as summarizeUsageFromMessages,pR as stopLocalHubServerGracefully,$$ as startLocalOAuthServer,V7 as startHubWebSocketServer,_c as startHubServer,tY as startClineDeviceAuth,aJ as splitCoreSessionConfig,s8 as spawnDetachedHubServerWithRetry,yR as spawnDetachedHubServer,uG as setTelemetryOptOutGlobally,qf as setMcpServerDisabled,T3 as setDisabledTools,pG as setDisabledPlugin,Um as sendHubCommand,bN as saveLocalProviderSettings,mN as saveLocalProviderOAuthCredentials,nf as sanitizeSessionToken,VQ as safeParseSettings,HA as safeCreateProviderConfig,C4 as runSubprocessEvent,h4 as runHook,iZ as reviveTeamStateDates,Jj as restartLocalHubIfIdleAfterStartupTimeout,$h as resolveWorkspaceHubOwnerContext,$J as resolveWorkflowsConfigSearchPaths,o6 as resolveSkillsConfigSearchPaths,D0 as resolveSharedHubOwnerContext,X_ as resolveSessionBackend,e6 as resolveRulesConfigSearchPaths,x6 as resolveProviderConfig,rJ as resolvePluginConfigSearchPaths,T$ as resolveMcpServerRegistrations,vN as resolveLocalClineAuthToken,$y as resolveHubUrl,A1 as resolveHubOwnerContext,C$ as resolveHubEndpointOptions,i1 as resolveHubBuildId,P9 as resolveHooksConfigSearchPaths,r0 as resolveDisabledToolNames,E8 as resolveDisabledPluginPaths,w0 as resolveDefaultMcpSettingsPath,t8 as resolveDefaultHubPort,$R as resolveDefaultHubPathname,eD as resolveDefaultHubHost,sZ as resolveCoreSelectedToolIds,g5 as resolveCompatibleLocalHubUrl,pE as resolveClineDir,E5 as resolveClineDataDir,g8 as resolveAndLoadAgentPlugins,If as resolveAgentPluginPaths,h5 as requestHubShutdown,LN as requestDesktopToolApproval,n1 as rememberRecoverableLocalHubUrl,ZY as registerRemoteConfigSessionBlobUpload,Cf as registerMcpServersFromSettingsFile,pu as registerDisposable,kN as refreshProviderModelsFromSource,O6 as refreshOpenAICodexToken,M6 as refreshOcaToken,U6 as refreshClineToken,S9 as readSessionCheckpointHistory,VN as readRemoteConfigSessionBlobUploadMetadata,B0 as readHubDiscovery,Q$ as readGlobalSettings,F0 as probeHubServer,Rm as probeHubConnection,QZ as prewarmFileIndex,rW as prewarmDetachedHubServer,KN as prepareRemoteConfigCoreIntegration,s6 as parseWorkflowConfigFromMarkdown,lu as parseUserCommandEnvelope,a6 as parseSkillConfigFromMarkdown,YQ as parseSettings,t6 as parseRuleConfigFromMarkdown,E4 as parseHookEventPayload,jV as openaiCodexOAuthProvider,j1 as normalizeWorkspacePath,du as normalizeUserInput,uu as normalizeSdkError,P0 as normalizeRuntimeCapabilities,l2 as normalizeProviderId,WV as normalizeOpenAICodexCredentials,IN as normalizeOAuthProvider,a1 as normalizeHubWebSocketUrl,cu as noopBasicLogger,M9 as migrateLegacyProviderSettings,s2 as mergeRulesForSystemPrompt,P2 as mergeAgentHooks,D5 as makeTeamTaskSubSessionId,p8 as makeSubSessionId,I2 as loginOpenAICodex,g2 as loginOcaOAuth,gN as loginLocalProvider,b2 as loginClineOAuth,Mu as loadOpenTelemetryAdapter,Mf as loadMcpSettingsFile,VT as loadLlmsConfigFromFile,W1 as loadAgentPluginsFromPathsWithDiagnostics,c3 as loadAgentPluginsFromPaths,dJ as loadAgentPluginFromPath,qD as listSessionHistoryFromBackend,nJ as listPluginTools,wJ as listMcpServerOAuthStatuses,EN as listLocalProviders,e1 as listHookConfigFiles,dG as isToolDisabledGlobally,hJ as isTelemetryOptedOutGlobally,yQ as isRuleEnabled,lG as isPluginDisabledGlobally,ZV as isOpenAICodexTokenExpired,gR as isHubReconnectableTransportError,$j as isHubCommandTimeoutError,nE as isDiscoveryFilePresent,_7 as isClineAccountActionRequest,ZA as isBuiltInProviderId,D$ as identifyAccount,Z1 as hasMcpSettingsFile,z6 as getValidOpenAICodexCredentials,q6 as getValidOcaCredentials,L6 as getValidClineCredentials,dN as getProviderConfigFields,o7 as getProviderConfig,wf as getMcpServerOAuthState,hN as getLocalProviderModels,d2 as getLiveModelsCatalog,e$ as getFileIndex,CL as getCurrentContextSize,NJ as getCoreHeadlessToolNames,tZ as getCoreDefaultEnabledToolIds,_f as getCoreBuiltinToolCatalog,oZ as getCoreAcpToolNames,Cu as getClineDefaultSystemPrompt,$5 as generateWorkspaceInfoWithDiagnostics,d8 as generateWorkspaceInfo,l7 as generateOcaOpcRequestId,t2 as formatRulesForSystemPrompt,vu as formatDisplayUserInput,IJ as filterExtensionToolRegistrations,d1 as filterDisabledTools,kJ as filterDisabledPluginPaths,jT as fetchClineRecommendedModels,y7 as executeClineAccountAction,$Y as ensureHubWebSocketServer,yc as ensureHubServer,Ah as ensureDetachedHubServer,MX as ensureCustomProvidersLoaded,J2 as ensureCompatibleLocalHubUrl,B8 as enrichPromptWithMentions,mu as emptyWorkspaceManifest,$f as emptyStoredProviderSettings,iJ as discoverPluginModulePaths,R5 as deriveSubsessionStatus,BY as deleteLocalProvider,YT as defineLlmsConfig,QJ as createWorkflowsConfigDefinition,v1 as createUserInstructionConfigService,XZ as createToolPoliciesWithPreset,gu as createTool,pX as createTeamName,WH as createSubprocessHooks,m1 as createSpawnAgentTool,fJ as createSkillsConfigDefinition,S4 as createSessionHost,S4 as createRuntimeHost,JJ as createRulesConfigDefinition,BN as createRemoteConfigSessionMessagesArtifactUploader,XA as createProviderConfig,m4 as createOpenTelemetryTelemetryService,MV as createOcaRequestHeaders,TV as createOcaOAuthProvider,e4 as createOAuthClientCallbacks,S8 as createMcpTools,Sm as createLocalHubScheduleRuntimeHandlers,LT as createLlmsSdk,K0 as createInitialAccumulatedUsage,iE as createInMemoryHubOwnerContext,j$ as createHubServerUrl,cW as createHubAuthToken,O9 as createHookConfigFileHooks,R4 as createHookConfigFileExtension,D4 as createHookAuditHooks,EJ as createDisabledMcpToolPolicy,z3 as createDisabledMcpToolPolicies,R8 as createDelegatedAgentConfigProvider,U8 as createDelegatedAgent,HZ as createDefaultToolsWithPreset,I1 as createDefaultTools,q8 as createDefaultMcpServerClientFactory,F8 as createDefaultExecutors,gf as createCoreSettingsService,h$ as createCoreSessionSnapshot,xu as createContributionRegistry,B9 as createContextCompactionPrepareTurn,_1 as createConfiguredTelemetryService,v4 as createConfiguredTelemetryHandle,Iu as createClineTelemetryServiceMetadata,ku as createClineTelemetryServiceConfig,oY as createClineOAuthProvider,yf as createBuiltinTools,zf as createAgentTeamsTools,ld as createAgentRuntime,K4 as createAgentHooksExtension,VH as connectToHub,sY as completeClineDeviceAuth,fA as clearPrivateModelsCatalogCache,$A as clearLiveModelsCatalogCache,n0 as clearHubDiscovery,xY as captureWorkspacePathResolved,$6 as captureWorkspaceInitialized,f6 as captureWorkspaceInitError,j6 as captureToolUsage,Z6 as captureTokenUsage,Q6 as captureTaskRestarted,J6 as captureTaskCreated,q2 as captureTaskCompleted,S2 as captureSubagentExecution,X6 as captureSkillUsed,bu as captureSdkError,w2 as captureProviderApiError,W6 as captureModeSwitch,Y6 as captureMentionUsed,A6 as captureMentionSearchResults,V6 as captureMentionFailed,K6 as captureHookDiscovery,IY as captureExtensionActivated,H6 as captureDiffEditFailure,Hf as captureConversationTurnEvent,P$ as captureAuthSucceeded,G$ as captureAuthStarted,r$ as captureAuthLoggedOut,F$ as captureAuthFailed,B6 as captureAgentTeamCreated,i$ as captureAgentCreated,f5 as buildWorkspaceMetadata,j4 as buildTeamProgressSummary,Eu as buildSdkErrorProperties,JY as buildRemoteConfigSessionBlobUploadMetadata,Lf as buildDelegatedAgentConfig,z8 as bootstrapAgentTeams,B3 as authorizeMcpServerOAuth,CN as addLocalProvider,H0 as accumulateUsageTotals,p6 as WORKFLOWS_CONFIG_DIRECTORY_NAME,Bf as UnifiedConfigFileWatcher,p0 as ToolPresets,z2 as TelemetryService,g4 as TelemetryLoggerSink,O8 as TEAM_TOOL_NAMES,k8 as SubprocessSandbox,L4 as StoredProviderSettingsSchema,YX as StoredProviderSettingsEntrySchema,D2 as SqliteTeamStore,k$ as SqliteSessionStore,Qf as SessionVersioningService,v0 as SessionVersioningError,G0 as SessionSource,jQ as SapSettingsSchema,l6 as SKILLS_CONFIG_DIRECTORY_NAME,v6 as SESSION_STATUSES,ru as SDK_ERROR_TELEMETRY_EVENT,o4 as RpcClineAccountService,$4 as RemoteRuntimeHost,JQ as ReasoningSettingsSchema,RQ as RULES_CONFIG_DIRECTORY_NAME,QY as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,E1 as ProviderSettingsSchema,c$ as ProviderSettingsManager,e7 as ProviderProtocolSchema,m6 as ProviderIdSchema,$Q as ProviderClientSchema,_2 as OpenTelemetryProvider,XQ as OcaSettingsSchema,I6 as OPENAI_COMPATIBLE_PROVIDERS,X$ as NodeHubClient,H7 as NativeHubTransportAdapter,HQ as ModelCatalogSettingsSchema,u$ as LocalRuntimeHost,wu as Llms,O4 as InMemoryWorkspaceManager,Ef as InMemoryMcpManager,Wy as HubUIClient,h0 as HubTransportError,Zy as HubSessionClient,i4 as HubServerTransport,x4 as HubScheduleService,b4 as HubScheduleCommandService,G1 as HubRuntimeHost,o8 as HubCommandError,QH as HookEventPayloadSchema,JH as HookEventNameSchema,G4 as HookConfigFileName,F9 as HOOK_CONFIG_FILE_EVENT_MAP,$X as HOOKS_CONFIG_DIRECTORY_NAME,C8 as GlobalSettingsSchema,ZQ as GcpSettingsSchema,KY as FileTeamPersistenceStore,LY as FALLBACK_CLINE_RECOMMENDED_MODELS,Z0 as DefaultToolNames,M4 as DefaultRuntimeBuilder,R7 as DefaultLlmsSdk,a7 as DEFAULT_MODELS_CATALOG_URL,sD as DEFAULT_HUB_PORT,oD as DEFAULT_HUB_PATHNAME,tD as DEFAULT_HUB_HOST,r1 as CoreSettingsService,I$ as CoreSessionService,hu as ContributionRegistry,r9 as ClineCore,s4 as ClineAccountService,oN as ChatViewStateSchema,RY as ChatSummarySchema,PY as ChatSessionStatusSchema,GY as ChatSessionConfigSchema,DY as ChatMessageSchema,FY as ChatMessageRoleSchema,g as CORE_TELEMETRY_EVENTS,eN as CORE_BUILD_VERSION,X7 as BrowserWebSocketHubAdapter,QA as BUILT_IN_PROVIDER_IDS,g6 as BUILT_IN_PROVIDER,WQ as AzureSettingsSchema,QQ as AwsSettingsSchema,fQ as AuthSettingsSchema,X2 as AgentTeamsRuntime,i5 as AgentTeam,dd as Agent,b1 as ALL_DEFAULT_TOOL_NAMES};
713
+ `),$.end()}catch{$.destroy()}}function PY($,f){if(!$||!f)return!1;let J=Buffer.from($,"utf8"),Q=Buffer.from(f,"utf8");return J.length===Q.length&&yT(J,Q)}function UY($,f){let J=$&&typeof $==="object"&&"code"in $&&typeof $.code==="string"?$.code:void 0,Q=$ instanceof Error?$.message:typeof $==="string"?$:"Unknown startup error",Z=`Failed to start hub server on ${f.host}:${f.port}${f.pathname}: ${Q}`,W=Error(J?`${Z} (${J})`:Z);if(J)$.code=J,W.code=J;if($ instanceof Error&&$.stack)W.stack=`${W.name}: ${W.message}
714
+ Caused by: ${$.stack}`;return W}async function IT($){return await new Promise((f,J)=>{let Q=ST.createServer();Q.once("error",J),Q.listen(0,$,()=>{let Z=Q.address();if(!Z||typeof Z==="string"){Q.close(()=>J(Error("Failed to resolve free port")));return}let W=Z.port;Q.close((j)=>{if(j){J(j);return}f(W)})})})}function xT($){return $ instanceof Error&&"code"in $&&$.code==="EADDRINUSE"}var _7=new Map,DY="cline-hub-auth.",mT=30000;function RY($){return Array.isArray($)?$.join(","):$??""}function gT($){let f=RY($).trim();return/^Bearer\s+(.+)$/i.exec(f)?.[1]?.trim()||null}function vT($){for(let f of RY($).split(",")){let J=f.trim();if(J.startsWith(DY))return J.slice(DY.length).trim()||null}return null}async function N7($){let f=$.owner??K1(),J=$.host??"127.0.0.1",Q=$.pathname??"/hub",Z=$.port??Z6(),W=Z===0?await IT(J):Z,j=W,X=j$(J,W,Q),H=t1(),Y=Qj(),V=new Qf($);await V.start();let A=new O7(new z7(V),$.telemetry),B=new Set,G=new Date().toISOString(),K={protocolVersion:"v1",buildId:H,pid:process.pid,startedAt:G},D=new Set,F,P,U=async()=>{if(P)return P;return P=(async()=>{if(F)clearInterval(F),F=void 0;for(let L of D)L.terminate?.();D.clear();for(let L of B)L();if(B.clear(),await new Promise((L,N)=>{_.close((M)=>{if(M){N(M);return}L()})}),await new Promise((L,N)=>{z.close((M)=>{if(M){N(M);return}L()})}),await V.stop(),(await A0(f.discoveryPath))?.url===X)await n0(f.discoveryPath)})(),P},z=wT.createServer((R,L)=>{if((R.url??"/")==="/health"){let M=JSON.stringify({hubId:V.getHubId(),...K,authToken:"",host:J,port:j,url:X,updatedAt:new Date().toISOString()});L.statusCode=200,L.setHeader("content-type","application/json"),L.end(M);return}if((R.url??"/")==="/version"){L.statusCode=200,L.setHeader("content-type","application/json"),L.end(JSON.stringify(K));return}if(new FY(R.url??"/",`http://${J}:${j}`).pathname==="/shutdown"&&R.method==="POST"){if(!PY(gT(R.headers.authorization),Y)){L.statusCode=401,L.end("Unauthorized");return}L.statusCode=202,L.setHeader("content-type","application/json"),L.end(JSON.stringify({ok:!0})),queueMicrotask(()=>{U()});return}L.statusCode=404,L.end("Not found")}),_=new hT({noServer:!0});F=setInterval(()=>{for(let R of D){if(R.isAlive===!1){try{R.terminate?.()}catch{}D.delete(R);continue}R.isAlive=!1;try{R.ping?.()}catch{try{R.terminate?.()}catch{}D.delete(R)}}},mT),z.on("upgrade",(R,L,N)=>{if(new FY(R.url??"/",`http://${J}:${j}`).pathname!==Q){L.destroy();return}if(!PY(vT(R.headers["sec-websocket-protocol"]),Y)){kT(L);return}try{_.handleUpgrade(R,L,N,(o)=>{let e=o;e.isAlive=!0,e.on("pong",()=>{e.isAlive=!0}),D.add(e);let a=A.attach(ET(o));B.add(a),o.once("close",()=>{D.delete(e),a(),B.delete(a)})})}catch{bT(L)}});try{await new Promise((R,L)=>{z.once("error",(N)=>{L(UY(N,{host:J,port:W,pathname:Q}))}),z.listen(W,J,()=>{let N=z.address();if(!N||typeof N==="string"){L(UY(Error("Failed to resolve hub port"),{host:J,port:W,pathname:Q}));return}j=N.port,X=j$(J,j,Q),R()})})}catch(R){if(F)clearInterval(F),F=void 0;throw await V.stop().catch(()=>{return}),R}return await Zj(f.discoveryPath,{hubId:V.getHubId(),protocolVersion:"v1",buildId:H,authToken:Y,host:J,port:j,url:X,pid:process.pid,startedAt:G,updatedAt:G}),{host:J,port:j,url:X,authToken:Y,close:U}}async function LY($){let f=$.owner??K1(),J=$.host!==void 0||$.port!==void 0||$.pathname!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),Q=$.host??"127.0.0.1",Z=$.port??Z6(),W=$.pathname??"/hub",j=j$(Q,Z,W),X=f.discoveryPath,H=(V)=>{if(!J)s1(V.url,V.authToken);return V},Y=_7.get(X);if(Y){let V=await Y;if(V.url===j)return H({server:V,url:V.url,authToken:V.authToken,action:"reuse"})}return await Wj(f.discoveryPath,async()=>{let V=await A0(f.discoveryPath);if(V?.url&&(V.url===j||$.allowPortFallback===!0)){let K=await U0(V.url);if(K?.url&&await E$(K.url,{authToken:V.authToken}))return H({url:K.url,authToken:V.authToken,action:"reuse"})}if((await U0(j))?.url||V?.url)await n0(f.discoveryPath);let G=async(K)=>{let D=N7({...K,owner:f});_7.set(X,D);try{let F=await D;return H({server:F,url:F.url,authToken:F.authToken,action:"started"})}catch(F){throw _7.delete(X),F}};try{return await G($)}catch(K){if(!$.allowPortFallback||!xT(K))throw K;return await G({...$,port:0})}})}async function Kc($){let f=C$({host:$.host,port:$.port,pathname:$.pathname});return await N7({...$,...f,owner:D0()})}async function Fc($){let f=$.port!==void 0||!!process.env.CLINE_HUB_PORT?.trim(),J=C$({host:$.host,port:$.port,pathname:$.pathname});return await LY({...$,...J,allowPortFallback:$.allowPortFallback??!f,owner:D0()})}T7();import{buildRemoteConfigSessionBlobUploadMetadata as zY,clearRemoteConfigSessionBlobUpload as uT,createClineTelemetryServiceConfig as cT,createSessionId as dT,createRemoteConfigSessionMessagesArtifactUploader as lT,prepareRemoteConfigRuntime as pT,REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY as _Y,readRemoteConfigSessionBlobUploadMetadata as rT,registerRemoteConfigSessionBlobUpload as NY}from"@cline/shared";function iT($,f){let J=$.telemetry||f.telemetryService?{...f.telemetryService??{},...$.telemetry??{}}:void 0;if(!J)return;return T1(cT(J)).telemetry}function nT(){let $=lT();return{async uploadMessagesFile(f){await $.uploadMessagesFile(f)}}}async function aT($){let f=await pT($),J=iT(f,$),Q=[f.pluginDefinition],Z=f.claims?.subject,W=zY(f.bundle?.remoteConfig,Z),j;return{prepared:f,extensions:Q,telemetry:J,applyToStartSessionInput(X){let H=X.config.extensions??[],Y=X.config.telemetry,V=W?X.config.sessionId?.trim()||dT():X.config.sessionId;if(V&&W)j=V;let A=V&&W?NY(V,f.bundle?.remoteConfig,Z):void 0,B=A?{...X.sessionMetadata??{},[_Y]:A}:X.sessionMetadata;return{...X,...B?{sessionMetadata:B}:{},config:{...X.config,...V?{sessionId:V}:{},extensions:[...H,...Q],telemetry:J??Y}}},async dispose(){if(j)uT(j)}}}import{mkdir as tT,readFile as sT,unlink as oT,writeFile as eT}from"node:fs/promises";import{join as TY}from"node:path";function $M($){return $.replace(/[^a-zA-Z0-9._-]+/g,"_")}function fM($){return new Promise((f)=>setTimeout(f,$))}async function M7($){try{await oT($)}catch{}}async function JM($,f={}){let J=f.approvalDir?.trim(),Q=f.sessionId?.trim();if(!J||!Q)return{approved:!1,reason:"Desktop tool approval IPC is not configured"};await tT(J,{recursive:!0});let Z=$M(`${$.toolCallId}`),W=TY(J,`${Q}.request.${Z}.json`),j=TY(J,`${Q}.decision.${Z}.json`),X=f.nowIso??(()=>new Date().toISOString());await eT(W,`${JSON.stringify({requestId:Z,sessionId:Q,createdAt:X(),toolCallId:$.toolCallId,toolName:$.toolName,input:$.input,iteration:$.iteration,agentId:$.agentId,conversationId:$.conversationId},null,2)}
715
+ `,"utf8");let H=f.timeoutMs??300000,Y=f.pollIntervalMs??200,V=Date.now();while(Date.now()-V<H){try{let A=await sT(j,"utf8"),B=JSON.parse(A),G={approved:B.approved===!0,reason:typeof B.reason==="string"?B.reason:void 0};return await Promise.all([M7(j),M7(W)]),G}catch{}await fM(Y)}return await M7(W),{approved:!1,reason:"Tool approval request timed out"}}Z$();import*as R0 from"@cline/llms";import{getClineEnvironmentConfig as QM}from"@cline/shared";function ZM($){return $.apiKey??$.auth?.apiKey}function WM($){return($.auth?.accessToken?.trim()??"").length>0}function MY($){return $.split(/[-_]/).filter(Boolean).map((f)=>f.charAt(0).toUpperCase()+f.slice(1)).join(" ")}function jM($){let f=$.split(/\s+/).filter(Boolean);if(f.length===0)return"?";if(f.length===1)return f[0].slice(0,2).toUpperCase();return`${f[0][0]}${f[1][0]}`.toUpperCase()}function XM($){let f=["#c4956a","#6b8aad","#e8963a","#5b9bd5","#6bbd7b","#9b7dd4","#d07f68","#57a6a1"],J=0;for(let Q of $)J=J*31+Q.charCodeAt(0)>>>0;return f[J%f.length]}function qY($){return Object.entries($).sort(([f],[J])=>f.localeCompare(J)).map(([f,J])=>gX(f,J))}async function HM($,f){let J=await R0.getModelsForProvider($);if(!f)return J;let Q=await nf($,{loadPrivateOnAuth:!0,failOnError:!1},f);return Q?.knownModels?{...J,...Q.knownModels}:J}function q7($){return[...new Set(($??[]).map((f)=>f.trim()).filter(Boolean))]}function YM($){if(!$?.length)return;return[...new Set($)]}function VM($,f){return YM([...$??[],...f??[]])}function AM($){let f=$?.popularRank;return typeof f==="number"&&Number.isFinite(f)?f:Number.MAX_SAFE_INTEGER}function yY($){let f=Object.entries($??{}).filter(([J])=>J.trim().length>0);return f.length>0?Object.fromEntries(f):void 0}function y7($,f){let J=f?.includes("vision")??!1,Q=f?.includes("reasoning")??!1;return Object.fromEntries($.map((Z)=>[Z,{id:Z,name:Z,supportsVision:J,supportsAttachments:J,supportsReasoning:Q}]))}async function wY($){if(!$.shouldRecompute)return $.fallbackModelIds??[];let f=$.modelsSourceUrl?await c8($.modelsSourceUrl,$.providerId):[];return[...new Set([...$.explicitModels??[],...f])]}function SY($,f){let J=$.read(),Q=!1;if(J.providers[f])delete J.providers[f],Q=!0;if(J.lastUsedProvider===f)delete J.lastUsedProvider,Q=!0;if(Q)$.write(J);R0.unregisterProvider(f)}async function BM($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=f.baseUrl.trim(),Z=f.apiKey?.trim()??"";if(!Q&&!Z){let K=O1($);if((await Z2(K)).providers[J]){let F=await CY($,{providerId:J});return{providerId:J,settingsPath:F.settingsPath,modelsPath:F.modelsPath,modelsCount:0}}return SY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:K,modelsCount:0}}if(R0.hasProvider(J))throw Error(`provider "${J}" already exists`);let W=f.name.trim();if(!W)throw Error("name is required");if(!Q)throw Error("baseUrl is required");let j=q7(f.models),X=f.modelsSourceUrl?.trim(),H=await wY({providerId:J,explicitModels:j,modelsSourceUrl:X,shouldRecompute:!0});if(H.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let Y=f.defaultModelId?.trim()&&H.includes(f.defaultModelId.trim())?f.defaultModelId.trim():H[0],V=f.capabilities?.length?[...new Set(f.capabilities)]:void 0,A=yY(f.headers);$.saveProviderSettings({provider:J,apiKey:Z||void 0,baseUrl:Q,headers:A,timeout:f.timeoutMs,model:Y,protocol:f.protocol,client:f.client},{setLastUsed:!1});let B=O1($),G=await Z2(B);return G.providers[J]={provider:{name:W,baseUrl:Q,defaultModelId:Y,protocol:f.protocol,client:f.client,capabilities:V,modelsSourceUrl:X},models:y7(H,V)},await C6(B,G),R8(J,G.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:B,modelsCount:H.length}}async function hY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=O1($),Z=await Z2(Q),W=Z.providers[J];if(!W){let _=$.getProviderSettings(J);if(!_)throw Error(`provider "${J}" does not exist`);let R=f.modelsSourceUrl?.trim(),L=q7(f.models)[0]??_.model?.trim();if(!L&&!R)throw Error(`provider "${J}" cannot be updated because no model is configured`);W={provider:{name:f.name?.trim()||MY(J),baseUrl:f.baseUrl?.trim()??_.baseUrl?.trim()??"",defaultModelId:L,protocol:_.protocol,client:_.client,capabilities:_.capabilities},models:L?y7([L],_.capabilities):{}}}if(!W.provider)throw Error(`provider "${J}" cannot be updated because it is a model overlay (no provider metadata)`);let j=f.name?.trim()??W.provider.name.trim();if(!j)throw Error("name is required");let X=f.baseUrl?.trim()??W.provider.baseUrl.trim();if(!X)throw Error("baseUrl is required");let H=f.capabilities===void 0?W.provider.capabilities:f.capabilities===null?void 0:[...new Set(f.capabilities)],Y=f.protocol===void 0?W.provider.protocol:f.protocol??void 0,V=f.client===void 0?W.provider.client:f.client??void 0,A=q7(f.models),B=f.modelsSourceUrl===void 0?W.provider.modelsSourceUrl:f.modelsSourceUrl?.trim()||void 0,G=f.models!==void 0||f.modelsSourceUrl!==void 0&&!!B,K=Object.keys(W.models??{}).map((_)=>_.trim()).filter(Boolean),D=await wY({providerId:J,explicitModels:A,modelsSourceUrl:B,fallbackModelIds:K,shouldRecompute:G});if(D.length===0)throw Error("at least one model is required (manual or via modelsSourceUrl)");let F=f.defaultModelId===void 0?W.provider.defaultModelId?.trim():f.defaultModelId?.trim(),P=F&&D.includes(F)?F:D[0],z={...$.getProviderSettings(J)??{},provider:J,baseUrl:X,model:P};if(Y)z.protocol=Y;else delete z.protocol;if(V)z.client=V;else delete z.client;if(f.apiKey!==void 0){let _=f.apiKey?.trim()??"";if(_)z.apiKey=_;else delete z.apiKey}if(f.headers!==void 0){let _=yY(f.headers);if(_)z.headers=_;else delete z.headers}if(f.timeoutMs!==void 0)if(typeof f.timeoutMs==="number")z.timeout=f.timeoutMs;else delete z.timeout;return $.saveProviderSettings(z,{setLastUsed:!1}),Z.providers[J]={provider:{name:j,baseUrl:X,defaultModelId:P,protocol:Y,client:V,capabilities:H,modelsSourceUrl:B},models:y7(D,H)},await C6(Q,Z),R8(J,Z.providers[J]),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q,modelsCount:D.length}}async function CY($,f){let J=f.providerId.trim().toLowerCase();if(!J)throw Error("providerId is required");let Q=O1($),Z=await Z2(Q);if(!Z.providers[J])throw Error(`provider "${J}" does not exist`);return delete Z.providers[J],await C6(Q,Z),R0.unregisterProvider(J),SY($,J),{providerId:J,settingsPath:$.getFilePath(),modelsPath:Q}}async function GM($){let f=$.read(),J=R0.getProviderIds(),Q=await Promise.all(J.map(async(W)=>{let[j,X]=await Promise.all([R0.getProvider(W),R0.getModelsForProvider(W)]),H=qY(X),Y=f.providers[W]?.settings,V=j?.name??MY(W),A=VM(j?.capabilities,Y?.capabilities);return{provider:{id:W,name:V,models:H.length,color:XM(W),letter:jM(V),enabled:Boolean(Y),apiKey:Y?ZM(Y):void 0,oauthAccessTokenPresent:Y?WM(Y):void 0,baseUrl:Y?.baseUrl??j?.baseUrl,defaultModelId:j?.defaultModelId,protocol:Y?.protocol??j?.protocol,client:Y?.client??j?.client,capabilities:A,authDescription:"This provider uses API keys for authentication.",baseUrlDescription:"The base endpoint to use for provider requests.",modelList:H},rank:AM(j?.metadata)}}));return Q.sort((W,j)=>{if(W.rank!==j.rank)return W.rank-j.rank;return W.provider.name.localeCompare(j.provider.name)||W.provider.id.localeCompare(j.provider.id)}),{providers:Q.map((W)=>W.provider),settingsPath:$.getFilePath()}}async function KM($,f){let J=$.trim(),Q=await HM(J,f),Z=qY(Q);return{providerId:J,models:Z}}function FM($,f){let J=f.providerId.trim();if(f.enabled===!1){let W=$.read();if(delete W.providers[J],W.lastUsedProvider===J)delete W.lastUsedProvider;return $.write(W),{providerId:J,enabled:!1,settingsPath:$.getFilePath()}}let Z={...$.getProviderSettings(J)??{},provider:J};for(let W of["apiKey","baseUrl","model","region"])if(Object.hasOwn(f,W)&&typeof f[W]==="string")if(f[W].trim().length===0)delete Z[W];else Z[W]=f[W];for(let W of["maxTokens","contextWindow","timeout","apiLine","protocol","client","routingProviderId","capabilities"])if(Object.hasOwn(f,W))Z[W]=f[W];for(let W of["auth","headers","reasoning","aws","gcp","azure","sap","oca"])if(Object.hasOwn(f,W)&&f[W]!=null)Z[W]={...typeof Z[W]==="object"&&Z[W]!=null?Z[W]:{},...f[W]};return $.saveProviderSettings(Z,{setLastUsed:!1}),{providerId:J,enabled:!0,settingsPath:$.getFilePath()}}async function PM($,f){let J=f.trim(),Q=$.getProviderSettings(J),W=R0.MODEL_COLLECTIONS_BY_PROVIDER_ID[J]?.provider,j=Q?.baseUrl?.trim()||W?.baseUrl?.trim(),X=d8(j,W?.baseUrl,W?.modelsSourceUrl);if(!Q||!W||!j||!X)return{providerId:J,refreshed:!1};let H=await hY($,{providerId:J,name:W.name,baseUrl:j,apiKey:Q.apiKey,headers:Q.headers??null,timeoutMs:Q.timeout??null,modelsSourceUrl:X,protocol:Q.protocol??W.protocol??null,client:Q.client??W.client??null,capabilities:Q.capabilities??null});return{providerId:J,refreshed:!0,modelsCount:H.modelsCount}}function UM($){let f=$.trim().toLowerCase();if(f==="codex"||f==="openai-codex")return"openai-codex";if(f==="cline"||f==="oca")return f;throw Error(`provider "${$}" does not support OAuth login (supported: cline, oca, openai-codex)`)}function DM($,f){if($==="cline")return f.access.startsWith("workos:")?f.access:`workos:${f.access}`;return f.access}async function RM($,f,J,Q){let Z=Vf({onPrompt:async(W)=>W.defaultValue??"",openUrl:J,onOpenUrlError:({error:W})=>{throw W instanceof Error?W:Error(String(W))}});if($==="cline")return x8({apiBaseUrl:f?.baseUrl?.trim()||QM().apiBaseUrl,useWorkOSDeviceAuth:!0,callbacks:Z,telemetry:Q});if($==="oca")return u8({mode:f?.oca?.mode,callbacks:Z,telemetry:Q});return g8({onAuth:Z.onAuth,onPrompt:Z.onPrompt,onProgress:Z.onProgress,onManualCodeInput:Z.onManualCodeInput,telemetry:Q})}function LM($,f,J,Q){let Z={...J?.auth??{},accessToken:DM(f,Q),refreshToken:Q.refresh,accountId:Q.accountId,expiresAt:Q.expires},W={...J??{provider:f},provider:f,auth:Z};return $.saveProviderSettings(W,{tokenSource:"oauth"}),W}function OM($){let f=$?.auth?.accessToken?.trim()||$?.apiKey?.trim();return f&&f.length>0?f:void 0}import*as Zf from"@cline/llms";import{isOAuthProviderId as zM}from"@cline/shared";var _M=["apiKey","baseUrl","awsRegion","awsProfile"],NM={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."}}}};function TM($,f){let J={};for(let Q of _M){let Z=$[Q],W=f[Q];if(Z||W)J[Q]={...Z,...W}}return J}function MM($){let f=NM[$.providerId];if(!f)return $;return{...$,description:f.description??$.description,fields:f.mode==="replace"?f.fields:TM($.fields,f.fields)}}var qM=new Set(["ollama","lmstudio","litellm","openai-compatible"]);function yM($,f){if(!f?.provider.baseUrl)return!1;if(f.provider.source!=="system")return!0;return qM.has($)}function wM($){let f=Zf.normalizeProviderId($);if(zM(f))return{providerId:f,authMethod:"oauth",fields:{}};let J=Zf.MODEL_COLLECTIONS_BY_PROVIDER_ID[f];if(J?.provider.capabilities?.includes("local-auth"))return{providerId:f,authMethod:"local",fields:{}};let Q=J?.provider.baseUrl,Z={apiKey:{}};if(yM(f,J))Z.baseUrl={defaultValue:Q};return MM({providerId:f,authMethod:"api-key",fields:Z})}G0();s6();import{appendFileSync as SM,existsSync as w7,mkdirSync as hM,readFileSync as CM,renameSync as EM,unlinkSync as bM,writeFileSync as kM}from"node:fs";import{join as S7}from"node:path";import{resolveTeamDataDir as IM}from"@cline/shared/storage";function xM($){return $.toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/^-+|-+$/g,"")}class EY{dirPath;statePath;taskHistoryPath;teammateSpecs=new Map;constructor($){let f=xM($.teamName),J=$.baseDir?.trim()||IM();this.dirPath=S7(J,f),this.statePath=S7(this.dirPath,"state.json"),this.taskHistoryPath=S7(this.dirPath,"task-history.jsonl")}loadState(){if(!w7(this.statePath))return;try{let $=CM(this.statePath,"utf8"),f=JSON.parse($);if(f.version!==1||!f.teamState)return;for(let J of f.teammates??[])this.teammateSpecs.set(J.agentId,J);return pj(f.teamState)}catch{return}}getTeammateSpecs(){return Array.from(this.teammateSpecs.values())}upsertTeammateSpec($){this.teammateSpecs.set($.agentId,$)}removeTeammateSpec($){this.teammateSpecs.delete($)}persist($){if(!this.hasPersistableState($)){this.clearPersistedState();return}this.ensureDir();let f={version:1,updatedAt:new Date().toISOString(),teamState:$.exportState(),teammates:Array.from(this.teammateSpecs.values())},J=`${this.statePath}.tmp`;kM(J,`${JSON.stringify(f,null,2)}
716
+ `,"utf8"),EM(J,this.statePath)}appendTaskHistory($){let f={};switch($.type){case"team_task_updated":f=$.task;break;case"team_message":f={agentId:$.message.fromAgentId,toAgentId:$.message.toAgentId,subject:$.message.subject,taskId:$.message.taskId};break;case"team_mission_log":f={agentId:$.entry.agentId,kind:$.entry.kind,summary:$.entry.summary,taskId:$.entry.taskId};break;case"teammate_spawned":case"teammate_shutdown":case"task_start":f={agentId:$.agentId,message:"message"in $?$.message:void 0};break;case"task_end":f={agentId:$.agentId,finishReason:$.result?.finishReason,error:$.error?.message};break;case"agent_event":f={agentId:$.agentId,eventType:$.event.type};break}this.ensureDir(),SM(this.taskHistoryPath,`${JSON.stringify({ts:new Date().toISOString(),type:$.type,task:f})}
717
+ `,"utf8")}ensureDir(){if(!w7(this.dirPath))hM(this.dirPath,{recursive:!0})}hasPersistableState($){let f=$.exportState();if(this.teammateSpecs.size>0)return!0;if(f.members.some((J)=>J.role==="teammate"))return!0;return f.tasks.length>0||f.mailbox.length>0||f.missionLog.length>0}clearPersistedState(){if(w7(this.statePath))bM(this.statePath)}}import{z as y}from"zod";var bY=y.object({workspaceRoot:y.string().min(1),cwd:y.string().optional(),provider:y.string().min(1),model:y.string().min(1),mode:y.enum(["act","plan"]).default("act"),apiKey:y.string(),systemPrompt:y.string().optional(),rules:y.string().optional(),maxIterations:y.number().int().positive().optional(),enableTools:y.boolean(),enableSpawn:y.boolean().optional(),enableTeams:y.boolean().optional(),autoApproveTools:y.boolean().optional(),missionStepInterval:y.number().int().positive().optional(),missionTimeIntervalMs:y.number().int().positive().optional()}),kY=y.enum(["idle","starting","running","pending","stopping","completed","cancelled","failed","error"]),IY=y.enum(["user","assistant","tool","system","status","error"]),xY=y.object({id:y.string().min(1),sessionId:y.string().nullable(),role:IY,content:y.string(),createdAt:y.number().int().nonnegative(),meta:y.object({stream:y.enum(["stdout","stderr"]).optional(),toolName:y.string().optional(),iteration:y.number().int().nonnegative().optional(),agentId:y.string().optional(),conversationId:y.string().optional(),hookEventName:y.string().optional(),inputTokens:y.number().int().nonnegative().optional(),outputTokens:y.number().int().nonnegative().optional(),checkpoint:y.object({ref:y.string(),createdAt:y.number().int().nonnegative(),runCount:y.number().int().positive(),kind:y.enum(["stash","commit"]).optional()}).optional()}).optional()}),mY=y.object({toolCalls:y.number().int().nonnegative(),tokensIn:y.number().int().nonnegative(),tokensOut:y.number().int().nonnegative()}),mM=y.object({sessionId:y.string().nullable(),status:kY,config:bY,messages:y.array(xY),rawTranscript:y.string(),error:y.string().nullable(),summary:mY});var gM=tW;import{Agent as xl,createAgentRuntime as ml}from"@cline/agents";import{getClineEnvironmentConfig as vM}from"@cline/shared";var uM=5000,vY={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 cM($){return{recommended:$.recommended.map((f)=>({...f,tags:[...f.tags]})),free:$.free.map((f)=>({...f,tags:[...f.tags]}))}}function gY($){if(!$||typeof $!=="object")return null;let f=$;if(typeof f.id!=="string"||f.id.length===0)return null;return{id:f.id,name:typeof f.name==="string"&&f.name.length>0?f.name:f.id,description:typeof f.description==="string"?f.description:"",tags:Array.isArray(f.tags)?f.tags.filter((J)=>typeof J==="string"):[]}}function dM($){if(!$||typeof $!=="object")return null;let f=$,J=Array.isArray(f.recommended)?f.recommended:[],Q=Array.isArray(f.free)?f.free:[],Z=J.map(gY).filter((j)=>j!==null),W=Q.map(gY).filter((j)=>j!==null);if(Z.length===0&&W.length===0)return null;return{recommended:Z,free:W}}function lM($){let f=$.baseUrl?.trim();if(f)return f;let J=vM().apiBaseUrl;try{return($.providerSettingsManager??new d$).getProviderSettings("cline")?.baseUrl?.trim()||J}catch{return J}}async function pM($,f,J){let Q=new AbortController,Z=setTimeout(()=>Q.abort(),J);try{return await $(f,{signal:Q.signal})}finally{clearTimeout(Z)}}async function rM($={}){try{let f=lM($),J=$.fetchImpl??fetch,Q=await pM(J,`${f}/api/v1/ai/cline/recommended-models`,$.timeoutMs??uM);if(!Q.ok)throw Error(`HTTP ${Q.status}`);let Z=await Q.json(),W=dM(Z);if(W)return W}catch{}return cM(vY)}import{readFile as iM}from"node:fs/promises";import nM from"node:path";function aM($){return $}async function tM($){let f=nM.resolve($),J=await iM(f,"utf8"),Q;try{Q=JSON.parse(J)}catch(Z){let W=Z instanceof Error?Z.message:String(Z);throw Error(`Failed to parse JSON config at "${f}": ${W}`)}return sM(Q,f)}function sM($,f){if(!$||typeof $!=="object")throw Error(`Invalid llms config in "${f}": expected an object.`);let Q=$.providers;if(!Array.isArray(Q))throw Error(`Invalid llms config in "${f}": "providers" must be an array.`);if(!Q.length)throw Error(`Invalid llms config in "${f}": "providers" cannot be empty.`);return $}import{BUILT_IN_PROVIDER_IDS as dY,createHandler as $q,createHandlerAsync as fq,getProviderCollection as Jq,hasProvider as lY,registerAsyncHandler as Qq,registerHandler as Zq,registerModel as Wq,registerProvider as pY}from"@cline/llms";function uY($){return $?{...$}:{}}function oM($,f){if($)return $;if(!f)return;let J=globalThis.process;if(!J?.env)return;return J.env[f]}function eM($,f){if(!f.length)throw Error(`Provider "${$}" must include at least one model.`)}function cY($){let f=Object.keys($.collection.models);return{id:$.collection.provider.id,name:$.collection.provider.name,description:$.collection.provider.description,protocol:$.collection.provider.protocol,baseUrl:$.collection.provider.baseUrl,capabilities:$.collection.provider.capabilities,env:$.collection.provider.env,models:f,defaultModel:$.collection.provider.defaultModelId,modelCount:f.length}}class h7{providers=new Map;register($){eM($.id,$.models);let f=$.defaultModel??$.models[0];if(!f)throw Error(`Provider "${$.id}" must define a default model.`);if(!$.models.includes(f))throw Error(`Default model "${f}" is not included in configured models for "${$.id}".`);let J=this.providers.get($.id);this.providers.set($.id,{id:$.id,models:new Set([...J?.models??[],...$.models]),defaultModel:f,defaults:{...J?.defaults??{},...uY($.defaults)}})}registerSelectionConfig($){this.register({id:$.id,models:$.models,defaultModel:$.defaultModel,defaults:{apiKey:oM($.apiKey,$.apiKeyEnv),routingProviderId:$.builtinProviderId,baseUrl:$.baseUrl,headers:$.headers,timeoutMs:$.timeoutMs,capabilities:$.capabilities,...uY($.settings)}})}registerModel($,f){let J=this.providers.get($);if(!J){this.providers.set($,{id:$,models:new Set([f]),defaultModel:f,defaults:{}});return}J.models.add(f)}createHandlerConfig($){let f=this.require($.providerId),J=$.modelId??f.defaultModel;if(!f.models.has(J))throw Error(`Model "${J}" is not configured for provider "${$.providerId}".`);return{providerId:$.providerId,modelId:J,...f.defaults,...$.overrides}}list(){return Array.from(this.providers.values()).map(($)=>({id:$.id,models:Array.from($.models),defaultModel:$.defaultModel}))}getModels($){return Array.from(this.require($).models)}hasProvider($){return this.providers.has($)}hasModel($,f){return this.providers.get($)?.models.has(f)??!1}require($){let f=this.providers.get($);if(!f)throw Error(`Provider "${$}" is not configured in this SDK instance.`);return f}}class C7{configuredProviders=new h7;constructor($){this.applyConfig($)}createHandler($){return $q(this.configuredProviders.createHandlerConfig($))}async createHandlerAsync($){return fq(this.configuredProviders.createHandlerConfig($))}registerProvider($){if(pY($.collection),$.handlerFactory&&$.asyncHandlerFactory)throw Error(`Provider "${$.collection.provider.id}" cannot register both sync and async handlers.`);if($.handlerFactory)Zq($.collection.provider.id,$.handlerFactory);if($.asyncHandlerFactory)Qq($.collection.provider.id,$.asyncHandlerFactory);this.configuredProviders.register({id:$.collection.provider.id,models:$.exposeModels??Object.keys($.collection.models),defaultModel:$.defaultModel??$.collection.provider.defaultModelId,defaults:$.defaults})}registerBuiltinProvider($){let f=$.exposeModels??Object.keys($.models),J=$.defaultModel??f[0];if(!J)throw Error(`Provider "${$.id}" must define a default model.`);pY({provider:{id:$.id,name:$.name??$.id,description:$.description,protocol:$.protocol,baseUrl:$.baseUrl,defaultModelId:J,client:$.client??"openai-compatible",capabilities:$.capabilities,env:$.env,source:"system"},models:$.models}),this.configuredProviders.register({id:$.id,models:f,defaultModel:J,defaults:{routingProviderId:$.builtinProviderId,...$.defaults??{}}})}registerModel($){Wq($.providerId,$.modelId,$.info),this.configuredProviders.registerModel($.providerId,$.modelId)}getProviders(){return this.configuredProviders.list()}getBuiltInProviderIds(){return[...dY]}async getBuiltInProviders(){return(await Promise.all(dY.map((f)=>Jq(f)))).filter((f)=>f!==void 0).map((f)=>cY({collection:f}))}getModels($){return this.configuredProviders.getModels($)}isProviderConfigured($){return this.configuredProviders.hasProvider($)}isModelConfigured($,f){return this.configuredProviders.hasModel($,f)}applyConfig($){for(let f of $.providers)this.configuredProviders.registerSelectionConfig(f);for(let f of $.models??[])this.registerModel(f);for(let f of $.customProviders??[])this.registerProvider(f);for(let f of this.configuredProviders.list()){let J=lY(f.id),Q=this.configuredProviders.createHandlerConfig({providerId:f.id,modelId:f.defaultModel}).routingProviderId,Z=typeof Q==="string"&&lY(Q);if(!J&&!Z)throw Error(`Provider "${f.id}" is not known. Register it through customProviders/registerProvider, registerBuiltinProvider, or use a built-in provider ID.`)}}}function jq($){return new C7($)}j7();async function Ld(){return Promise.resolve().then(() => (T7(),OY))}export{Zj as writeHubDiscovery,I2 as writeGlobalSettings,Wj as withHubStartupLock,E$ as verifyHubConnection,C2 as updateMcpServerOAuthState,hY as updateLocalProvider,A7 as truncateNotificationBody,pJ as toggleDisabledTool,F6 as toTeamProgressLifecycleEvent,$$ as toProviderConfig,wD as toHubHealthUrl,S9 as toHookConfigFileName,L6 as summarizeUsageFromMessages,hR as stopLocalHubServerGracefully,e0 as startLocalOAuthServer,N7 as startHubWebSocketServer,Kc as startHubServer,UV as startClineDeviceAuth,H5 as splitCoreSessionConfig,W6 as spawnDetachedHubServerWithRetry,VR as spawnDetachedHubServer,UF as setTelemetryOptOutGlobally,S2 as setMcpServerDisabled,v3 as setDisabledTools,LF as setDisabledPlugin,Vv as sendHubCommand,FM as saveLocalProviderSettings,LM as saveLocalProviderOAuthCredentials,s2 as sanitizeSessionToken,TQ as safeParseSettings,qA as safeCreateProviderConfig,u6 as runSubprocessEvent,d6 as runHook,H3 as reviveTeamStateDates,Dj as restartLocalHubIfIdleAfterStartupTimeout,uE as resolveWorkspaceHubOwnerContext,AJ as resolveWorkflowsConfigSearchPaths,YJ as resolveSkillsConfigSearchPaths,D0 as resolveSharedHubOwnerContext,d_ as resolveSessionBackend,VJ as resolveRulesConfigSearchPaths,nf as resolveProviderConfig,W5 as resolvePluginConfigSearchPaths,M$ as resolveMcpServerRegistrations,OM as resolveLocalClineAuthToken,IN as resolveHubUrl,K1 as resolveHubOwnerContext,C$ as resolveHubEndpointOptions,t1 as resolveHubBuildId,y9 as resolveHooksConfigSearchPaths,Q$ as resolveDisabledToolNames,v4 as resolveDisabledPluginPaths,C0 as resolveDefaultMcpSettingsPath,Z6 as resolveDefaultHubPort,vD as resolveDefaultHubPathname,gD as resolveDefaultHubHost,B3 as resolveCoreSelectedToolIds,s5 as resolveCompatibleLocalHubUrl,CE as resolveClineDir,p5 as resolveClineDataDir,r4 as resolveAndLoadAgentPlugins,v2 as resolveAgentPluginPaths,r5 as requestHubShutdown,JM as requestDesktopToolApproval,s1 as rememberRecoverableLocalHubUrl,NY as registerRemoteConfigSessionBlobUpload,E2 as registerMcpServersFromSettingsFile,md as registerDisposable,PM as refreshProviderModelsFromSource,bf as refreshOpenAICodexToken,vf as refreshOcaToken,Cf as refreshClineToken,d9 as readSessionCheckpointHistory,rT as readRemoteConfigSessionBlobUploadMetadata,A0 as readHubDiscovery,J$ as readGlobalSettings,U0 as probeHubServer,Yv as probeHubConnection,DZ as prewarmFileIndex,Hj as prewarmDetachedHubServer,aT as prepareRemoteConfigCoreIntegration,HJ as parseWorkflowConfigFromMarkdown,xd as parseUserCommandEnvelope,jJ as parseSkillConfigFromMarkdown,NQ as parseSettings,XJ as parseRuleConfigFromMarkdown,c6 as parseHookEventPayload,qV as openaiCodexOAuthProvider,Y1 as normalizeWorkspacePath,Id as normalizeUserInput,kd as normalizeSdkError,P0 as normalizeRuntimeCapabilities,t8 as normalizeProviderId,MV as normalizeOpenAICodexCredentials,UM as normalizeOAuthProvider,o1 as normalizeHubWebSocketUrl,bd as noopBasicLogger,v9 as migrateLegacyProviderSettings,Q4 as mergeRulesForSystemPrompt,D8 as mergeAgentHooks,S5 as makeTeamTaskSubSessionId,e4 as makeSubSessionId,g8 as loginOpenAICodex,u8 as loginOcaOAuth,RM as loginLocalProvider,x8 as loginClineOAuth,Ld as loadOpenTelemetryAdapter,w2 as loadMcpSettingsFile,tM as loadLlmsConfigFromFile,g2 as loadAgentPluginsFromPathsWithDiagnostics,fW as loadAgentPluginsFromPaths,f5 as loadAgentPluginFromPath,KD as listSessionHistoryFromBackend,HW as listPluginToolsWithDiagnostics,X5 as listPluginTools,vJ as listMcpServerOAuthStatuses,GM as listLocalProviders,J2 as listHookConfigFiles,DF as isToolDisabledGlobally,lJ as isTelemetryOptedOutGlobally,gQ as isRuleEnabled,RF as isPluginDisabledGlobally,TV as isOpenAICodexTokenExpired,NR as isHubReconnectableTransportError,Pj as isHubCommandTimeoutError,kE as isDiscoveryFilePresent,x7 as isClineAccountActionRequest,_A as isBuiltInProviderId,U$ as identifyAccount,X1 as hasMcpSettingsFile,kf as getValidOpenAICodexCredentials,uf as getValidOcaCredentials,Ef as getValidClineCredentials,wM as getProviderConfigFields,GQ as getProviderConfig,h2 as getMcpServerOAuthState,KM as getLocalProviderModels,a8 as getLiveModelsCatalog,J1 as getFileIndex,PO as getCurrentContextSize,IJ as getCoreHeadlessToolNames,A3 as getCoreDefaultEnabledToolIds,T2 as getCoreBuiltinToolCatalog,G3 as getCoreAcpToolNames,Nd as getClineDefaultSystemPrompt,G5 as generateWorkspaceInfoWithDiagnostics,s4 as generateWorkspaceInfo,ZQ as generateOcaOpcRequestId,J4 as formatRulesForSystemPrompt,Ed as formatDisplayUserInput,iJ as filterExtensionToolRegistrations,l1 as filterDisabledTools,rJ as filterDisabledPluginPaths,rM as fetchClineRecommendedModels,m7 as executeClineAccountAction,LY as ensureHubWebSocketServer,Fc as ensureHubServer,oE as ensureDetachedHubServer,rX as ensureCustomProvidersLoaded,W8 as ensureCompatibleLocalHubUrl,D4 as enrichPromptWithMentions,Cd as emptyWorkspaceManifest,Q2 as emptyStoredProviderSettings,j5 as discoverPluginModulePaths,h5 as deriveSubsessionStatus,CY as deleteLocalProvider,aM as defineLlmsConfig,KJ as createWorkflowsConfigDefinition,c1 as createUserInstructionConfigService,zZ as createToolPoliciesWithPreset,hd as createTool,VH as createTeamName,NH as createSubprocessHooks,u1 as createSpawnAgentTool,BJ as createSkillsConfigDefinition,v6 as createSessionHost,v6 as createRuntimeHost,GJ as createRulesConfigDefinition,nT as createRemoteConfigSessionMessagesArtifactUploader,MA as createProviderConfig,a6 as createOpenTelemetryTelemetryService,nV as createOcaRequestHeaders,iV as createOcaOAuthProvider,Vf as createOAuthClientCallbacks,I4 as createMcpTools,Ov as createLocalHubScheduleRuntimeHandlers,jq as createLlmsSdk,B0 as createInitialAccumulatedUsage,bE as createInMemoryHubOwnerContext,j$ as createHubServerUrl,Qj as createHubAuthToken,b9 as createHookConfigFileHooks,M6 as createHookConfigFileExtension,T6 as createHookAuditHooks,dJ as createDisabledMcpToolPolicy,x3 as createDisabledMcpToolPolicies,N4 as createDelegatedAgentConfigProvider,T4 as createDelegatedAgent,_Z as createDefaultToolsWithPreset,m1 as createDefaultTools,b4 as createDefaultMcpServerClientFactory,z4 as createDefaultExecutors,c2 as createCoreSettingsService,b$ as createCoreSessionSnapshot,Sd as createContributionRegistry,T9 as createContextCompactionPrepareTurn,T1 as createConfiguredTelemetryService,t6 as createConfiguredTelemetryHandle,wd as createClineTelemetryServiceMetadata,yd as createClineTelemetryServiceConfig,RV as createClineOAuthProvider,M2 as createBuiltinTools,N2 as createAgentTeamsTools,ml as createAgentRuntime,O6 as createAgentHooksExtension,wH as connectToHub,DV as completeClineDeviceAuth,LA as clearPrivateModelsCatalogCache,RA as clearLiveModelsCatalogCache,n0 as clearHubDiscovery,QV as captureWorkspacePathResolved,Af as captureWorkspaceInitialized,Bf as captureWorkspaceInitError,Uf as captureToolUsage,Ff as captureTokenUsage,Kf as captureTaskRestarted,Gf as captureTaskCreated,h8 as captureTaskCompleted,E8 as captureSubagentExecution,Df as captureSkillUsed,qd as captureSdkError,ZV as captureProviderConfigured,C8 as captureProviderApiError,Pf as captureModeSwitch,Lf as captureMentionUsed,zf as captureMentionSearchResults,Of as captureMentionFailed,Nf as captureHookDiscovery,JV as captureExtensionActivated,Rf as captureDiffEditFailure,A2 as captureConversationTurnEvent,Mf as captureCompactionSkipped,Tf as captureCompactionExecuted,F$ as captureAuthSucceeded,K$ as captureAuthStarted,n$ as captureAuthLoggedOut,P$ as captureAuthFailed,_f as captureAgentTeamCreated,a$ as captureAgentCreated,K5 as buildWorkspaceMetadata,K6 as buildTeamProgressSummary,Td as buildSdkErrorProperties,zY as buildRemoteConfigSessionBlobUploadMetadata,z2 as buildDelegatedAgentConfig,y4 as bootstrapAgentTeams,q3 as authorizeMcpServerOAuth,BM as addLocalProvider,H0 as accumulateUsageTotals,JJ as WORKFLOWS_CONFIG_DIRECTORY_NAME,K2 as UnifiedConfigFileWatcher,r0 as ToolPresets,T8 as TelemetryService,n6 as TelemetryLoggerSink,q4 as TEAM_TOOL_NAMES,c4 as SubprocessSandbox,y6 as StoredProviderSettingsSchema,qX as StoredProviderSettingsEntrySchema,L8 as SqliteTeamStore,x$ as SqliteSessionStore,j2 as SessionVersioningService,d0 as SessionVersioningError,F0 as SessionSource,OQ as SapSettingsSchema,fJ as SKILLS_CONFIG_DIRECTORY_NAME,sf as SESSION_STATUSES,gd as SDK_ERROR_TELEMETRY_EVENT,Yf as RpcClineAccountService,H6 as RemoteRuntimeHost,UQ as ReasoningSettingsSchema,EQ as RULES_CONFIG_DIRECTORY_NAME,_Y as REMOTE_CONFIG_SESSION_BLOB_UPLOAD_METADATA_KEY,b1 as ProviderSettingsSchema,d$ as ProviderSettingsManager,KQ as ProviderProtocolSchema,tf as ProviderIdSchema,FQ as ProviderClientSchema,M8 as OpenTelemetryProvider,zQ as OcaSettingsSchema,rf as OPENAI_COMPATIBLE_PROVIDERS,X$ as NodeHubClient,z7 as NativeHubTransportAdapter,_Q as ModelCatalogSettingsSchema,l$ as LocalRuntimeHost,zd as Llms,w6 as InMemoryWorkspaceManager,b2 as InMemoryMcpManager,uN as HubUIClient,I0 as HubTransportError,vN as HubSessionClient,Qf as HubServerTransport,i6 as HubScheduleService,l6 as HubScheduleCommandService,P1 as HubRuntimeHost,j6 as HubCommandError,zH as HookEventPayloadSchema,OH as HookEventNameSchema,z6 as HookConfigFileName,w9 as HOOK_CONFIG_FILE_EVENT_MAP,DX as HOOKS_CONFIG_DIRECTORY_NAME,g4 as GlobalSettingsSchema,RQ as GcpSettingsSchema,EY as FileTeamPersistenceStore,vY as FALLBACK_CLINE_RECOMMENDED_MODELS,W0 as DefaultToolNames,x6 as DefaultRuntimeBuilder,C7 as DefaultLlmsSdk,VQ as DEFAULT_MODELS_CATALOG_URL,xD as DEFAULT_HUB_PORT,mD as DEFAULT_HUB_PATHNAME,ID as DEFAULT_HUB_HOST,a1 as CoreSettingsService,m$ as CoreSessionService,Md as ContributionRegistry,W7 as ClineCore,Hf as ClineAccountService,mM as ChatViewStateSchema,mY as ChatSummarySchema,kY as ChatSessionStatusSchema,bY as ChatSessionConfigSchema,xY as ChatMessageSchema,IY as ChatMessageRoleSchema,k as CORE_TELEMETRY_EVENTS,gM as CORE_BUILD_VERSION,O7 as BrowserWebSocketHubAdapter,zA as BUILT_IN_PROVIDER_IDS,af as BUILT_IN_PROVIDER,LQ as AzureSettingsSchema,DQ as AwsSettingsSchema,PQ as AuthSettingsSchema,V8 as AgentTeamsRuntime,j9 as AgentTeam,xl as Agent,I1 as ALL_DEFAULT_TOOL_NAMES};